Python串口数据收发实战指南

1、确认串口信息

2、安装pyserial库

打开终端或命令行,敲入这行命令:pip install pyserial

3、python编程

import serial

def main():
    #创建串口对象
    ser = serial.Serial('COM4', 9600, timeout=1)
    if not ser.isOpen():
        print("串口打开失败,请检查设置!")
        return
    print("串口已打开")
    #准备发送的数据
    data_to_send = "Hello,Arduino!".encode()
    #发送数据
    ser.write(data_to_send)
    print("数据已发送!")
    while True:
        #读取一行数据
        data_received = ser.readline().decode().strip()
        if data_received:
            print(f"收到数据:{data_received}")
        else:
            break
        #关闭串口
        ser.close()
        print("串口已关闭!")
if __name__ == "__main__":
    main()

作者:码哝小鱼

物联沃分享整理
物联沃-IOTWORD物联网 » Python串口数据收发实战指南

发表回复