SparkFun Forums 

Where electronics enthusiasts find answers.

Tips and questions relating to the GPS modules from SFE
#127264
Hey Everyone,

Quick question really, I can send AT commands to the Telit 862GPS via Python no problems. I'm just starting out though and I want to code it robustly. I can't find a good example online, here's my attempt:
Code: Select all
# Setup Booleans!
True, False = 1, 0

def at_command(command, win="OK", fail="ERROR", delay=10):
  # Send the command
  MDM.send(command + '\r', 5)
  # Wait for the response
  for i in range(delay):
    # Listen to serial port for click
    res = MDM.receive(1)
    # See what happened
    if res.find(win) > -1:
      return False, res
    if res.find(fail) > -1:
      return True, res
  # Timed out :(
  return True, "Timed out"
What do you think?

Cheers, Dave.
#127339
Should the sleep not be between the send and the receive?

If you are using a fixed sleep between all sends and receives to pace the communication flow, you can greatly slow things down if you have lots of calls to make. I find that in many cases a busy loop works well. It will sit and wait for num bytes till such time as the timeout period has elapsed (where it returns null). Something like this:
Code: Select all
# Get num bytes from port with a timeout. Return null if no bytes 
def getLine(port, num, timeout):
	"""Doc String
	"""
	j = 0
	s = ""

	while 1:

		if (port.inWaiting() >= num):

			# Get the bytes
			s = port.read(num)

		else:
			time.sleep(0.01)
			j = j+0.01
			if (j > timeout):
				break

	return s
#127864
I've been playing with the Telit for a while now, here's my final AT sending function that has so far done everything I needed:
Code: Select all
#
# Performs AT command, returning result or False
#
def at_command(command, delay=20, win="OK", fail="ERROR"):
  # Send the command
  MDM.send(command + '\r', 5)
  # Create a buffer
  buffer = ''
  # Wait for the response
  for i in range(delay):
    # Listen to serial port for click
    buffer = buffer + MDM.receive(1)
    # See what happened
    if buffer.find(win) > -1:
      return buffer
    if buffer.find(fail) > -1:
      return False
  # Timed out :(
  return False
Cheers, Dave.