import serial
import time
# 串口配置
SERIAL_PORT = 'COM143' # 替换为你的串口名
BAUD_RATE = 9600 # 替换为你的波特率
TIMEOUT = 0.01 # 超时时间(秒)
# 匹配的16进制字符串
MATCHING_DATA = '01 E0 01 01 C0 7E'
# 要发送的响应数据
RESPONSE_DATA = '01 E4 04 4B 19 9D 65 83 7C'
# 将16进制字符串转换为字节串
# 首先,将字符串分割成单独的16进制数,然后将其转换为整数,最后转换回字节
response_bytes = bytearray.fromhex(' '.join(RESPONSE_DATA.split()))
# 打开串口
ser = serial.Serial(SERIAL_PORT, BAUD_RATE, timeout=TIMEOUT)
print(f"Listening on {SERIAL_PORT} at {BAUD_RATE} baud...")
try:
while True:
# 读取串口数据
if ser.in_waiting:
# data = ser.readline().decode('utf-8').strip()
data = ser.readline().strip()
# hex_data = ' '.join([f'{b:02X}' for b in data.encode('utf-8')])
hex_data = ' '.join([f'{b:02X}' for b in data])
# 检查是否匹配
if hex_data.upper() == MATCHING_DATA:
print(f"Matching data received: {hex_data}")
# 发送响应数据
# ser.write(RESPONSE_DATA.encode('utf-8'))
ser.write(response_bytes)
print(f"Sent response: {RESPONSE_DATA}")
else:
print(f"Not Mathing,Received data: {hex_data}")
# 休眠以减少CPU使用率
time.sleep(0.01)
except KeyboardInterrupt:
print("Program interrupted.")
finally:
# 关闭串口
ser.close()
用百度的comate生成,串口收一段特定16进制串,回复一另外一段特定的16进制串。玩玩
于 2024-03-22 22:54:30 首次发布