Skip to main content

Beam me up, Rosie!



How do you get from A to B?

You can't, as As and Bs are just letters in the alphabet. But if A is your house, and B is a meerkat village at your favourite safari park, you'd probably use a device equipped with GPS.  Not to be confused with UPS, who will deliver you your chosen meerkat through the post. And why on Earth would Rosie Patrol need one? Precisely, it's because she is on Earth that she needs one. Because our planet is rather big. Big enough to get lost in. And we don't want to lose our friendly plastic boxes on wheels. And maybe, eventually when she's clever enough, she'll go and defeat baddies on her own. And return home afterwards for a well deserved Earl Grey tea.

Besides, why wouldn't we want to add another three letter acronym to Rosie Patrol's repertoire?

All superheroes need:

  • One Raspberry Pi 3, running Raspbian OS
  • Computer from which you are connecting to the Raspberry Pi
  • Probably the most important bit: a GPS receiver thingmy.   There are many different types available.  We're using a USB dongle: a Diymall Vk-172.  Under the covers, we're told it is powered by a U-Blox UBX-G7020 chip.
  • We revisited this post in 2019, when we got our hands on a U-Blox Neo-6 based module, named GY-NEO6MV2, which could be interfaced using a UART serial connection.   This might be the better option, if a) the device does not have a USB port, or b) you don't necessarily want a USB stick permanently attached to the side of your device.  This update appears at the end of this post.

Already completed these missions?

You'll need to have completed the Rosie series.  Then:
  1. Lights in shining armour 
  2. I'm just angling around 
  3. Eye would like to have some I's
  4. Eh, P.I?  
  5. Lights, camera, satisfaction

Your mission, should you accept it, is to:

  • Connect the GPS receiver to the Pi.  It's a USB device.  Can you guess where we need to plug this into?
  • Install gpsd which is what we'll use to interact with the receiver
  • Test that we can contact satellites in space.  And that we can get in on the geolocation action.
  • Install gpsd-py3 to allow us to interact with gpsd, using Python3
  • Track you robot as it fights crime across the globe

The brief:

In case you were wondering, GPS stands for Global Positioning System.  Using GPS, a receiver based down on Earth (yes, that's our USB dongle thingmy) can contact a few GPS satellites in space, and obtain geolocation information.  Which means we can now make wild (but actually quite true) claims about our robot being able to contact satellites in space.   More importantly, it means Rosie Patrol can find out for herself where she is on Earth.

Drones have them.  Watches have them.  Smart phones have them.  So it's only natural that robots should have GPS too.

And surprisingly, thanks to the people who have already thought about all this (not us!), it's not very difficult to get some pretty interesting, real-life data.  Without doing too much engineering ourselves.

We'll leave what you do with that data up to you.  You could draw a map of where your robot has been.  Or maybe you'll use it to guide your creation across town.

But - for now - let's get GPS up and running.

The devil is in the detail:

Do you know how to insert a USB device into a USB port?  Good.  That's about it for the hardware.  We hope we didn't disappoint.


Next, let's dabble in a bit of Linux.  Actually, more than just a bit.  Firstly, run lsusb to see what USB devices are connected to your Pi, and what the Raspbian OS sees.

sudo lsusb
...lists USB device information


Connect the GPS receiver to the USB port on the Pi, and try again.   That's promising!  We can see a 'U-blox' device, which suspiciously looks like our GPS USB dongle thingmy.  Let's see it in another place, just to be sure. 

View the Raspbian OS's Linux kernel log (/var/log/kern.log) using cat and filter for text 'u-blox' using grep.

cat /var/log/kern.log | grep u-blox
...nothing to do with actual cats.  We are simply viewing the content of this log file.  We're interested in just the lines with the text 'u-blox'.


We can see entries from the time the device was connected.  So where is this device, actually?  And what is its name in Linux?  Looking at other log entries from around the time the receiver was connected to the USB port, more is revealed.

cat /var/log/kern.log
...still, nothing to do with cats.  This time, we want to trawl through the whole file, without grep.


This suggests that the device isn't named Harry, or Henry, or Henrietta.  It's actually called... wait for it... ttyACM0.  It's really memorable, isn't it?  Look in our /dev Linux device directory and you'll find it there, waiting to be found.

ls /dev/ttyACM0
...lists the ttyACM0 device file


...At which point you can attempt to read the raw data from the device using cat (but good luck understanding it).

cat /dev/ttyACM0
...attempts to read content of ttyACM0 device file.  Nope, not really of any use.

There is garbled text that looks suspiciously like some form of GPS geolocation data, but it's all a bit messed up really.  There's no way we can work with this.  This is where gpsd comes in.  It can do all the funny GPS language -> English translation for us, and we can only query the information that we want.

This means we need to install some Linux packages.  And we do this using apt-get.

sudo apt-get install gpsd gpsd-clients python-gps
...downloads and installs gpsd, gpsd-clients and python-gps Linux packages


Once everything's been installed, let's temporarily stop the gpsd service from starting up automatically when the Pi boots.  Why?  Because we just want to manually start it, and see how it behaves.  We'll re-enable this later.

sudo systemctl stop gpsd.socket
sudo systemctl disable gpsd.socket
sudo gpsd /dev/ttyACM0 -F /var/run/gpsd.sock
...uses systemctl to stop the gpsd service, and disable it.  We then manually start up gpsd, while pointing it at the /dev/ttyACM0 device. 


This is indeed the moment of truth.  Now, gpsd is running.  And it should be deciphering the geolocation data from our GPS receiver (and doing a better job of it, than we did when we had a peek).  To check if this is the case, we can run a helpful test tool - cgps.

cgps -s
 ...runs cgps.  And enjoy the wealth of data being provided to us by the satellites in the sky!  This really is Rosie Patrol, talking to things in space.


If everything is working successfully, you should see a neat table, with lots of useful information.  The most useful for geolocation - of course - is the latitude and longitude data, which is an important component of the geographic coordinate system that us humans use to describe a specific position on Earth.  There are other bits of useful information here too, like speed and elevation.

There's a very good reason why we're blotching out our own GPS coordinates with a big white blob.  It's because GPS coordinates tell people where you are - exactly.  Well, that is the whole point of GPS isn't it?

Never provide your GPS coordinates to people you don't know, or publish them on the Internet, unless you want them to know exactly where you are.  In most cases, there just won't be a good reason to.


So how do you make sense of these coordinates?

The easiest way to quickly visualise it, is to use Google Maps.  For example, if your Latitude says '51.188637 N' and Longitude says '2.262735 W', enter '51.188637 N, 2.262735 W' in Google Maps.


Congratulations.  Your robot is in the middle of a Safari Park.  Hopefully, somewhere near the meerkat village.  And not in the tiger zone. So far so good.  It's all working out nicely.  And we've completed the hardest part of this challenge.

The only bit remaining is to wrap it all up, using Python.  And you won't be at all surprised to know that there are some Python libraries out there that allow you to interact with gpsd.

Let's install gpsd-py using pip.

sudo pip3 install gpsd-py3
...downloads and installs gpsd-py3 Python 3 library for gpsd


Let's now fire up IPython.  All we need to do is import the gpsd library, run a connect() to hook up with gpsd, and retrieve the latest GPS data using get_current().  For position information, you can get a tuple containing your longitude and latitude coordinates using position().  It really couldn't be any easier...

import gpsd
gpsd.connect()
data = gpsd.get_current()
print(data.position())


Now, do you remember we disabled automatic start-up of the gpsd service?  We want to enable it again.  First, edit the /etc/default/gpsd configuration file to point it at our GPS receiver.

sudo nano /etc/default/gpsd
...uses Nano to open the file.  Enter the device name (ttyACM0) where it is currently blank.


Then let's enable the service again.  And start it up.

sudo systemctl enable gpsd.socket 
sudo systemctl start gpsd.socket
...uses systemctl to enable the gpsd service, and start it up

To prove the point, we'll reboot the Pi.  And check if the service is running.

sudo reboot
sudo systemctl status gpsd.socket
...reboots Pi.  Use systemctl to check status of gpsd service.


You should be able to get right back into IPython and connect to gpsd to retrieve your latest data.  This proves that our gspd service starts up automatically, and is pointing at our USB GPS receiver.

Now what you do with the data is up to you.  You could store it in a directory on the Pi, so you can draw the route your robot has taken during its mission.  Or, you could use it to control it in real time.  Could you, for example, tell it where to go based on GPS waypoints if the robot is equipped with a compass?

Here is a snippet of the Python code we used to write the longitude and latitude coordinates to a file, every second.

import gpsd
import time
import datetime

# Wait 60 seconds before connecting to gpsd
time.sleep(60)
gpsd.connect()
date = datetime.datetime.now().strftime("%d_%m_%Y_%H_%M_%S")
filename = "geo/geodata_" + date + ".txt"
while True:
    try:
        data = gpsd.get_current()
        position = data.position()
        f = open(filename, "a") 
        f.write(str(position[0]) + "," + str(position[1]) + "\n")
        f.close()
    except:
        pass
    time.sleep(1)

Configure the above using Supervisor and your Pi will start to log its coordinates to a text file in the "/geo" directory.  The longitude and latitude will be values separated by a comma, which makes it perfect for processing.  There are plenty of websites - such as this or this - that allow you to copy and paste the coordinates to plot them on Google Maps.  Here's the result of our little detour around a park.


For something so sophisticated, the steps were actually quite simple.  We can now say Rosie Patrol is 'GPS-enabled' and track her as she wanders around the meerkat village.  And hopefully not the lion zone.

Update 1 - November 2018

You can skip forward to an episode in which we field test this creation in the Brecon Beacons National Park.  Then, it went slightly over the top during its second enhancement.

Update 2 - January 2019

If we don't want to use a USB-based GPS receiver, there are serial (UART) alternatives.  These might be the preference, if the device in hand has few or no USB ports (think Pi Zero, or a ESP8266). We eventually got our hands on a U-Blox Neo-6 based GPS receiver, which has a 2-pin UART interface.  Cabling is a doddle, as it uses Pi's TX and RX UART connections, as well as the 3.3V and 0.0V (Ground) lines for power.

Pi PinGPS UART Module PinDescription
0V / Ground (any)0V (Ground)0V (Ground)
3.3V (any)Vcc3.3V used to power the module
8 (BCM 14) - TXRXUART - data
10 (BCM 15) - RXTXUART - data



The remainder of the setup steps are fairly similar to that of the USB equivalent, with the exception of the below...

Disable Pi's default console connection present on the serial interface so that it can be used by the UART interface of the GPS receiver.  This is achieved by removing text "console=ttyAMA0,115200" from file /boot/cmdline.txt.  It's always best to make a copy of the file prior to modification, just in case you need to retrieve it later.

sudo nano /boot/cmdline.txt


Also, comment out the re-spawning of the console in file /etc/inittab.

sudo nano /etc/inittab


Reboot the Pi, then change the /etc/default/gpsd configuration file to state DEVICES="/dev/ttyS0".

sudo nano /etc/default/gpsd


Restart the gpsd service, and unsurprisingly the net result is the same.  You have a different GPS receiver, and the Pi is communicating with it using the UART connection (not USB), but it is doing what a GPS receiver is meant to be doing.

Running "cgps -s" after all of this will show that you are receiving a GPS signal from the new receiver.  USB or no USB, UART or no UART, a GPS receiver remains a GPS receiver.

Information overload:

Our USB GPS receiver is based on the U-blox UBX-G7020 chipset:
Here's another guide on how to set up a GPIO receiver with a Pi (although the steps are different from ours, due to different hardware being used):
The gpsd-py3 library can be found on GitHub here:
And, finally, extensive GPSD documentation is available here:

Comments

MOST VISITED (APPARENTLY)

LoRa-Wan Kenobi

In the regurgitated words of Michael BublĂ©: It's a new dawn .  It's a new day .  It's a new Star Wars film .  For me .  And I'm (George Lucas, and I'm) feeling good .  Unfortunately for Canadian Mike, the Grammy that year was won by the novelty disco classic with the famous refrain: We love IoT, even in Planet Tatooine * . *Not true. Clearly, the Star Wars producers didn't sincerely mean the last Jedi the previous time around.  Return of the Jedi, released during the decade that spearheaded cultural renaissance 2.0 with the mullet and hair-metal , was less economic with the truth.  Either way, we're going to take inspiration from the impressive longevity of the money-spinning space-opera and reboot our franchise with some Jedi mind tricks.  Except this particular flick doesn't require an ever-growing cast of unrecognisable characters, unless ASCII or UTF counts.  In place of an ensemble gathering of Hollywood stars and starlets, we will b

Battle of BLEtain

The trolling . The doxing . An army of perplexing emojis. And endless links to the same - supposedly funny - viral video of a cat confusing a reflection from a dangling key for a golden hamster, while taking part in the mice bucket challenge. Has social media really been this immense force for good? Has it actually contributed significantly to the continued enlightenment of the human (or feline) race? In order to answer these poignant existential questions about the role of prominent platforms such as Critter, StinkedIn and Binterest, employing exceptional scientific rigour equal to that demonstrated by Theranos , we're going to set up a ground-breaking experiment using the Bluetooth Low Energy feature of MicroPython v1.12, and two ESP32 development boards with inexplicable hatred for one another.  And let them hurl quintessentially British expressions (others call them abuse) at each other like two Wiltshire residents who have had their internet access curbed by the co

Hard grapht

You would all be forgiven for assuming that bar , pie and queue line are favourite pastimes of the British .  Yet, in fact – yes, we did learn this back in GCSE maths – they are also mechanisms through which meaningless, mundane data of suspect origin can be given a Gok Wan -grade makeover, with the prime objective of padding out biblical 187-page PowerPoint presentations and 871-page Word reports (*other Microsoft productivity tools are available).  In other words, documents that nobody has the intention of ever reading.  But it becomes apparent over the years; this is perhaps the one skill which serves you well for a lifetime in certain careers.  In sales.  Consultancy.  Politics.  Or any other profession in which the only known entry requirement is the ability to chat loudly over a whizzy graph of dubious quality and value, preferably while frantically waving your arms around. Nevertheless, we are acutely conscious of the fact that we have spent an inordinate amount