You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
48 lines
1.4 KiB
48 lines
1.4 KiB
# serial_manager.py
|
|
import serial
|
|
import time
|
|
|
|
|
|
class SerialManager:
|
|
def __init__(self, port='COM3', baudrate=115200):
|
|
self.port = port
|
|
self.baudrate = baudrate
|
|
self.serial_conn = None
|
|
|
|
def connect(self):
|
|
"""建立串口连接"""
|
|
try:
|
|
self.serial_conn = serial.Serial(
|
|
port=self.port,
|
|
baudrate=self.baudrate,
|
|
bytesize=serial.EIGHTBITS,
|
|
parity=serial.PARITY_NONE,
|
|
stopbits=serial.STOPBITS_ONE,
|
|
timeout=1
|
|
)
|
|
print(f"✅ 串口连接成功: {self.port}")
|
|
return True
|
|
except Exception as e:
|
|
print(f"❌ 串口连接失败: {e}")
|
|
return False
|
|
|
|
def send_command(self, command_bytes):
|
|
"""发送命令到矩阵硬件"""
|
|
if not self.serial_conn or not self.serial_conn.is_open:
|
|
print("❌ 串口未连接")
|
|
return False
|
|
|
|
try:
|
|
# 添加小延时避免命令粘连
|
|
time.sleep(0.05)
|
|
self.serial_conn.write(command_bytes)
|
|
print(f"📤 发送命令: {command_bytes.hex().upper()}")
|
|
return True
|
|
except Exception as e:
|
|
print(f"❌ 命令发送失败: {e}")
|
|
return False
|
|
|
|
def close(self):
|
|
"""关闭串口"""
|
|
if self.serial_conn and self.serial_conn.is_open:
|
|
self.serial_conn.close()
|