Skip to content
Snippets Groups Projects
Commit 73755ae3 authored by ym13n22's avatar ym13n22
Browse files

add

parent dcdc8b56
No related branches found
No related tags found
No related merge requests found
No preview for this file type
No preview for this file type
import serial
import time
class EMGSensor:
def __init__(self, port='COM5', baudrate=9600):
self.port = port
self.baudrate = baudrate
self.ser = None
self._open_serial()
def _open_serial(self):
"""
打开串口连接。
"""
try:
self.ser = serial.Serial(self.port, self.baudrate, timeout=1)
print(f"Serial port {self.port} opened with baudrate {self.baudrate}.")
except Exception as e:
print(f"Error opening serial port: {e}")
def _decode(self, serial_data):
"""
解码串口数据,返回两个ADC值。
:param serial_data: 从串口读取的原始数据
:return: 两个ADC值的列表
"""
serial_string = serial_data.decode(errors="ignore")
adc_string_1 = ""
adc_string_2 = ""
adc_values = [0, 0]
if '\n' in serial_string:
# remove new line character
serial_string = serial_string.replace("\n", "")
if serial_string != '':
# Convert number to binary, placing 0s in empty spots
serial_string = format(int(serial_string, 10), "024b")
# Separate the input number from the data
adc_string_1 = serial_string[0:12]
adc_string_2 = serial_string[12:24]
adc_values[0] = int(adc_string_1, base=2)
adc_values[1] = int(adc_string_2, base=2)
return adc_values
return None
def read_emg_data(self):
"""
从EMG传感器读取数据并返回两个输出值。
:return: 包含两个ADC值的列表,如果读取失败则返回 None
"""
try:
# 读取一行数据
line = self.ser.readline()
emg_values = self._decode(line)
if emg_values:
return emg_values
except Exception as e:
print(f"Error reading data: {e}")
return None
def start_data_collection(self):
print("Starting EMG data collection...")
try:
while True:
emg_values = self.read_emg_data()
if emg_values is not None:
print(f"EMG Value 1: {emg_values[0]}, EMG Value 2: {emg_values[1]}")
# 在这里添加数据分析代码
# 例如,计算平均值,滤波等
else:
print("Failed to read EMG data")
time.sleep(0.1) # 控制读取频率
except KeyboardInterrupt:
print("Stopping EMG data collection.")
finally:
self.close()
def close(self):
"""
关闭串口连接。
"""
if self.ser and self.ser.is_open:
self.ser.close()
print("Serial port closed.")
if __name__ == "__main__":
sensor = EMGSensor(port='COM5', baudrate=9600)
sensor.start_data_collection()
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment