Python3通过数据缓存区读取串口数据

来源:互联网 发布:js改变css样式class 编辑:程序博客网 时间:2024/06/05 18:55

一种较为安全的数据读取方式

#_*_coding:utf-8_*_import serialimport timeser = serial.Serial("/dev/ttyUSB0",9600,)  #Serial类实例化一个对象def main():    while True:        count = ser.in_waiting() #获取接收缓存区的字节数        if count!=0: #如果有数据            recv = ser.read(count)  #读取数据        ser.flushInput()    #清空缓存区        time.sleep(1)   #延迟1sif __name__ == '__main__':    try:        main()    except KeyboardInterrupt:   #按下ctrl-C时需将串口关闭        if ser!=None:            ser.close()