El miniSMU MS01 puede controlarse mediante programación con la biblioteca oficial de Python, minismu_py. Esta interfaz ofrece una forma cómoda de automatizar mediciones, realizar secuencias de prueba complejas e integrar el miniSMU en sus aplicaciones personalizadas y sus flujos de trabajo de investigación.
Instalación
Instale la biblioteca minismu_py directamente desde PyPI con pip:
pip install minismu_py
La biblioteca tiene pocas dependencias y requiere:
- Python 3.6 o posterior
- El paquete pyserial, para las conexiones USB
- El paquete tqdm (opcional, se utiliza para las barras de progreso de los ejemplos)
Con el firmware 2.0, use minismu_py 0.4.2 o posterior. Las versiones anteriores esperan la respuesta durante un segundo, por lo que los comandos lentos, como la búsqueda de redes wifi, fallan con el firmware 2.0.
Primeros pasos
Conexión básica
Para empezar a utilizar la interfaz de Python, primero debe establecer una conexión con su miniSMU MS01:
from minismu_py import SMU, ConnectionType
# For USB connection
smu = SMU(ConnectionType.USB, port="/dev/ttyACM0") # Linux/Mac
# or
smu = SMU(ConnectionType.USB, port="COM3") # Windows
# For WiFi connection
smu = SMU(ConnectionType.NETWORK, host="192.168.1.100", tcp_port=3333)
# Verify connection
print("Device Info:", smu.get_identity())
Uso del gestor de contexto
La clase SMU admite el protocolo de gestores de contexto de Python, que se encarga automáticamente de liberar los recursos:
from minismu_py import SMU, ConnectionType
# Using context manager ensures proper cleanup
with SMU(ConnectionType.USB, port="COM3") as smu:
# Work with the SMU
print("Device Info:", smu.get_identity())
# No need to explicitly close the connection
# It will be closed automatically when exiting the 'with' block
Ejemplo de medición básica
Este es un ejemplo sencillo que configura un canal, establece una tensión y realiza mediciones:
from minismu_py import SMU, ConnectionType
import time
with SMU(ConnectionType.USB, port="COM3") as smu:
# Configure channel 1
smu.set_mode(1, "FVMI") # Force Voltage, Measure Current mode
smu.set_voltage_range(1, "AUTO")
smu.enable_channel(1)
# Set voltage to 3.3V
smu.set_voltage(1, 3.3)
time.sleep(0.1) # Allow settling time
# Take measurements
voltage, current = smu.measure_voltage_and_current(1)
print(f"Voltage: {voltage:.6f}V")
print(f"Current: {current:.6f}A")
# Disable the channel when done
smu.disable_channel(1)
Conceptos clave
Tipos de conexión
La biblioteca admite dos métodos de conexión:
Conexión USB: conexión directa mediante un cable USB
smu = SMU(ConnectionType.USB, port="COM3")Conexión de red: conexión por wifi
smu = SMU(ConnectionType.NETWORK, host="192.168.1.100")
Modos de medición
El miniSMU admite dos modos de medición principales:
FVMI (Force Voltage, Measure Current: forzar tensión, medir corriente)
- Aplica una tensión especificada y mide la corriente resultante
- Adecuado para la caracterización de resistencias, las pruebas de diodos, etc.
smu.set_mode(1, "FVMI")FIMV (Force Current, Measure Voltage: forzar corriente, medir tensión)
- Aplica una corriente especificada y mide la tensión resultante
- Adecuado para las pruebas de LED, la caracterización de baterías, etc.
smu.set_mode(1, "FIMV")
Gestión de errores
La biblioteca incluye una gestión de excepciones propia mediante la clase SMUException:
from minismu_py import SMU, ConnectionType, SMUException
try:
with SMU(ConnectionType.USB, port="COM3") as smu:
# SMU operations
pass
except SMUException as e:
print(f"SMU Error: {e}")
except Exception as e:
print(f"Unexpected error: {e}")
Operaciones habituales
Información del dispositivo
# Get device identity
identity = smu.get_identity()
print(f"Connected to: {identity}")
# Get system temperatures
adc_temp, ch1_temp, ch2_temp = smu.get_temperatures()
print(f"Temperatures: ADC: {adc_temp}°C, CH1: {ch1_temp}°C, CH2: {ch2_temp}°C")
Configuración de los canales
# Select channel to configure
channel = 1
# Set mode (FVMI: Force Voltage, Measure Current)
smu.set_mode(channel, "FVMI")
# Set voltage range (AUTO, LOW, HIGH)
smu.set_voltage_range(channel, "AUTO")
# Enable channel
smu.enable_channel(channel)
Ajuste de los valores de salida
# Set voltage (in volts)
smu.set_voltage(1, 3.3)
# Set current (in amperes)
smu.set_current(2, 0.01) # 10mA
Realización de mediciones
# Measure voltage only
voltage = smu.measure_voltage(1)
print(f"Voltage: {voltage}V")
# Measure current only
current = smu.measure_current(1)
print(f"Current: {current}A")
# Measure both voltage and current in one command
voltage, current = smu.measure_voltage_and_current(1)
print(f"Voltage: {voltage}V, Current: {current}A")
Control del estado de los canales
# Enable channel
smu.enable_channel(1)
# Disable channel
smu.disable_channel(1)
Funciones avanzadas
Barrido de tensión
Puede realizar un barrido de tensión para obtener curvas I-V:
import csv
from tqdm import tqdm
import time
def voltage_sweep(smu, channel=1, start=-1.0, stop=1.0, step=0.1):
"""Perform a voltage sweep and measure current"""
try:
# Configure channel
smu.set_mode(channel, "FVMI")
smu.set_voltage_range(channel, "AUTO")
smu.enable_channel(channel)
# Create voltage points
voltages = [round(v, 3) for v in
[start + step*i for i in range(int((stop-start)/step) + 1)]]
results = []
# Create progress bar
for voltage in tqdm(voltages, desc="Voltage Sweep"):
smu.set_voltage(channel, voltage)
time.sleep(0.1) # Allow settling time
v, i = smu.measure_voltage_and_current(channel)
results.append({
'target_voltage': voltage,
'measured_voltage': v,
'measured_current': i
})
return results
finally:
# Always disable channel after measurement
smu.disable_channel(channel)
# Run voltage sweep and save results
with SMU(ConnectionType.USB, port="COM3") as smu:
sweep_results = voltage_sweep(smu, channel=1, start=-1.0, stop=1.0, step=0.05)
# Save results to CSV
with open('voltage_sweep_results.csv', 'w', newline='') as f:
writer = csv.DictWriter(f, fieldnames=[
'target_voltage', 'measured_voltage', 'measured_current'])
writer.writeheader()
writer.writerows(sweep_results)
print("Results saved to voltage_sweep_results.csv")
Transmisión de datos
Para la adquisición de datos a alta velocidad, el miniSMU admite la transmisión continua de datos (streaming):
import time
import csv
from tqdm import tqdm
from datetime import datetime
def stream_data(smu, channel=1, duration=10.0, sample_rate=100.0, voltage=3.3):
"""Stream data from the SMU for a specified duration"""
try:
# Configure channel
smu.set_mode(channel, "FVMI")
smu.enable_channel(channel)
smu.set_voltage(channel, voltage)
# Configure streaming
smu.set_sample_rate(channel, sample_rate)
# Set miniSMU's internal time for timestamping
current_time = int(time.time() * 1000) # Convert to milliseconds
smu.set_time(current_time)
# Calculate number of samples
num_samples = int(duration * sample_rate)
# Prepare data storage
timestamps = []
voltages = []
currents = []
# Start streaming
print("Starting streaming...")
smu.start_streaming(channel)
# Collect data with progress bar
pbar = tqdm(total=num_samples, desc="Streaming Data")
while len(timestamps) < num_samples:
try:
# Read streaming data packet
data_channel, t, v, i = smu.read_streaming_data()
# Only process data from the requested channel
if data_channel == channel:
timestamps.append(t)
voltages.append(v)
currents.append(i)
pbar.update(1)
except Exception as e:
print(f"\nError reading streaming data: {e}")
break
# Stop streaming
smu.stop_streaming(channel)
pbar.close()
# Save data to CSV
filename = f'streaming_data_{datetime.now().strftime("%Y%m%d_%H%M%S")}.csv'
with open(filename, 'w', newline='') as f:
writer = csv.writer(f)
writer.writerow(['Timestamp (s)', 'Voltage (V)', 'Current (A)'])
for t, v, i in zip(timestamps, voltages, currents):
writer.writerow([t, v, i])
print(f"Data saved to {filename}")
return timestamps, voltages, currents
finally:
# Always cleanup
smu.disable_channel(channel)
smu.stop_streaming(channel)
# Stream data for 5 seconds at 100Hz
with SMU(ConnectionType.USB, port="COM3") as smu:
timestamps, voltages, currents = stream_data(
smu,
channel=1,
duration=5.0,
sample_rate=100.0,
voltage=3.3
)
Mediciones Kelvin a 4 hilos
Para mediciones de alta exactitud que eliminan la resistencia de los cables:
with SMU(ConnectionType.USB, port="COM3") as smu:
# Enable 4-wire mode (CH2 becomes sense channel)
smu.enable_fourwire_mode()
# Configure CH1 as voltage source
smu.set_mode(1, "FVMI")
smu.set_voltage(1, 1.0)
smu.enable_channel(1)
# Measure - returns CH1 current and CH2 (sense) voltage
voltage, current = smu.measure_voltage_and_current(1)
resistance = voltage / current
print(f"True resistance: {resistance:.6f} Ohm")
# Disable 4-wire mode when done
smu.disable_fourwire_mode()
Configuración del wifi
La biblioteca ofrece funciones para gestionar la configuración wifi:
# Scan for available networks
networks = smu.wifi_scan()
for network in networks:
print(f"SSID: {network['ssid']}, RSSI: {network['rssi']}")
# Configure WiFi credentials
smu.set_wifi_credentials("YourNetworkSSID", "YourPassword")
# Enable WiFi
smu.enable_wifi()
# Check WiFi status
status = smu.get_wifi_status()
print(f"Connected: {status.connected}")
print(f"SSID: {status.ssid}")
print(f"IP Address: {status.ip_address}")
print(f"Signal Strength: {status.rssi}dBm")
Con el firmware 2.0, wifi_scan() requiere minismu_py 0.4.2 o posterior: las versiones anteriores esperan la respuesta durante un segundo, que no basta para la búsqueda.
Ejemplos de aplicación
Caracterización de dispositivos
Este ejemplo caracteriza un diodo realizando un barrido de tensión y analizando los resultados:
import numpy as np
import matplotlib.pyplot as plt
from minismu_py import SMU, ConnectionType
with SMU(ConnectionType.USB, port="COM3") as smu:
# Configure channel
smu.set_mode(1, "FVMI")
smu.enable_channel(1)
# Perform voltage sweep
voltages = np.linspace(-0.5, 1.0, 100) # -0.5V to 1.0V in 100 steps
measured_voltages = []
measured_currents = []
for v in voltages:
smu.set_voltage(1, v)
time.sleep(0.05) # Allow settling time
mv, mi = smu.measure_voltage_and_current(1)
measured_voltages.append(mv)
measured_currents.append(mi)
# Disable channel when done
smu.disable_channel(1)
# Plot results
plt.figure(figsize=(10, 6))
plt.plot(measured_voltages, measured_currents * 1000) # Convert to mA
plt.grid(True)
plt.xlabel('Voltage (V)')
plt.ylabel('Current (mA)')
plt.title('Diode I-V Characteristic')
plt.savefig('diode_iv_curve.png')
plt.show()
Secuencia de prueba automatizada
Este ejemplo muestra una secuencia de prueba automatizada para una batería:
import time
import csv
from datetime import datetime
from minismu_py import SMU, ConnectionType
def battery_discharge_test(smu, channel=1, discharge_current=0.01, cutoff_voltage=3.0):
"""Perform battery discharge test until cutoff voltage is reached"""
try:
# Configure for constant current discharge (FIMV mode)
smu.set_mode(channel, "FIMV")
smu.enable_channel(channel)
# Set discharge current (negative for discharge)
smu.set_current(channel, -discharge_current)
# Prepare data storage
start_time = time.time()
results = []
print(f"Starting battery discharge test at {discharge_current*1000:.1f}mA")
print(f"Test will run until battery voltage reaches {cutoff_voltage}V")
# Run test until cutoff voltage is reached
while True:
# Measure voltage and current
voltage, current = smu.measure_voltage_and_current(channel)
# Calculate elapsed time
elapsed_time = time.time() - start_time
# Record data
results.append({
'time': elapsed_time,
'voltage': voltage,
'current': current
})
# Display progress
print(f"\rTime: {elapsed_time:.1f}s, Voltage: {voltage:.3f}V, Current: {current*1000:.1f}mA", end="")
# Check if cutoff voltage reached
if voltage <= cutoff_voltage:
print("\nCutoff voltage reached. Test complete.")
break
# Wait before next measurement
time.sleep(5) # Take measurements every 5 seconds
# Save results
filename = f'battery_discharge_{datetime.now().strftime("%Y%m%d_%H%M%S")}.csv'
with open(filename, 'w', newline='') as f:
writer = csv.DictWriter(f, fieldnames=['time', 'voltage', 'current'])
writer.writeheader()
writer.writerows(results)
print(f"Results saved to {filename}")
return results
finally:
# Always disable channel when done
smu.disable_channel(channel)
# Run battery discharge test
with SMU(ConnectionType.USB, port="COM3") as smu:
battery_discharge_test(
smu,
channel=1,
discharge_current=0.01, # 10mA discharge
cutoff_voltage=3.0 # 3.0V cutoff
)
Referencia de la API
Gestión de la conexión
| Método | Descripción |
|---|---|
SMU(connection_type, port, host, tcp_port) | Inicializa la conexión con la SMU |
close() | Cierra la conexión |
get_identity() | Obtiene la identificación del dispositivo |
reset() | Reinicia el dispositivo |
Suministro y medición
| Método | Descripción |
|---|---|
set_voltage(channel, voltage) | Establece la tensión del canal especificado |
set_current(channel, current) | Establece la corriente del canal especificado |
measure_voltage(channel) | Mide la tensión en el canal especificado |
measure_current(channel) | Mide la corriente en el canal especificado |
measure_voltage_and_current(channel) | Mide la tensión y la corriente |
Configuración de los canales
| Método | Descripción |
|---|---|
enable_channel(channel) | Activa el canal especificado |
disable_channel(channel) | Desactiva el canal especificado |
set_voltage_range(channel, range_type) | Establece el rango de tensión (AUTO/LOW/HIGH) |
set_mode(channel, mode) | Establece el modo del canal (FIMV/FVMI) |
Transmisión de datos
| Método | Descripción |
|---|---|
start_streaming(channel) | Inicia la transmisión de datos |
stop_streaming(channel) | Detiene la transmisión de datos |
read_streaming_data() | Lee un paquete de datos de la transmisión (canal, marca de tiempo, tensión, corriente) |
set_sample_rate(channel, rate) | Establece la frecuencia de muestreo en Hz |
Configuración del sistema
| Método | Descripción |
|---|---|
set_led_brightness(brightness) | Establece el brillo de los LED (0-100) |
get_led_brightness() | Obtiene el brillo actual de los LED |
get_temperatures() | Obtiene las temperaturas del sistema (ADC, canal 1, canal 2) |
set_time(timestamp) | Ajusta el reloj interno del dispositivo (marca de tiempo Unix en milisegundos) |
enable_fourwire_mode() | Activa el modo de medición Kelvin a 4 hilos |
disable_fourwire_mode() | Desactiva el modo de 4 hilos y restablece los canales independientes |
get_fourwire_mode() | Consulta el estado del modo de 4 hilos (devuelve un valor booleano) |
Configuración del wifi
| Método | Descripción |
|---|---|
wifi_scan() | Busca las redes wifi disponibles (con el firmware 2.0, requiere minismu_py 0.4.2 o posterior) |
get_wifi_status() | Obtiene el estado actual del wifi |
set_wifi_credentials(ssid, password) | Establece las credenciales wifi |
enable_wifi() | Activa el wifi |
disable_wifi() | Desactiva el wifi |
Buenas prácticas
Estas son algunas prácticas recomendadas para trabajar con la biblioteca minismu_py:
1. Utilice gestores de contexto
Utilice siempre los gestores de contexto de Python para garantizar que los recursos se liberen correctamente:
with SMU(ConnectionType.USB, port="COM3") as smu:
# Code here
2. Desactive siempre los canales
Desactive los canales cuando terminen las mediciones:
try:
smu.enable_channel(1)
# Your measurement code
finally:
smu.disable_channel(1)
3. Añada un tiempo de establecimiento
Incluya un tiempo de establecimiento para obtener mediciones estables:
smu.set_voltage(1, 3.3)
time.sleep(0.1) # Allow settling time before measuring
4. Gestione correctamente las excepciones
Implemente una gestión de excepciones adecuada:
try:
# SMU operations
except SMUException as e:
print(f"SMU Error: {e}")
5. Compruebe el estado de la conexión
Verifique la conexión antes de ejecutar operaciones:
identity = smu.get_identity()
if not identity:
print("Device not responding")
6. Cierre las conexiones
Cierre siempre las conexiones al terminar:
smu.close()
Solución de problemas
Problemas habituales
No es posible conectarse al dispositivo
- Verifique que el dispositivo esté encendido
- Compruebe la conexión del cable USB
- Confirme que el nombre del puerto es correcto
- Asegúrese de que ningún otro software esté utilizando el puerto
Errores de comunicación
- Reinicie el dispositivo
- Cierre la conexión y vuelva a abrirla
- Compruebe si hay interferencias o problemas con el cable
- Verifique que la velocidad en baudios sea la correcta (115200)
Resultados de medición inesperados
- Compruebe la configuración del canal (modo, rango)
- Deje un tiempo de establecimiento suficiente
- Verifique las conexiones con el dispositivo bajo prueba
- Compruebe los límites de protección
Problemas de conexión wifi
- Asegúrese de que la antena wifi esté bien colocada
- Verifique las credenciales wifi
- Compruebe la intensidad de la señal
- Pruebe primero la conexión USB para configurar el wifi
Más recursos
- Biblioteca de Python del miniSMU en GitHub
- Carpeta de scripts de ejemplo
- Documentación completa de la API
Para ver ejemplos más avanzados y documentación detallada, visite el repositorio oficial y los enlaces a la documentación que figuran arriba.