Gallwch reoli’r miniSMU MS01 drwy raglen gan ddefnyddio’r llyfrgell Python swyddogol, minismu_py. Mae’r rhyngwyneb hwn yn ffordd hwylus o awtomeiddio mesuriadau, rhedeg dilyniannau profi cymhleth, ac integreiddio’r miniSMU yn eich apiau pwrpasol a’ch llifoedd gwaith ymchwil.
Gosod
Gosodwch y llyfrgell minismu_py yn uniongyrchol o PyPI gan ddefnyddio pip:
pip install minismu_py
Ychydig iawn o ddibyniaethau sydd gan y llyfrgell. Mae angen:
- Python 3.6 neu fersiwn fwy diweddar
- Y pecyn pyserial ar gyfer cysylltiadau USB
- Y pecyn tqdm (dewisol, i ddangos bariau cynnydd yn yr enghreifftiau)
Dechrau arni
Cysylltiad sylfaenol
I ddechrau defnyddio’r rhyngwyneb Python, bydd angen i chi sefydlu cysylltiad â’ch miniSMU MS01 yn gyntaf:
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())
Defnyddio rheolwr cyd-destun
Mae’r dosbarth SMU yn cefnogi protocol rheolwr cyd-destun (context manager) Python, sy’n rhyddhau adnoddau’n awtomatig:
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
Enghraifft o fesuriad sylfaenol
Dyma enghraifft syml sy’n ffurfweddu sianel, yn gosod foltedd ac yn gwneud mesuriadau:
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)
Cysyniadau allweddol
Mathau o gysylltiad
Mae’r llyfrgell yn cefnogi dau ddull cysylltu:
Cysylltiad USB: Cysylltiad uniongyrchol drwy gebl USB
smu = SMU(ConnectionType.USB, port="COM3")Cysylltiad rhwydwaith: Cysylltiad dros Wi-Fi
smu = SMU(ConnectionType.NETWORK, host="192.168.1.100")
Moddau mesur
Mae’r miniSMU yn cefnogi dau brif fodd mesur:
FVMI (Force Voltage, Measure Current)
- Rhoi foltedd penodol a mesur y cerrynt sy’n deillio ohono
- Addas ar gyfer nodweddu gwrthyddion, profi deuodau, ac ati
smu.set_mode(1, "FVMI")FIMV (Force Current, Measure Voltage)
- Rhoi cerrynt penodol a mesur y foltedd sy’n deillio ohono
- Addas ar gyfer profi LEDs, nodweddu batrïau, ac ati
smu.set_mode(1, "FIMV")
Trin gwallau
Mae’r llyfrgell yn cynnwys ei dosbarth eithriad ei hun, SMUException, i drin gwallau:
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}")
Gweithrediadau cyffredin
Gwybodaeth am y ddyfais
# 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")
Ffurfweddu sianeli
# 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)
Gosod gwerthoedd allbwn
# Set voltage (in volts)
smu.set_voltage(1, 3.3)
# Set current (in amperes)
smu.set_current(2, 0.01) # 10mA
Gwneud mesuriadau
# 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")
Rheoli cyflwr y sianel
# Enable channel
smu.enable_channel(1)
# Disable channel
smu.disable_channel(1)
Nodweddion uwch
Sgubiad foltedd
Gallwch wneud sgubiad foltedd i gynhyrchu cromliniau 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")
Ffrydio data
Ar gyfer caffael data ar gyflymder uchel, mae’r miniSMU yn cefnogi ffrydio data:
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
)
Mesuriadau Kelvin 4 gwifren
Ar gyfer mesuriadau cywir iawn sy’n dileu gwrthiant y gwifrau:
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()
Ffurfweddu’r Wi-Fi
Mae’r llyfrgell yn cynnig ffwythiannau i reoli’r gosodiadau 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")
Enghreifftiau o gymwysiadau
Nodweddu dyfais
Mae’r enghraifft hon yn nodweddu deuod drwy wneud sgubiad foltedd a dadansoddi’r canlyniadau:
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()
Dilyniant profi awtomataidd
Mae’r enghraifft hon yn dangos dilyniant profi awtomataidd ar gyfer batri:
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
)
Cyfeirnod yr API
Rheoli’r cysylltiad
| Dull | Disgrifiad |
|---|---|
SMU(connection_type, port, host, tcp_port) | Cychwyn y cysylltiad â’r SMU |
close() | Cau’r cysylltiad |
get_identity() | Cael manylion adnabod y ddyfais |
reset() | Ailosod y ddyfais |
Cyflenwi a mesur
| Dull | Disgrifiad |
|---|---|
set_voltage(channel, voltage) | Gosod y foltedd ar gyfer y sianel a nodir |
set_current(channel, current) | Gosod y cerrynt ar gyfer y sianel a nodir |
measure_voltage(channel) | Mesur y foltedd ar y sianel a nodir |
measure_current(channel) | Mesur y cerrynt ar y sianel a nodir |
measure_voltage_and_current(channel) | Mesur y foltedd a’r cerrynt |
Ffurfweddu sianeli
| Dull | Disgrifiad |
|---|---|
enable_channel(channel) | Galluogi’r sianel a nodir |
disable_channel(channel) | Analluogi’r sianel a nodir |
set_voltage_range(channel, range_type) | Gosod yr amrediad foltedd (AUTO/LOW/HIGH) |
set_mode(channel, mode) | Gosod modd y sianel (FIMV/FVMI) |
Ffrydio data
| Dull | Disgrifiad |
|---|---|
start_streaming(channel) | Dechrau ffrydio data |
stop_streaming(channel) | Stopio ffrydio data |
read_streaming_data() | Darllen pecyn o ddata sy’n cael ei ffrydio (sianel, stamp amser, foltedd, cerrynt) |
set_sample_rate(channel, rate) | Gosod y gyfradd samplu mewn Hz |
Ffurfweddu’r system
| Dull | Disgrifiad |
|---|---|
set_led_brightness(brightness) | Gosod disgleirdeb yr LEDs (0-100) |
get_led_brightness() | Cael disgleirdeb presennol yr LEDs |
get_temperatures() | Cael tymereddau’r system (ADC, Sianel 1, Sianel 2) |
set_time(timestamp) | Gosod cloc mewnol y ddyfais (stamp amser Unix mewn milieiliadau) |
enable_fourwire_mode() | Galluogi’r modd mesur Kelvin 4 gwifren |
disable_fourwire_mode() | Analluogi’r modd 4 gwifren, ac adfer y sianeli annibynnol |
get_fourwire_mode() | Holi statws y modd 4 gwifren (yn dychwelyd bool) |
Ffurfweddu’r Wi-Fi
| Dull | Disgrifiad |
|---|---|
wifi_scan() | Chwilio am rwydweithiau Wi-Fi sydd ar gael |
get_wifi_status() | Cael statws presennol y Wi-Fi |
set_wifi_credentials(ssid, password) | Gosod manylion mewngofnodi’r Wi-Fi |
enable_wifi() | Galluogi’r Wi-Fi |
disable_wifi() | Analluogi’r Wi-Fi |
Arferion gorau
Dyma rai arferion a argymhellir wrth weithio gyda’r llyfrgell minismu_py:
1. Defnyddiwch reolwyr cyd-destun
Defnyddiwch reolwyr cyd-destun Python bob amser, er mwyn sicrhau bod adnoddau’n cael eu rhyddhau’n iawn:
with SMU(ConnectionType.USB, port="COM3") as smu:
# Code here
2. Analluogwch y sianeli bob amser
Analluogwch y sianeli pan fydd y mesuriadau wedi gorffen:
try:
smu.enable_channel(1)
# Your measurement code
finally:
smu.disable_channel(1)
3. Ychwanegwch amser setlo
Rhowch amser setlo i gael mesuriadau sefydlog:
smu.set_voltage(1, 3.3)
time.sleep(0.1) # Allow settling time before measuring
4. Triniwch eithriadau’n iawn
Rhowch drefn briodol ar waith i drin eithriadau:
try:
# SMU operations
except SMUException as e:
print(f"SMU Error: {e}")
5. Gwiriwch statws y cysylltiad
Gwiriwch y cysylltiad cyn rhedeg gweithrediadau:
identity = smu.get_identity()
if not identity:
print("Device not responding")
6. Caewch y cysylltiadau
Caewch y cysylltiadau bob amser pan fyddwch wedi gorffen:
smu.close()
Datrys problemau
Problemau cyffredin
Methu cysylltu â’r ddyfais
- Gwiriwch fod y ddyfais wedi’i throi ymlaen
- Gwiriwch gysylltiad y cebl USB
- Gwiriwch fod enw’r porth yn gywir
- Gwnewch yn siŵr nad oes meddalwedd arall yn defnyddio’r porth
Gwallau cyfathrebu
- Ailosodwch y ddyfais
- Caewch y cysylltiad a’i agor eto
- Chwiliwch am ymyriant neu broblemau gyda’r cebl
- Gwiriwch fod y gyfradd baud yn gywir (115200)
Canlyniadau mesur annisgwyl
- Gwiriwch ffurfweddiad y sianel (modd, amrediad)
- Rhowch ddigon o amser setlo
- Gwiriwch y cysylltiadau â’r ddyfais sy’n cael ei phrofi
- Gwiriwch y terfynau amddiffyn
Problemau cysylltu dros Wi-Fi
- Gwnewch yn siŵr bod yr antena Wi-Fi wedi’i chysylltu’n iawn
- Gwiriwch fanylion mewngofnodi’r Wi-Fi
- Gwiriwch gryfder y signal
- Cysylltwch drwy USB yn gyntaf i ffurfweddu’r Wi-Fi
Adnoddau pellach
I gael enghreifftiau mwy datblygedig a dogfennaeth fanwl, ewch i’r ystorfa swyddogol a’r dolenni dogfennaeth uchod.