Python 串口读写

 如果没有安装 pyserial 则需要安装:

pip install pyserial

 

import serial
import threading
import time

ser = serial.Serial('COM1', 9600)


def sends():
    """ 发送数据 """
    while True:
        inp = input("请输入要发送的字符:")
        inp = inp.encode('utf-8')
        ser.write(inp)  # 发送


def reads():
    """ 读取数据 """
    out = ''
    while True:
        while ser.inWaiting() > 0:
            out += ser.read(1).decode()  # 一个一个的读取
        if out != '':
            print(out)
            out = ''


if __name__ == '__main__':
    t1 = threading.Thread(target=sends, name='sends')
    t2 = threading.Thread(target=reads, name='reads')
    t1.start()
    t2.start()

 

你可能感兴趣的:(系统,数据分析)