【问题标题】:communication with modem using pyserial使用pyserial与调制解调器通信
【发布时间】:2013-03-25 01:31:39
【问题描述】:

我没有找到一个合理的好例子来说明如何使用 pyserial 与串行调制解调器通信。我创建了一个代码 sn-p,它应该执行以下操作,给定一个实例化的 pyserial 对象ser

  • 向调制解调器发送 AT 命令
  • 尽快返回调制解调器应答
  • 返回例如超时情况下无
  • 处理脚本和调制解调器之间的通信最合理、健壮和容易。

这里是sn-p:

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 提供一段代码,只返回整个缓冲区内容。另外,我是否/应该在开始时刷新输出,以避免之前在输出缓冲区中出现一些废话?

谢谢 亚历克斯

【问题讨论】:

  • 注意行尾,你确定'\r'是正确的行尾吗?通常是普通换行符 ('\n') 或回车换行符 ('\r\n')。
  • @Joachim:这是一个我无法回答的好观点。它应该被视为问题的一部分。

标签: python serial-port modem pyserial


【解决方案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

我认为这是一种很好的管理与串口通信的方式。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-08-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多