2015-04-04 33 views
1

我正在面臨的問題,而我試圖從COM端口讀取數據我不知道是什麼問題..這裏是我正在使用的代碼通過com端口發送和接收數據。com端口連接到STM32板,它將數據發送到COM端口。我在要顯示的字符串末尾追加'\ n'。所以這裏是代碼如何通過使用pyserial一次讀取一行

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

你在哪裏打開你的連接? – Finwood 2015-04-04 08:56:21

+0

這是直接的...配置後,我們可以通過使用ser.write() – 2015-04-06 06:06:32

+0

寫入端口,當然,我只是期待一些'ser = serial.Serial()':-) – Finwood 2015-04-06 06:48:05

回答

0

看起來像你的print out聲明是在你的while裏面,它被多次調用。如果我得到你想要的正確輸出,這是不是你想要的 - 取消縮進print out把它你while -loop之外,你的罰款:

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

亞..你是正確的,但我輸入命令後需要按兩次輸入... – 2015-04-06 06:08:48

0

serial.readline()只接受「\ n」作爲行分隔符,和它會一直等到換行符(除非明確指定了serial.timeoutNone不同)。所以,我會去爲一個簡單的循環:

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

serial.inWaiting()返回輸入緩衝區,這似乎並不在此情況下重要的符號的數量。

+0

但我的COM端口一次只發送一個字符,所以我需要將所有字符存儲在變量中,然後顯示它... – 2015-04-06 02:52:42

+0

readline()爲您做它,它積累字符在內部緩衝區中,直到換行符('\ n')到來,然後將整個返回給你。這個調用是阻塞的,所以你的程序/線程什麼都不做,直到整個線路積累爲止。我還希望顯式的'ser = serial.Serial()'。 – 2015-04-06 14:04:01

+0

如果我發送多行附有'\ n',我應該怎麼做?我是否需要發送號碼行,我要先發送,這樣我就可以讀取很多行.. – 2015-04-07 07:23:47