886.Python串口通信

串口通信http://pypi.python.org/pypi/pyserial

相关代码:

import serial
from time import sleep
ser = serial.Serial('/dev/ttyUSB0', 2400, timeout=1) # https://salangsayang.com/Whisper/category/python
def recv(serial):
    data, quit = None, False
    while 1:
        data =serial.read(1)
        if data == '':
            continue
        sleep(0.02) # data is this interval will be merged
        while 1:
            n = serial.inWaiting()
            if n > 0:
                data = "%s%s" % (data,serial.read(n))
            else:
                quit = True
                break
        if quit:
            break
 
    return data
while 1:
    data =recv(ser)
    if data== 'c' :
        ser.close()
        break
    ser.write(data)

Author: 搬运工

发表评论