Undalogic 로고Undalogic

문서

Python 인터페이스

Python 라이브러리로 miniSMU MS01을 제어하고 자동화하는 방법

miniSMU MS01은 공식 Python 라이브러리인 minismu_py로 프로그래밍 방식으로 제어할 수 있습니다. 이 인터페이스를 사용하면 측정을 자동화하고, 복잡한 테스트 시퀀스를 수행하고, miniSMU를 사용자 애플리케이션과 연구 워크플로에 손쉽게 통합할 수 있습니다.

설치

pip로 PyPI에서 minismu_py 라이브러리를 바로 설치하십시오:

pip install minismu_py

이 라이브러리는 의존성이 최소화되어 있으며 다음이 필요합니다:

  • Python 3.6 이상
  • USB 연결용 pyserial 패키지
  • 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
    )

4선식 켈빈 측정

리드 저항을 제거하여 높은 정확도로 측정하려면 다음과 같이 합니다:

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()4선식 켈빈 측정 모드 활성화
disable_fourwire_mode()4선식 모드를 비활성화하고 채널을 다시 독립적으로 동작시킴
get_fourwire_mode()4선식 모드 상태 조회(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 접속 정보를 확인하십시오
    • 신호 강도를 확인하십시오
    • Wi-Fi를 설정하려면 먼저 USB로 연결해 보십시오

추가 자료

더 많은 고급 예제와 자세한 문서는 위의 공식 저장소와 문서 링크를 참조하십시오.