代码之家  ›  专栏  ›  技术社区  ›  Robin

Python串行速度慢

  •  -3
  • Robin  · 技术社区  · 7 年前

    我已将Arduino UNO连接到我的raspberry pi,并希望使用Python脚本读取连接的传感器。 当我尝试从Arduino IDE读取传感器数据时,它工作得非常快,但使用Python时速度非常慢。

    这是我的代码:

    import serial
    from subprocess import call
    from time import sleep
    
    ser = serial.Serial('/dev/ttyACM0')
    ser.baudrate = 9600
    
    a = 0
    stop = False
    
    file = open("PulseData/MasterArrayData.txt","w")
    if(ser.isOpen() == False):
            ser.open()
    
    print("Start scanning")
    
    while stop == False:
            test = ser.readline()
            try:
                    testInt = int(test)
                    if testInt > 100 and testInt < 800:
                            print test
                            file.write(str(testInt))
                            file.write("\n")
                            a = a+1
            except ValueError:
                    print "Not an integer"
            if(a == 400):
                    stop = True
            sleep(0.1)
    
    file.close()
    
    
    call(["./main", "PulseData/MasterArrayData.txt"])
    

    我已经尝试使用更高的波特率,或更短的睡眠时间,但没有成功。

    我读到PyTTY可以提高速度,但遗憾的是,我没有找到任何关于这方面的文档。

    我感谢你的帮助。

    1 回复  |  直到 7 年前
        1
  •  0
  •   gre_gor    7 年前

    从…起 comment by jasonharper :

    在两次阅读之间睡上十分之一秒绝对可以保证你每秒的阅读量少于10次。当串行端口缓冲区不可避免地溢出和字符丢失时,偶尔会出现垃圾值。