Files
Test-Repo/视觉代码python/TTLCommunicator.py
2025-11-05 17:08:18 +08:00

70 lines
2.3 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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连接已关闭")