Python串口通信


Python #串口通信2012-11-27 23:41

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

相关代码:

import serial
from time import sleep
ser = serial.Serial('/dev/ttyUSB0', 2400, timeout=1) # http://yige.org/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)


相关文章

粤ICP备11097351号-1