python 监听串口数据并写入到文件

import serial
import time

# ser=serial.Serial("/dev/ttyUSB0",19200,timeout=0.5) #使用USB连接串行口
def main():
    ser = serial.Serial(port='/dev/ttyUSB0',baudrate=115200,parity=serial.PARITY_NONE,stopbits=serial.STOPBITS_ONE,bytesize=serial.EIGHTBITS)
    data = ''

    while True:
        data = ser.read(20)
        print(data)
        f = open('test.txt', 'a')
        f.writelines(data.decode('utf-8'))
        f.close()

if __name__ == "__main__":
    main()

你可能感兴趣的:(python,串口)