Undalogic 標誌Undalogic

說明文件

Python 介面

使用 Python 函式庫控制 miniSMU MS01 並實現自動化

miniSMU MS01 可透過官方 Python 函式庫 minismu_py 以程式控制。此介面讓您能方便地實現量測自動化、執行複雜的測試序列,並將 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())

使用 context manager

SMU 類別支援 Python 的 context manager(情境管理器)協定,可自動處理資源的清理:

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. 使用 context manager

務必使用 Python 的 context manager,以確保正確清理資源:

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

更多資源

如需更多進階範例與詳細說明文件,請造訪上方的官方儲存庫與說明文件連結。