title: communication with modem using pyserial
body: <p>I did not find a reasonable good example of how to talk to a serial modem using pyserial. I have created a code snippet that should do the following, given an instantiated pyserial object <code>ser</code>:</p>
  
  <ul>
  <li>Send an AT command to the modem</li>
  <li>Return the modem answer as quickly as possible</li>
  <li>Return e.g. None in the case of a timeout</li>
  <li>Handle the communication between the script and the modem most reasonable, robust and easy.</li>
  </ul>
  
  <p>Here is the snippet:</p>
  
  <pre><code>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&lt;timeout:
      pass
  
    n = ser.inWaiting()
    if n&gt;0:
      return ser.read(n)
    else:
      return None
  </code></pre>
  
  <p>My question: Is this good, robust code, or can pieces be changed/simplified? I especially do not like the <code>read(n)</code> method, I would expect pyserial to offer a piece of code that just returns the whole buffer content. Also, do I / should I flush the output at the begin, to avoid having some crap in the output buffer before?</p>
  
  <p>Thanks
    Alex</p>