繁体   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