Files
LJ360/seial_test.py
2025-12-26 10:02:00 +08:00

37 lines
1007 B
Python

import serial
import time
# 配置串口(请根据实际情况修改设备名)
PORT = '/dev/ttyS0' # 或 '/dev/ttyUSB0'
BAUDRATE = 115200
try:
# 打开串口
ser = serial.Serial(PORT, BAUDRATE, timeout=1)
print(f"✅ 已打开串口 {PORT}")
# 发送数据
data_to_send = b'123456\n'
# 持续读取数据(注意:此时串口是打开的!)
print("📥 开始监听串口数据...")
while True:
ser.write(data_to_send)
print("📤 已发送数据")
try:
line = ser.readline()
if line:
print("接收到:", line.hex())
except serial.SerialException as e:
print("❌ 串口异常:", e)
break
time.sleep(1)
except serial.SerialException as e:
print(f"❌ 无法打开串口 {PORT}: {e}")
except KeyboardInterrupt:
print("\n🛑 用户中断")
finally:
if 'ser' in locals() and ser.is_open:
ser.close()
print("🔌 串口已关闭")