测试文件夹架构
This commit is contained in:
70
新建文件夹/TTLCommunicator.py
Normal file
70
新建文件夹/TTLCommunicator.py
Normal file
@@ -0,0 +1,70 @@
|
||||
import serial
|
||||
import serial.tools.list_ports
|
||||
|
||||
|
||||
class TTLCommunicator:
|
||||
def __init__(self, baudrate=115200, timeout=0.1):
|
||||
"""初始化TTL通信对象"""
|
||||
self.baudrate = baudrate
|
||||
self.timeout = timeout
|
||||
self.ser = None
|
||||
self.connected = False
|
||||
|
||||
@staticmethod # 声明为静态方法
|
||||
def find_usb_ttl_port():
|
||||
"""自动查找USB转TTL设备端口(静态方法,不依赖实例状态)"""
|
||||
ports = list(serial.tools.list_ports.comports())
|
||||
for port in ports:
|
||||
if "USB Serial" in port.description or "CH340" in port.description or "PL2303" in port.description:
|
||||
return port.device
|
||||
return None
|
||||
|
||||
def connect(self, port=None):
|
||||
"""连接到USB转TTL设备"""
|
||||
try:
|
||||
if not port:
|
||||
# 调用静态方法时,可直接通过类名或实例调用(此处保持原有逻辑)
|
||||
port = self.find_usb_ttl_port()
|
||||
if not port:
|
||||
print("未找到USB转TTL设备")
|
||||
return False
|
||||
|
||||
self.ser = serial.Serial(
|
||||
port=port,
|
||||
baudrate=self.baudrate,
|
||||
timeout=self.timeout,
|
||||
parity=serial.PARITY_NONE,
|
||||
stopbits=1,
|
||||
bytesize=serial.EIGHTBITS
|
||||
)
|
||||
|
||||
if self.ser.is_open:
|
||||
self.connected = True
|
||||
print(f"已连接TTL设备:{port}(波特率:{self.baudrate})")
|
||||
return True
|
||||
return False
|
||||
except Exception as e:
|
||||
print(f"连接失败:{str(e)}")
|
||||
return False
|
||||
|
||||
def send_data(self, data_str):
|
||||
"""发送数据到TTL设备"""
|
||||
if not self.connected or not self.ser:
|
||||
print("未连接TTL设备,请先调用connect()")
|
||||
return False
|
||||
|
||||
try:
|
||||
data = (data_str + "\n").encode("utf-8") # 加换行符作为结束标志
|
||||
self.ser.write(data)
|
||||
self.ser.flush()
|
||||
return True
|
||||
except Exception as e:
|
||||
print(f"发送失败:{str(e)}")
|
||||
return False
|
||||
|
||||
def close(self):
|
||||
"""关闭串口连接"""
|
||||
if self.ser and self.ser.is_open:
|
||||
self.ser.close()
|
||||
self.connected = False
|
||||
print("TTL连接已关闭")
|
||||
Reference in New Issue
Block a user