pySerial切断文件中的文本

时间:2015-02-06 14:18:22

标签: android python serial-port pyserial

我正在尝试通过串口打印出Android上文件的内容,它只是截断了一半。

我的代码如下:

ser = Serial('/dev/ttyUSB0', 115200, timeout=0)
ser.write(' cat /sdcard/dump.xml \r\n')
sleep(5)
while ser.inWaiting():
    print ser.readline()
ser.close()

Cat在我的串口终端内工作没有任何问题,因此必须使用Serial类进行一些设置。它有一些maxlimit?我试图用它的变量玩一下,但似乎找不到任何有用的东西。

1 个答案:

答案 0 :(得分:0)

问题似乎是inWaiting()返回false,导致读数停止。也就是说,如果你足够快地循环,就不会有任何数据在等待" (因为你只是阅读它并循环播放)。

另请注意,readline()没有超时(= 0)将会阻塞,直到它看到换行符,这意味着您可能会陷入循环。

最好将超时时间增加到例如一秒钟,并附加一个相当大的read()附加到字符串(或列表)。当你已经用完缓冲区并用结果做任何你想做的事情时退出阅读。也就是说,如果没有办法知道你什么时候收到了所有东西。

ser = Serial('/dev/ttyUSB0', 115200, timeout=1) # NB! One second timeout here!
ser.flushInput() # Might be a good idea?
ser.flushOutput()
ser.write(' cat /sdcard/dump.xml \r\n')
sleep(5) # I really don't think you need to sleep here.

rx_buf = [ser.read(1024)] # Try reading a large chunk. It will read up to 1024 bytes, or timeout and continue.
while True: # Loop to read remaining data, to the end of the rx buffer.
    pending = ser.inWaiting()
    if pending:
        rx_buf.append(ser.read(pending)) # Read pending data, appending to the list.
        # You'll read pending number of bytes, or until the timeout.
    else:
        break

rx_data = ''.join(rx_buf) # Make a string of your buffered chunks.

免责声明:我还没有配备串口的Python解释器,所以这不是我的首选。

相关问题