From 857c57be8176f4eec6fac8dc53dd9e940fd6c8db Mon Sep 17 00:00:00 2001 From: zhji Date: Mon, 6 Jan 2025 10:36:17 +0800 Subject: [PATCH] [feat] add serial demo by python --- python/serial/pec_serial.py | 51 +++++++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 python/serial/pec_serial.py diff --git a/python/serial/pec_serial.py b/python/serial/pec_serial.py new file mode 100644 index 0000000..4eb6262 --- /dev/null +++ b/python/serial/pec_serial.py @@ -0,0 +1,51 @@ +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()