2012-09-27 33 views
3

我沒有找到一個合理的好例子,說明如何使用pyserial與串行調制解調器對話。我創建了一個代碼片段,應該做到以下幾點,給定一個實例化對象pyserial ser使用pyserial與調制解調器通信

  • 儘快發送AT命令到調制解調器
  • 返回調制解調器答案儘可能
  • 返回例如在沒有超時的情況下無
  • 處理腳本和調制解調器之間的通信最合理,健壯且簡單。

下面是摘錄:

def send(cmd, timeout=2): 

    # flush all output data 
    ser.flushOutput() 

    # initialize the timer for timeout 
    t0 = time.time() 
    dt = 0 

    # send the command to the serial port 
    ser.write(cmd+'\r') 

    # wait until answer within the alotted time 
    while ser.inWaiting()==0 and time.time()-t0<timeout: 
    pass 

    n = ser.inWaiting() 
    if n>0: 
    return ser.read(n) 
    else: 
    return None 

我的問題:這是很好的,健壯的代碼,或者片被改變/簡化?我特別不喜歡read(n)方法,我希望pyserial提供一段只返回整個緩衝區內容的代碼。另外,我/我是否應該在開始時刷新輸出,以避免在輸出緩衝區中存在一些廢話?

感謝 亞歷克斯

+0

注意行結尾,你確定''\ r''是正確的行結尾嗎?通常它是簡單的換行符(''\ n'')或回車符和換行符(''\ r \ n'')。 –

+0

@Joachim:這是我無法回答的一個好點。它應該被視爲問題的一部分。 – Alex

回答

1

與帕拉姆timeout=2讀超時創建串行對象。

彌食譜是:

def send(data): 
    try: 
     ser.write(data) 
    except Exception as e: 
     print "Couldn't send data to serial port: %s" % str(e) 
    else: 
     try: 
      data = ser.read(1) 
     except Exception as e: 
      print "Couldn't read data from serial port: %s" % str(e) 
     else: 
      if data: # If data = None, timeout occurr 
       n = ser.inWaiting() 
       if n > 0: data += ser.read(n) 
       return data 

我認爲這是與串口管理通信的一種好形式。

相關問題