# “Where am I” with GPS

Today I am going to talk about GPS and how you can harness its power for mobile robots. We shall see how it works in some detail and especially from a robotics point-of-view. Next, we will look at some GPS modules/ GPS ICs out there and they can be used. I have with me a GPS module from ublox and I shall try getting data out of it with my Arduino board.

## How GPS Works & History

There are several good sources out there which explain how GPS works. This is my attempt to shine some light on what is happening. In the 1970s US airforce started developing positioning system for their own aircraft navigation. Their prototype system in the 1960s was a ground-based system. Let me give some details on this prototype system. This system later on developed as what we call today GPS or Global Positioning System.

#### The Early Prototype

It all started in 1960s during the era of cold-war. The US airforce was exploring better ways to navigate the Earth. They did this rather small project (small for them but still cost 10s of millions). On the ground, they had 4 transmitters (at various locations separated by few 100s of Km) which transmitted some fixed and synchronized data. What I mean with this is that each of the transmitters sent exactly the same data at the same instant of time. However, there is some time delay for these electromagnetic waves to reach the receiver (a receiver is attached to the body). Say the transmitter (call it transmitter-A) it is 100 Km (or 10^5 m) from the body, in this case, the body sees a time delay of about 0.33 milli-sec (speed of the light is 3×10^8 m/s). So if the body can measure this time delay and since the body already knows what data it expects to receive from the transmitter, it will know how far it is from the transmitter. Note, it just knows how far it is, but have no clue as to where it is exactly. So it can be anywhere on a sphere of radius ‘R’. Say it also receives data from transmitter-B and figures out it say ‘R_b’ distance from transmitter-B, similarly with transmitter-C and transmitter-D. This gave them 4 equations of spheres (x^2+y^2+z^2=R^2). So once the body solves these equations for unknows x,y,z which are pinpoint positions you have effectively localized yourself. Only 3 are enough but they kept 4th for verification. So in conclusion positioning just boils down to solving equations of spheres. I have made this sound too simplistic but it took US airforce 100s of people and 10s-100s of millions of dollars and 10 years to get it to work. Needless to say, it was a classified project at that time.

The next step they embarked onto was putting these transmitters onto geosynchronous orbits (about 36,000Km in the sky, a plane flies 10Km up, so these satellites are way-way-way up.). And to their surprise, the time delay logic just didn’t work.!! This baffled scientists and especially physicist of the day. Soon enough it was figured out that we need to apply relativistic compensation (Einstein’s Special Theory of Relativity). The central point was that the distance, here 36,000km was significant compared to the speed of light and the formula, speed is distance divided by time doesn’t apply. Time dilation was at play here. Read this for a somewhat elaborate discussion on GPS and Relativity. So in retrospect, if Einstein had not figured out relativity in 1915, we probably would be still baffled about what happens when we put our transmitters in the orbit and GPS definitely wouldn’t be a common thing that we take for granted. This is one of the practical uses of the Theory of Relativity.

Another thing that was realized was that the synchronization’s accuracy must be of the order of nanoseconds. Such high accuracies are needed because the electromagnetic waves are traveling at 3×10^8 m/s. And an inaccuracy of a few nanoseconds would make the localization system useless. FYI the normal watches (even the digital ones) drift about 1min or so in a year, which is about the accuracy of a few 100s micro-seconds. Blame the quartz crystal for this. Network Time Protocol (NTP) which most computers use to correct itself every few days was as a result of the development of the GPS system. The accuracy still was few 100s of nanoseconds.

Accurate timekeeping prompted the development of atomic clocks. These clocks work on certain electron transition from their orbits. The first accurate atomic clock, a cesium standard based on a certain transition of the cesium-133 atom, was built by Louis Essen and Jack Parry in 1955 at the National Physical Laboratory in the UK. There is quite a bit of high-end physics involved here, which is well beyond my scope of understanding, but well…..God save the Queen…!

The time from the atomic clock is now open to the public, see time.gov. Eventually around 1975 the US military lay supreme as they were the only ones to have geolocalization capabilities. The USSR had it only at the start of the 1980s. Today (2019) best atomic clocks have an accuracy in the range 10^(-16)sec.

#### GPS Opens for Civilian Use

From 1970s-1983 GPS system was in use by the US military for their internal purposes. All these developments were hidden from the public eye. However, the Korean Air Flight 007 incident prompted the then US president Ronald Regan to open up the system for civilian use to avoid the repeat of the incident. So in 1983 GPS was thrown open to the public. Little did they know then, how GPS will change our lives several years later. In 1991, a 1.25 Kg receiver was commercially available which was a massive leap from 16Kg receivers which were used in civilian aircraft of 1980s. From 1998-2004, the administration of the satellites was moved to a newly formed agency (which still stands today and manages the satellites, https://www.gps.gov/ ). This agency launched a few more satellite for global coverage and redundancy, also standardized a lot of technicalities related to GPS, most notably it introduced the gold-code. Additionally GPS communication frequencies and the underlying protocol were also standardized. After this standardization, things moved rather at bullet-train pace from a snail pace for the previous 2 decades.

So, if you understand the concept of wireless communication and could build receivers from scratch you could build yourself a GPS localization system. All the details on protocol were (and still are) open and available at GPS.gov website. In an earlier blog post, I talked about wireless communication from scratch, you might want to check that out as well. Qualcomm in 2004-2005 did just that, they launched a chip suitable for mobile phones which can receive this GPS gold-code and decode it to GPS-coordinates. Here is the official press release from Qualcomm dated to 2005. Soon enough by 2010-2015, almost all phones had this device and we all could use the power of GPS with ease. 2010 onwards we have also witnessed several location-based services like maps, restaurant recommendation etc. Applications of GPS on moving platforms is an even more recent thing with commercial aerial drones becoming available since 2012 or so. Cargo tracking, autonomous farm tractors are some of the upcoming developments which rely on GPS.

#### GPS Developments 2010 onwards

More recently, several countries have developed their own clones of GPS. Russia (GLONASS), China (BeiDou), European Union (Galileo), India (IRNSS or GAGAN), and Japan (QZSS). Although these systems are useful from a geopolitics standpoint, they are essentially just clones of GPS. Ordinary GPS ICs often have support for GLONASS and have gotten incredibly cheap at around US\$5 or so. There are also several hobby level GPS boards available for as cheap as US\$10. I am not aware of such cheap boards for other systems though. I have with me UBLOX 8M series (which I bought for around US\$12) which has GPS (and a GLONASS) receiver chip and an inbuilt micro-controller which gives me GPS coordinates. I will play around this board, details in the next section.

GPS.gov have also launched RTK-GPS which is highly accurate (upto 10cm or so) GPS positioning. Qualcomm has even launched an ic-chip for RTK-GPS in 2015-2016. Sparkfun has a hobby RTK-GPS board which uses this chip. It comes in at US\$ 200 and you need two, so if you want to build stuff with RTK-GPS be prepared to burn US\$400 per device extra, but it is definitely possible today (2019) even for hobbyists. DJI Phantom4-RTK drone is a professional grade drone which uses RTK-GPS and was launched in 2017. This comes in as great value for drone mapping applications. However, for aerial photography, phone location-based services ordinary GPS with its accuracy at 2-5m is sufficient. We sapiens are yet to see highly commercialized applications of super accurate positioning systems like the RTK-GPS.

#### Some Current Research

Three major themes I see for localization are: a) Localization with Wifi routers, b) Visual Localization, c) Deep Space Navigation System

a) Wifi & Smart Lights. Using wifi it is possible to localize. Here is how it works. The wifi router’s positions are known and based on the signal strength that you receive (on your phone, called RSSI) it is possible to estimate how far is the router. The core logic is that the signal strength is weaker as you move away from the wifi router. You do this with 3 or 4 or more routers and it comes to the exact same problem GPS solves – equation fo spheres. But since it is almost impossible to get the locations of 100s of wifi routers in an arena with good accuracy and because there is a lot of electromagnetic interference, the accuracy of such systems is incredibly poor and not enough for robotic applications.

Another way is using flicker of the tubelights. The tubelights (or LEDs) can be made to flicker at say 100Hz. Different tube lights are made to flicker at different frequencies. It works in the same principle as wifi localization, the accuracy is better. See my friend Liang Qing’s recent IROS paper titled, “Indoor Mapping and Localization for Pedestrians using Opportunistic Sensing with Smartphones”. They are already selling their special led bulbs to malls as pilot projects. Likely indoor robots can make use of such systems in the coming future.

b) Visual Localization: Due to the ubiquity of cameras, localization with the camera is getting a lot of attention. So far it is possible to do local localization (GPS is global localization). Google, SLAM (Simultaneous Localization and Mapping using a camera) to know more in this direction. DJI’s Mavic drone already implement a toned down version of SLAMs which is behind its indoor flying and obstacle avoidance system. Some drone show operators like dronisos are also making use of QR code carpets for localization, while verity studios have made their own localization system (whose workings are not public).

c) Deep Space Navigation System: As of 2019, Nasa’s Jet propulsion lab is developing a deep space navigation system. This system will be similar to GPS in some sense but will be usable outside of Earth. There will be satellites orbiting the sun rather than the Earth. Their objective behind this system is better navigation for future missions to Mars, Venus, and other planets. When this system becomes a reality the space crafts designing becomes easier and more cost-effective and rely less on super expensive gravity sensors (aka space-grade IMUs). We already have super-accurate atomic clocks which are a key ingredients to localization, so this looks like a deja-vu moment to the development of GPS. We sapiens have no clue what can deep space navigation system and space travel do for us and where this would lead us.

All this development may sound quite fascinating (well it is…but…) and give you a feeling that GPS like systems is invincible, or in Indian context have become Aswathama. Reality is far from it. Let me give you my thoughts.

GPS doesn’t work indoors: Talk situations like inside your home, tunnels, malls, even rainy and cloudy sky you are out of luck with GPS. At best you will have inaccurate localization and at worst no signals. The main point is if you cannot receive those gold-codes you can’t localize.

GPS doesn’t work in Urban Canyons: If you have walked around in HK (or any other city which has tall buildings (30 floors+) on both sides of the road, you might have noticed using google map with GPS is even worse than your own intuitive sense. A wrong localization is a lot of time worse than no localization. In such cases, I just keep my phone in the pocket and read the street names and navigate myself. Even RTK-GPS is not going to solve this issue. Increasing the transmission power of the satellites can solve this issue though. But remember you are getting to use those satellites for free from US taxpayers money so can’t change that. God bless America..!

Security Risk: With GPS in all our mobile devices we have opened ourself to huge security risk. Imagine a fraudster gets access to your GPS location. Easily possible with trojan horse app on your phone. Or even worse, what happens if the US government suddenly decides to charge (or disbars your country) from using GPS? The satellites sometimes get out of sync and as a result gives you wrong location data. It actually happens quite often, almost 1-2 times a week. For location-based phone services, this is not as much of an issue. However, for things like autonomous drones or tractors which are coming very very soon, it will be a disaster. For people dealing with GPS on moving platforms keeping these things in mind is crucial. What happens when the mispositioning of the satellites is deliberate?

GPS Jamming: Another type of attack is GPS jamming. An attacker can generate electromagnetic waves at the frequency that GPS receiver works and send it noise data. This will render the GPS device useless. Mind you that this is illegal in theory but in practice, the local police force has no power (and no equipment) to stop such attacks. In the 2018 HK drone show that failed, it was speculated that some unknown attacker had used GPS-jamming. Read the story here. But the exact cause on what exactly happened remained unknown (at least to the public).

## GPS Questionaire

There is a lot of misconception out there even amongst tech-savvy people. I am putting up some common questions that turn up. Before reading the answers I recommend try answering it yourself first in your mind and then read my answer. Of course, my answers could be a bit mis-directed (for which I appreciate a correction from the reader) but I am trying to be as accurate and precise as possible.

Q) Can governments track me if I use GPS?
Ans.) The GPS itself is not to be blamed here. It is the cell phone and the software in it that enable spying. GPS receiver itself has no transmitter in it. So if you use GPS in a standalone way there is no way for the likes of NSA to know of your whereabouts.

Q) Why is the GPS free?
Ans.) Because the US government decided so. There is a large economy that is heavily dependent on GPS and it doesn’t cost as much to run 24 or so currently active satellites. A few millions (dollars) is supporting an economy of billions, despite some countries getting a free ride.

Q) What does the military use GPS for?
Ans.) Cruise missiles, military drones, fighter planes, personel localization.

Q) Why does GPS not work on thundering and rainy days?
Ans. Too much electromagnetic interference. Those electromagnetic waves are traveling a distance of 20-30K Km to reach your receiver. There is severe attenuation. Thundering and lightning are known to cause huge electric potential difference which in turn cause fluctuating magnetic fields.

Q) What’s the point of other localization systems like GLONASS or even indoor localization when we have RTK-GPS?
Ans.) RTK-GPS only works outdoors. GLONASS and other system are a result of geo-political risk management. For example, if you are Russian military you don’t want to be dependent on US government.

Q) What are some industrial uses of GPS?
Ans.) Aircraft navigation, Construction. Those island reclamation near Dubai (Palm Jameira etc) wouldn’t be possible if construction crew cannot tell where they are laying the sandbars exactly. Shipping container tracking.

Q) Why is GPS device only 1 Hz ?
Ans.) The electromagnetic waves that are generated by the satellite has to travel 30K km. Signals are often corrupt and need to listen to a lot of signals to understand the message. This usually cannot be done faster than 1 times a second or so.

Q) Why is my GPS app showing me the wrong location on the map?
Ans.) The GPS device is likely giving correct data. The plotting of this co-ordinates on the map is the cause. So most likely it is the problem of the mapping software and not the GPS itself.

Q) I do need an internet connection to use GPS?
Ans.) No!

Q) Will I get GPS coverage all over the earth ?
Ans.) Generally yes. However, the satellites are so positioned so the populated area get better coverage. So in places like Siberia, north Canada, Antarctica the coverage might be a bit weak. On popular sea routes GPS does work but on remote places like south Indian Ocean, middle of Pacific Ocean coverage might be non existent.

## Time for Field Test

I have with me two GPS devices. One is a Taiwanese GlobalSat’s G-Star 4 (Model No. BU-353S4) and another is Swiss Ublox M8N. I bought it from Taobao (China’s Amazon) for about US\$ 25 and US\$15 respectively. G-star connects directly to a PC with standard USB (so makes it less of a hassle to use for non-hardware savvy guys or girls. The ublox has 4 wires UART which are GND, VCC, Rx, and Tx. These can be connected to a USB-TTL device for connection to a PC or a phone or a tablet (if need be) or directly to an Arduino. A while ago, I had done a blog post where I got my HC-12 (Lora Bluetooth) module working which has exactly same wire configuration as this GPS device. Some of my info from there might come in handy as well.

It is useful to know that, GlobalSat also sells modules which connect with a serial connection (4 wires) rather than the whole package with USB casing. Similarly, U-Blox is a general wireless communication company which sells various other products. Modules are usually available at significantly cheaper prices and manufacturers like Globalsat easily can give you bulk discounts for 1000+ units. I am not promoting any manufacturer here, but I tend to prefer GlobalSat (because they answer my emails…lol).

Let’s talk about important technical specs you should be worried about when choosing a module. You need to know the baud rate and the protocol your device uses. NMEA 0183 is the most common protocol. There are parsers out there for it in most common programming languages. For python, users see this. I am pulling out a specs table for my Ublox device. It is quite helpful to quickly go through the datasheets, most of the specs are quite self-explanatory:

#### My GlobalSat Device with PySerial and PyNmea2

I use pyserial to read serial device data. Reading serial device is almost like reading from a file on Linux. This can easily be accomplished in your favorite programming language/environment. Then I use pynmea2 to parse the NMEA formatted data to retrieve the geo-coordinates ie. latitude and longitude. Go to my github-repo-gps to see the code and some related utils. The only thing to note for this device is that it communicates at baud rate of 4800 (and not the usual 9600).

``# Python script to test a GPS device import serial  #sudo pip install pyserial import pynmea2 #sudo pip install pynmea2 # Open File/Device for reading # You may need to run this script as sudo as not all devices can be accessed by normal users in Ubuntu. But you can configure your udev-rules after which you won't need to sudo. ser = serial.Serial( '/dev/ttyUSB0', 4800 ) #                     ^^(Device file)   ^^^baud rate while True:     print '\n---'     # Get data from the device     line = ser.readline()     print "raw data:", line     # Parse the data and print     try:         msg = pynmea2.parse( line )         print 'lat=', msg.lat,         print 'lon=', msg.lon,         #print '#sats=', msg.num_sats,         print 'datetime=', msg.datetime         Q = {}         Q[ 'latitude' ] = msg.latitude         Q[ 'latitude_minutes' ] = msg.latitude_minutes         Q[ 'latitude_seconds' ] = msg.latitude_seconds         Q[ 'longitude' ] = msg.longitude         Q[ 'longitude_minutes' ] = msg.longitude_minutes         Q[ 'longitude_seconds' ] = msg.longitude_seconds     except:         continue``

#### U-Blox GPS with Arduino / USB-TTL Device

I set up the usual serial communication. Remember Tx of the device goes to Rx of Arduino(or USB-TTL device) and Rx of the device goes to Tx of Arduino. I am using 3.3 volts to power this device. Although the datasheet recommends the use of 3.3volts, it also says this device can be used with 5 volts. There is no reverse polarity protection, so double check the vcc and gnd before connecting your device. It communicates at the baud rate of 9600. So if things don’t work for you, you may want to double check the baud rate. Finally, TinyGPS [ TinyGPS-github ] seems to be a compact enough implementation of an NMEA0183 parser for Arduino.

The GPS device also works fine with the Arduino (I tried with Teensy2++). Here is the code that I used:

``// Arduino Sketch for UBLOX-serial communication // Teensy2++ TX: 25 and RX: 4 #include <AltSoftSerial.h> void setup(){     altserial.begin(9600) } void loop() {     while( altserial.available() ) {          // If data is available from the device sent it to serial monitor (aka to the PC)          Serial.write( altserial.read() );     } }``

## Conclusion

We looked at the history of GPS and how it came to be where it is now. Hopefully, the reader can now appreciate the GPS devices we take for granted. We looked at two GPS devices. The main point was to understand the difference between the consumer device and a module. We realized both are in fact very similar devices at the core.

We tried to access the data from the device through serial communication. We performed this with pyserial on our Ubuntu laptop and on Arduino with AltSerial. Finally, we used NMEA0183 parsers to interpret the data coming from the GPS device. All the code related to this test can be found in github-repo: gps-test.

Some more things that need to be explored. a) Get the TinyGPS NMEA parser (see this and this) for Arduino working. b) Test and verify the functionality like: number of GPS available, the status of the device like fixing, fixed, moving etc. c) I have read there are issues when multiple devices are connected to arduino serial. Need to verify that multiple devices (eg. HC-12, GPS, IMU, barometer works together). d) Instead of playing with wires (which is also prone to stupid errors) one must use connectors like 2P, 3P, 4P etc (see this). Also, it is a good idea to make one of the Arduino as a serial tester. So permanently keep the serial test code on that arduino and do not change it. Such a device will come in handy for testing serial devices in the future.

All in all, we learned how we can get access to live GPS coordinates using devices available on the market.

## One thought on ““Where am I” with GPS”

1. ΞXΤЯ3МΞ says:

awesome!