Alex
Alex

Reputation: 44385

communication with modem using pyserial

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 ser:

Here is the snippet:

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

My question: Is this good, robust code, or can pieces be changed/simplified? I especially do not like the read(n) 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?

Thanks Alex

Upvotes: 3

Views: 3077

Answers (1)

SmartElectron
SmartElectron

Reputation: 1451

Create the Serial object with the param timeout=2 for read timeout.

Mi recipe is:

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

I think that this is a good form of manage the communications with the serial port.

Upvotes: 1

Related Questions