1

我在尝试从 COM 端口读取数据时遇到问题我不知道是什么问题.. 这是我用来通过 com 端口发送和接收数据的代码。 com 端口连接到将要显示的数据发送到 com 端口的 STM32 板。我在要显示的字符串的末尾附加了 '\n'。所以这是代码

import serial

ser.port = "COM4"
ser.baudrate = 9600
ser.bytesize = serial.EIGHTBITS #number of bits per bytes
ser.parity = serial.PARITY_NONE #set parity check: no parity
ser.stopbits = serial.STOPBITS_ONE #number of stop bits
ser.isOpen()

print 'Enter your commands below.\r\nInsert "exit" to leave the application.'

while 1:
    input = raw_input()
    if input == 'exit':
        ser.close()
        exit()
    else:
        ser.write(input.encode('ascii')+'\r')
        out = ''

        while ser.inWaiting() > 0:
            out += ser.readline()

            print  out

这是预期的输出

Different commands offered are as follows: 
''dis''                 Displays contact list
''crt name number''     To create contact list
''del name''                To delete contact details
''edt existingName newName number''      To edit contact details
''clog''                    To display calllog details
''cin''                 Displays only incoming call details
''cout''                    Displays only outgoing call details
''cmis''                    Displays only missed call details
''rvc number''          To receive a call
''mkc number''          To make a call
''mkc name''                To call from contact list
''clogc number''            To call from calllog list
''cdel''                    To delete callLog details

但我得到了这个 http://s15.postimg.org/sg9pvr20r/Untitled.jpg 抱歉,我无法粘贴总输出,所以我已经包含了我的输出截图..

4

2 回答 2

0

看起来您的print out语句在您的while-loop 中,它被多次调用。如果我正确地得到了你想要的输出,这不是你想要的 -print out将它放在你的while-loop 之外,你很好:

while ser.inWaiting() > 0:
    out += ser.readline()
print  out
于 2015-04-04T09:04:18.453 回答
0

serial.readline()仅接受 '\n' 作为行分隔符,并且它一直等到换行符(除非显式指定serial.timeout不同)。None所以我会选择一个更简单的循环:

while True:
    out = ser.readline()
    if not out or out == "exit":
        break
    print out

serial.inWaiting()返回输入缓冲区中的符号数,在这种情况下似乎无关紧要。

于 2015-04-04T14:43:14.657 回答