为什么我的'为'循环不循环?

时间:2016-08-06 21:10:15

标签: python pyserial

以下python脚本应该执行以下操作:

  • 等待按键,然后
  • X1650 Y0 Z0发送到嵌入式设备,然后
  • 使用响应
  • 逐字节填充变量line

Altough print (ser.in_waiting)声称输入缓冲区已正确填充,for没有迭代它。

代码:

import serial
import time

# configure the serial connections
ser = serial.Serial(
    port='COM3',
    baudrate=9600,
)

while 1 :
    # Wait until user presses a key
    eingabe = input("PROMPT >> ")

    # Send text string to embedded device
    destination_position = 'X1650 Y0 Z0\r\n'
    ser.write(destination_position.encode('ascii'))

    # Wait until embedded device responds
    while ser.in_waiting == 0:
        time.sleep(0.1)

    # How long is the response?
    print ('The response is: ')
    print (ser.in_waiting)
    print (' bytes long')

    # Traverse through the queue
    line = []
    for c in ser.read():
        line.append(chr(c))
        print(line)

输出:

D:\7-Thema\Programmieren\projects\robot\remote-control-scripts>python test.py
PROMPT >> GO!
The response is:
39
 bytes long
['X']
PROMPT >>

1 个答案:

答案 0 :(得分:2)

您必须指定要读取的字节数。但我不知道返回类型,所以当你打印一行时,你会看到:)然后你可以相应地转换

line = ser.read(ser.in_waiting)
print("%r"%line)

以下是文档link