2013-01-23 97 views
5

使用PySerial可以實現全雙工通信嗎?具體而言,是否有可能在需要時連續監控端口以進行輸入和寫入?我想應該可以使用線程(而串行接口是全雙工的?)。如果不是,不傳輸時監控串口的最佳方法是什麼?超時?PySerial - 全雙工通信

編輯:這是我的嘗試。此代碼針對TI的CC2540藍牙LE芯片。在發送GATT發起消息我預計的答覆(詳細介紹了芯片的工作參數)...我得到什麼,雖然

import serial 
import threading 
from time import sleep 

serial_port = serial.Serial() 

GAP_DeviceInit = \ 
       "\x01\x00\xfe\x26\x08\x03\x00\x00\x00\x00\x00\x00\x00\x00\ 
       \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\ 
       \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00" 

def read(): 
    while True: 
     data = serial_port.read(9999); 
     if len(data) > 0: 
      print 'Got:', data 

     sleep(0.5) 
     print 'not blocked' 

def main(): 
    serial_port.baudrate = 57600 
    serial_port.port = '/dev/ttyACM0' 
    serial_port.timeout = 0 
    if serial_port.isOpen(): serial_port.close() 
    serial_port.open() 
    t1 = threading.Thread(target=read, args=()) 
    while True: 
     try: 
      command = raw_input('Enter a command to send to the Keyfob: \n\t') 
      if (command == "1"): 
       serial_port.write(message) 
     except KeyboardInterrupt: 
      break 
    serial_port.close() 

回答

3

是串口硬件全雙工。是的,您可以使用線程同時執行Rx和Tx。或者,您可以使用單個線程循環,該循環以短暫超時讀取並在讀取和寫入之間交替。

+0

你能舉個簡單的例子嗎?或者可能指示給出的代碼示例的任何即時問題。第二種方法的問題是我不知道何時需要發送數據......用戶可以隨時選擇要發送的消息 – stephenfin

+2

您並未開始讀取線程。加't1.start()' – TJD

+0

Doh!非常感謝! – stephenfin

0

您沒有指定超時,所以讀取等待接收的全部字節數,然後才顯示任何內容。