# -*- coding:utf-8 -*- import RPi.GPIO as GPIO import serial import time #EN_485 = 5 #GPIO.setmode(GPIO.BCM) #GPIO.setup(EN_485, GPIO.OUT) #GPIO.output(EN_485, GPIO.LOW) # 初始化为接收模式 # 正确定义十六进制数据(使用字符串格式) send_data = "12 4c 0a 01 03 6c" try: # 串口初始化放在循环外,避免重复打开 ser = serial.Serial( port="/dev/ttyS0", baudrate=115200, timeout=1 ) if ser.is_open: print(f"serial is open: {ser.portstr}") while True: # 将十六进制字符串转换为字节数组 hex_data = bytes.fromhex(send_data) # 切换到发送模式 #GPIO.output(EN_485, GPIO.HIGH) time.sleep(0.001) # 等待模式切换完成 # 发送数据 n = ser.write(hex_data) print(f"send {n} bytes") print(f"data(hex): {' '.join(f'{b:02X}' for b in hex_data)}") ser.flush() # 确保数据发送完成 # 切换回接收模式 #GPIO.output(EN_485, GPIO.LOW) # 循环发送的间隔时间 time.sleep(1) except KeyboardInterrupt: print(":stop") finally: # 释放资源 if 'ser' in locals() and ser.is_open: ser.close() GPIO.cleanup()