我在尝试从COM端口读取数据时遇到问题我不知道问题是什么..这是我用来发送和接收的代码数据通过com端口.com端口连接到STM32板,STM32板发送数据显示到com端口..我附加' \ 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 抱歉,我无法粘贴总输出,所以我已经包含了输出的截图..
答案 0 :(得分:0)
看起来你的print out
语句在你的while
循环中,它被多次调用。如果我正确地得到了你想要的输出,那么这不是你想要的 - unindent print out
将它放在while
- 循环之外并且你很好:
while ser.inWaiting() > 0:
out += ser.readline()
print out
答案 1 :(得分:0)
serial.readline()
仅接受' \ n'作为行分隔符,它等到换行符(除非明确指定serial.timeout
与None
不同)。所以我会选择一个更简单的循环:
while True:
out = ser.readline()
if not out or out == "exit":
break
print out
serial.inWaiting()
返回输入缓冲区中的符号数,在这种情况下似乎无关紧要。