Undalogic 标志Undalogic

文档

Python 接口

使用 Python 库控制 miniSMU MS01 并实现自动化

您可以使用官方 Python 库 minismu_py 以编程方式控制 miniSMU MS01。借助这一接口,您可以方便地实现测量自动化、执行复杂的测试序列,并将 miniSMU 集成到您自己的应用程序和研究工作流程中。

安装

使用 pip 直接从 PyPI 安装 minismu_py 库:

pip install minismu_py

该库依赖项极少,需要:

  • Python 3.6 或更高版本
  • pyserial 包,用于 USB 连接
  • tqdm 包(可选,用于示例中的进度条)

入门

基本连接

要开始使用 Python 接口,首先需要与您的 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())

使用上下文管理器

SMU 类支持 Python 的上下文管理器协议,可自动完成资源清理:

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

基本测量示例

下面是一个简单的示例,用于配置通道、设置电压并进行测量:

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)

关键概念

连接类型

该库支持两种连接方式:

  1. USB 连接:通过 USB 线缆直接连接

    smu = SMU(ConnectionType.USB, port="COM3")
    
  2. 网络连接:通过 Wi-Fi 连接

    smu = SMU(ConnectionType.NETWORK, host="192.168.1.100")
    

测量模式

miniSMU 支持两种主要测量模式:

  1. FVMI(施加电压、测量电流)

    • 施加指定电压,并测量由此产生的电流
    • 适用于电阻表征、二极管测试等
    smu.set_mode(1, "FVMI")
    
  2. FIMV(施加电流、测量电压)

    • 施加指定电流,并测量由此产生的电压
    • 适用于 LED 测试、电池表征等
    smu.set_mode(1, "FIMV")
    

错误处理

该库通过 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}")

常用操作

设备信息

# 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")

通道配置

# 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)

设置输出值

# Set voltage (in volts)
smu.set_voltage(1, 3.3)

# Set current (in amperes)
smu.set_current(2, 0.01)  # 10mA

进行测量

# 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")

控制通道状态

# Enable channel
smu.enable_channel(1)

# Disable channel
smu.disable_channel(1)

高级功能

电压扫描

您可以执行电压扫描来生成 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")

数据流

为实现高速数据采集,miniSMU 支持数据流传输:

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
    )

四线开尔文测量

用于消除引线电阻影响的高精度测量:

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()

Wi-Fi 配置

该库提供用于管理 Wi-Fi 设置的函数:

# 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")

应用示例

器件表征

此示例通过执行电压扫描并分析结果来表征一个二极管:

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()

自动测试序列

此示例演示了一个电池自动测试序列:

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
    )

API 参考

连接管理

方法说明
SMU(connection_type, port, host, tcp_port)初始化 SMU 连接
close()关闭连接
get_identity()获取设备标识信息
reset()复位设备

输出与测量

方法说明
set_voltage(channel, voltage)设置指定通道的电压
set_current(channel, current)设置指定通道的电流
measure_voltage(channel)测量指定通道的电压
measure_current(channel)测量指定通道的电流
measure_voltage_and_current(channel)同时测量电压和电流

通道配置

方法说明
enable_channel(channel)启用指定通道
disable_channel(channel)禁用指定通道
set_voltage_range(channel, range_type)设置电压量程(AUTO/LOW/HIGH)
set_mode(channel, mode)设置通道模式(FIMV/FVMI)

数据流

方法说明
start_streaming(channel)开始数据流传输
stop_streaming(channel)停止数据流传输
read_streaming_data()读取数据流数据包(通道、时间戳、电压、电流)
set_sample_rate(channel, rate)设置采样率(单位为 Hz)

系统配置

方法说明
set_led_brightness(brightness)设置 LED 亮度(0-100)
get_led_brightness()获取当前 LED 亮度
get_temperatures()获取系统温度(ADC、通道 1、通道 2)
set_time(timestamp)设置设备内部时钟(以毫秒为单位的 Unix 时间戳)
enable_fourwire_mode()启用四线开尔文测量模式
disable_fourwire_mode()禁用四线模式,恢复为独立通道
get_fourwire_mode()查询四线模式状态(返回 bool)

Wi-Fi 配置

方法说明
wifi_scan()扫描可用的 Wi-Fi 网络
get_wifi_status()获取当前 Wi-Fi 状态
set_wifi_credentials(ssid, password)设置 Wi-Fi 凭据
enable_wifi()启用 Wi-Fi
disable_wifi()禁用 Wi-Fi

最佳实践

使用 minismu_py 库时,建议遵循以下做法:

1. 使用上下文管理器

始终使用 Python 上下文管理器,以确保正确清理资源:

with SMU(ConnectionType.USB, port="COM3") as smu:
    # Code here

2. 始终禁用通道

测量完成后禁用通道:

try:
    smu.enable_channel(1)
    # Your measurement code
finally:
    smu.disable_channel(1)

3. 留出建立时间

留出建立时间,以获得稳定的测量结果:

smu.set_voltage(1, 3.3)
time.sleep(0.1)  # Allow settling time before measuring

4. 正确处理异常

实现正确的异常处理:

try:
    # SMU operations
except SMUException as e:
    print(f"SMU Error: {e}")

5. 检查连接状态

执行操作前先确认连接:

identity = smu.get_identity()
if not identity:
    print("Device not responding")

6. 关闭连接

完成后务必关闭连接:

smu.close()

故障排查

常见问题

  1. 无法连接设备

    • 确认设备已开机
    • 检查 USB 线缆连接
    • 确认端口名称正确
    • 确保没有其他软件正在使用该端口
  2. 通信错误

    • 复位设备
    • 关闭连接后重新打开
    • 检查是否存在干扰或线缆问题
    • 确认波特率正确(115200)
  3. 测量结果异常

    • 检查通道配置(模式、量程)
    • 留出足够的建立时间
    • 确认与被测器件的连接
    • 检查保护限值
  4. Wi-Fi 连接问题

    • 确保 Wi-Fi 天线已正确安装
    • 确认 Wi-Fi 凭据
    • 检查信号强度
    • 先通过 USB 连接来配置 Wi-Fi

更多资源

如需更多高级示例和详细文档,请访问上面的官方代码仓库和文档链接。