簡體   English   中英

使用pyserial與調制解調器通信

[英]communication with modem using pyserial

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

  • 發送AT命令到調制解調器
  • 盡快返回調制解調器答案
  • 在超時的情況下返回例如None
  • 處理腳本和調制解調器之間的通信最合理,健壯和容易。

這是片段:

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提供一段只返回整個緩沖區內容的代碼。 此外,我是否應該在開始時刷新輸出,以避免之前在輸出緩沖區中有一些廢話?

謝謝Alex

對於讀取超時,使用param timeout=2創建Serial對象。

Mi食譜是:

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM