import serial import time from datetime import datetime # 串口配置 serial_port = 'COM3' # 替换为你的串口设备 baud_rate = 115200 # 替换为你的波特率 timeout = 0.04 # 超时时间 # 要发送的数据 data_to_send = "json_get_down" count_right = 0 count_error = 0 count_total = 0 # 创建串口对象 ser = serial.Serial(serial_port, baud_rate, timeout=timeout) print("pec_serial test start ...") try: while True: # 发送数据 # print(f'Sending: {data_to_send}', count_right) ser.write(data_to_send.encode('utf-8')) # 等待接收数据 time.sleep(0.04) # 等待设备响应 received_data = ser.read(ser.in_waiting or 1).decode('utf-8') # 读取所有可用的数据 # 检查收到的数据 if received_data == data_to_send: count_right = count_right + 1 # print('Data received correctly:', received_data) else: print('Data mismatch. Expected:', data_to_send, 'Received:', received_data) count_error = count_error + 1 count_total = count_total + 1 if count_total % 1000 == 0: now = datetime.now() formatted_now = now.strftime("%Y-%m-%d %H:%M:%S ") print(formatted_now, end='') print('all:', count_total, 'Success:', count_right, ', Failed:', count_error) except KeyboardInterrupt: ser.close() print("Exiting...") finally: # 关闭串口 ser.close()