import serial
import time
# 打开串口
ser = serial.Serial(
port='/dev/ttyUSB0', # 串口号,根据实际情况修改
baudrate=9600, # 波特率
parity=serial.PARITY_NONE,# 校验位
stopbits=serial.STOPBITS_ONE, # 停止位
bytesize=serial.EIGHTBITS # 数据位
)
if ser.isOpen():
print("串口打开成功")
else:
print("串口打开失败")
# 写入数据
data_to_send = "Hello from Python".encode('utf-8')
ser.write(data_to_send)
print(f"发送数据: {data_to_send.decode()}")
# 读取数据
time.sleep(1) # 等待一段时间确保数据接收完成
received_data = ser.read(ser.in_waiting or 1)
print(f"接收到的数据: {received_data.decode()}")
# 关闭串口
ser.close()
import serial 和 import time 导入了处理串口通信和时间延迟的模块。serial.Serial() 创建一个串口对象,并设置相应的参数(如端口、波特率等)。ser.isOpen() 检查串口是否成功打开。ser.close() 关闭串口连接。请根据实际使用的串口设备和配置调整代码中的参数。
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站