GPS Module Interfacing with Raspberry Pi
Interfaced GPS receiver module with Raspberry Pi and display the Time, Latitude and Longitude info on the output window. Raspberry Pi read the data serially from GPS receiver using Python and C language.

Overview of GPS
- Global Positioning System (GPS) makes use of signals sent by satellites in space and ground stations on Earth to accurately determine their position on Earth.
- Radio Frequency signals sent from satellites and ground stations are received by the GPS. GPS makes use of these signals to determine its exact position.
- The GPS itself does not need to transmit any information.
- The signals received from the satellites and ground stations contain time stamps of the time when the signals were transmitted. By calculating the difference between the time when the signal was transmitted and the time when the signal was received. Using the speed of the signal, the distance between the satellites and the GPS receiver can be determined using a simple formula for distance using speed and time.
- Using information from 3 or more satellites, the exact position of the GPS can be triangulated.
- For more information about GPS and how to use it, refer the topic GPS Receiver Module in the sensors and modules section.
- The GPS receiver module uses UART communication to communicate with controller or PC terminal.
Before using UART on Raspberry Pi, we should configure and enable it. For more information about UART in Raspberry Pi and how to use it, refer the Raspberry Pi UART Communication Using Python And C topic in the Raspberry Pi section.

Connection Diagram of GPS Module with Raspberry Pi


Get GPS Location using Raspberry Pi
Let’s interface the GPS module with Raspberry Pi and will extract GPS information. We can interface the GPS module to Raspberry Pi using Python and C (WiringPi). To interface the GPS module, connect the GPS module to the Raspberry Pi as shown in the above figure.
Using Python
Let’s extract Latitude, Longitude, and time information from the NMEA GPGGA string received from the GPS module using Python. And print them on the console (terminal). By using these latitude and longitude, locate the current position on Google Map.
GPS Code for Raspberry Pi using Python
'''
GPS Interfacing with Raspberry Pi using Pyhton
http://www.electronicwings.com
'''
import serial #import serial pacakge
from time import sleep
import webbrowser #import package for opening link in browser
import sys #import system package
def GPS_Info():
global NMEA_buff
global lat_in_degrees
global long_in_degrees
nmea_time = []
nmea_latitude = []
nmea_longitude = []
nmea_time = NMEA_buff[0] #extract time from GPGGA string
nmea_latitude = NMEA_buff[1] #extract latitude from GPGGA string
nmea_longitude = NMEA_buff[3] #extract longitude from GPGGA string
print("NMEA Time: ", nmea_time,'\n')
print ("NMEA Latitude:", nmea_latitude,"NMEA Longitude:", nmea_longitude,'\n')
lat = float(nmea_latitude) #convert string into float for calculation
longi = float(nmea_longitude) #convertr string into float for calculation
lat_in_degrees = convert_to_degrees(lat) #get latitude in degree decimal format
long_in_degrees = convert_to_degrees(longi) #get longitude in degree decimal format
#convert raw NMEA string into degree decimal format
def convert_to_degrees(raw_value):
decimal_value = raw_value/100.00
degrees = int(decimal_value)
mm_mmmm = (decimal_value - int(decimal_value))/0.6
position = degrees + mm_mmmm
position = "%.4f" %(position)
return position
gpgga_info = "$GPGGA,"
ser = serial.Serial ("/dev/ttyS0") #Open port with baud rate
GPGGA_buffer = 0
NMEA_buff = 0
lat_in_degrees = 0
long_in_degrees = 0
try:
while True:
received_data = (str)(ser.readline()) #read NMEA string received
GPGGA_data_available = received_data.find(gpgga_info) #check for NMEA GPGGA string
if (GPGGA_data_available>0):
GPGGA_buffer = received_data.split("$GPGGA,",1)[1] #store data coming after "$GPGGA," string
NMEA_buff = (GPGGA_buffer.split(',')) #store comma separated data in buffer
GPS_Info() #get time, latitude, longitude
print("lat in degrees:", lat_in_degrees," long in degree: ", long_in_degrees, '\n')
map_link = 'http://maps.google.com/?q=' + lat_in_degrees + ',' + long_in_degrees #create link to plot location on Google map
print("<<<<<<<<press ctrl+c to plot location on google maps>>>>>>\n") #press ctrl+c to plot on map and exit
print("------------------------------------------------------------\n")
except KeyboardInterrupt:
webbrowser.open(map_link) #open current position information in google map
sys.exit(0)Output for Python
Output on Python IDE

Output Location on Google Map

To plot our location on Google map, we need to call URL link for Google map. We can use following link for opening google map with our extracted longitude and latitude.
http://maps.google.com/?q=<latitude>,<longitude>

Using C
We will extract the NMEA GPGGA string and print it on the output window. Here, we are using the WiringPi library written in C to read the GPS module.
To know more about WiringPi, you can refer How To Use WiringPi Library On Raspberry Pi
GPS Code for Raspberry Pi using C (WiringPi Library)
/*
GPS Interfacing with Raspberry Pi using C (WiringPi Library)
http://www.electronicwings.com
*/
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <wiringPi.h>
#include <wiringSerial.h>
int main ()
{
int serial_port;
char dat,buff[100],GGA_code[3];
unsigned char IsitGGAstring=0;
unsigned char GGA_index=0;
unsigned char is_GGA_received_completely = 0;
if ((serial_port = serialOpen ("/dev/ttyS0", 9600)) < 0) /* open serial port */
{
fprintf (stderr, "Unable to open serial device: %s\n", strerror (errno)) ;
return 1 ;
}
if (wiringPiSetup () == -1) /* initializes wiringPi setup */
{
fprintf (stdout, "Unable to start wiringPi: %s\n", strerror (errno)) ;
return 1 ;
}
while(1){
if(serialDataAvail (serial_port) ) /* check for any data available on serial port */
{
dat = serialGetchar(serial_port); /* receive character serially */
if(dat == '$'){
IsitGGAstring = 0;
GGA_index = 0;
}
else if(IsitGGAstring ==1){
buff[GGA_index++] = dat;
if(dat=='\r')
is_GGA_received_completely = 1;
}
else if(GGA_code[0]=='G' && GGA_code[1]=='G' && GGA_code[2]=='A'){
IsitGGAstring = 1;
GGA_code[0]= 0;
GGA_code[0]= 0;
GGA_code[0]= 0;
}
else{
GGA_code[0] = GGA_code[1];
GGA_code[1] = GGA_code[2];
GGA_code[2] = dat;
}
}
if(is_GGA_received_completely==1){
printf("GGA: %s",buff);
is_GGA_received_completely = 0;
}
}
return 0;
}
Output

Note: As we interfaced GPS module with Raspberry Pi 3, we used /dev/ttyS0 serial port for UART communication. Those who are interfacing it with Raspberry Pi 2 and previous model, you should use /dev/ttyAMA0 instead.
Components Used
Powered by
Downloads
Comments72
Join the discussion — share a question or tip.
- SB
First of all, I would like to thank you. I communicated with the C language source you provided. Thank you so much. I would like to receive the source code to store the received sensor data. I don't know C language at all, so I just copied this part to see if it works. (Like some others, no python code.) Help saving the data would be appreciated. If you are kind, I would be more grateful if you could link to the above C programming source code and let me know. kamcho2000@naver.com
- KR
hello sir, im facing problem on getting data of gps, while i have setup and influxdb for store all the data collected. in my case i will view the data in grafana, in my grafana server it the gps data will be visualize as realtime moving geographical view. my problem is i can get the gps data but for few minutes its not shows any data and after that it showing back. can you please help me.
- SU
Hi, I need one help. I tried running your c code and it works fine with me. But I need to get the GPRMC data. would be a big help. Thank you.
- SI
Instead of NMEA string i am getting b'' as an output... I tried taking it outside also still nothing expect b'' can you help me....The red led of gps module is blinking...
- IV
So if this is the first project you are doing on you're raspberry pi 4 B, you do have to follow http://www.electronicwings.com/raspberry-pi/raspberry-pi-uart-communication-using-python-and-c to get the UART correct right? Thanks in advance!
- FA
Was able to get interface up and running. Issue arises when plotting in google maps. Is there a way to return a west indicator for longitude? My location on the map was a different country altogether. That is the only thing I could see that might be a problem.
- SA
I,m getting an error like this: "NMEA Time: NMEA Latitude: NMEA Longitude: Traceback (most recent call last): File "gp.py", line 51, in <module> GPS_Info() #get time, latitude, longitude File "gp.py", line 20, in GPS_Info lat = float(nmea_latitude) #convert string into float for calculation ValueError: could not convert string to float:"
- AB
Replying to @lokeshc
Hello, my latitude and longitude printing doesn't work properly, what can i do to get them ?
- SR
Hi, I am trying to get the GNGGA string from the RTK-Gnss antenna through the TCP. When i try the code in python3 it says the following error: TypeError: a byte like object is required not 'str'
- PR
Getting this error.. Traceback (most recent call last): File "/usr/lib/python3/dist-packages/serial/serialposix.py", line 265, in open self.fd = os.open(self.portstr, os.O_RDWR | os.O_NOCTTY | os.O_NONBLOCK) PermissionError: [Errno 13] Permission denied: '/dev/ttyS0' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/tmp/xa-NDjJuf/gps_info.py", line 42, in <module> ser = serial.Serial ("/dev/ttyS0") #Open port with baud rate File "/usr/lib/python3/dist-packages/serial/serialutil.py", line 236, in __init__ self.open() File "/usr/lib/python3/dist-packages/serial/serialposix.py", line 268, in open raise SerialException(msg.errno, "could not open port {}: {}".format(self._port, msg)) serial.serialutil.SerialException: [Errno 13] could not open port /dev/ttyS0: [Errno 13] Permission denied: '/dev/ttyS0' >>> %Run gps_info.py Traceback (most recent call last): File "/usr/lib/python3/dist-packages/serial/serialposix.py", line 265, in open self.fd = os.open(self.portstr, os.O_RDWR | os.O_NOCTTY | os.O_NONBLOCK) PermissionError: [Errno 13] Permission denied: '/dev/ttyS0' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/tmp/xa-NDjJuf/gps_info.py", line 42, in <module> ser = serial.Serial ("/dev/ttyS0") #Open port with baud rate File "/usr/lib/python3/dist-packages/serial/serialutil.py", line 236, in __init__ self.open() File "/usr/lib/python3/dist-packages/serial/serialposix.py", line 268, in open raise SerialException(msg.errno, "could not open port {}: {}".format(self._port, msg)) serial.serialutil.SerialException: [Errno 13] could not open port /dev/ttyS0: [Errno 13] Permission denied: '/dev/ttyS0'
- PR
try running your code via terminal. use sudo. # sudo python3 <your_code_name>.py
- VA
bro when i executed the code there is no output shown on the terminal. i also tried on python idle on pi desktop but it displays error at self.open, "ser=serial.Serisl("/dev/ttsy0")" "coudn't open the port"-.format(self,_port,msg)
- O3
hi i got the output but i want that location name and convert that to speech can you help me with that
- DHdhwanidesai9427· edited
Hey , is the serial 0 ttyS0 in this project or is it to be swapped before using it. Also it shows Restart : / home/pi/gps1.py on python shell and nothing else.
- DH
Replying to @lokeshc
If I keep serial0 as ttyS0 and run the same code then it shows error and if I change the code line /dev/ttyAMA0 it does not show any error but shows restart : /home/...
- AH
I get this error when running the code despite making all the serial configurations as you described. What could be the error please? "Traceback (most recent call last): File "mapplot.py", line 38, in <module> ser = serial.Serial ("/dev/ttyS0") #Open port with baud rate File "/usr/lib/python2.7/dist-packages/serial/serialutil.py", line 236, in __init__ self.open() File "/usr/lib/python2.7/dist-packages/serial/serialposix.py", line 272, in open self._reconfigure_port(force_update=True) File "/usr/lib/python2.7/dist-packages/serial/serialposix.py", line 315, in _reconfigure_port raise SerialException("Could not configure port: {}".format(msg)) serial.serialutil.SerialException: Could not configure port: (5, 'Input/output error')"
- AH
Forgot to mention that I'm using Raspberry Pi 3 Model B and NEO6m GPS module.
- TO
Traceback (most recent call last): File "test_gps.py", line 51, in <module> GPS_Info() #get time, latitude, longitude File "test_gps.py", line 20, in GPS_Info lat = float(nmea_latitude) #convert string into float for calculation ValueError: could not convert string to float: I know this error happen, when GPS module unable to get data, but i want to know how avoid this error, because GPS modul sometime cannot receive data, when device is in Building oder something… GPS Tracking is a part of my Program, this error will make my program stop, too. I have 2 Solution, but don not know how to make it: 1. GPS in other python program, run parallel to my program. And python pragram run automatic again, when this happen. 2. When GPS Module unable to get data, program will get last coordinator data
- VA
GETTING THIS ERROR: NMEA Time: NMEA Latitude: NMEA Longitude: " Traceback (most recent call last): File "/home/pi/gps_info.py", line 55, in <module> GPS_Info() #get time, latitude, longitude File "/home/pi/gps_info.py", line 24, in GPS_Info lat = float(nmea_latitude) ValueError: could not convert string to float: " MY ALL CONNECTION IS PROPER GPS TX CONNECT TO RX OF RASPBERRY PI PIN 10. AND NO NETWORK ISSUE
- VA
Replying to @lokeshc
$GPGSA,A,1,,,,,,,,,,,,,99.99,99.99,99.99*30 $GPGSV,1,1,00*79 $GPGLL,,,,,,V,N*64 $GPRMC,,V,,,,,,,,,,N*53 $GPVTG,,,,,,,,,N*30 $GPGGA,,,,,,0,00,99.99,,,,,,*48 $GPGSA,A,1,,,,,,,,,,,,,99.99,99.99,99.99*30 $GPGSV,1,1,00*79 $GPGLL,,,,,,V,N*64 $GPRMC,,V,,,,,,,,,,N*53 $GPVTG,,,,,,,,,N*30 $GPGGA,,,,,,0,00,99.99,,,,,,*48 $GPGSA,A,1,,,,,,,,,,,,,99.99,99.99,99.99*30 $GPGSV,4,1,15,01,,,26,03,,,26,04,,,27,06,,,25*7A $GPGSV,4,2,15,07,,,24,09,,,25,10,,,26,11,,,26*75 $GPGSV,4,3,15,13,,,26,15,,,26,16,,,26,17,,,24*7F $GPGSV,4,4,15,27,,,27,28,,,24,33,,,28*7B $GPGLL,,,,,,V,N*64 $GPRMC,,V,,,,,,,,,,N*53 $GPVTG,,,,,,,,,N*30 $GPGGA,,,,,,0,00,99.99,,,,,,*48 $GPGSA,A,1,,,,,,,,,,,,,99.99,99.99,99.99*30 $GPGSV,4,1,14,01,,,23,03,,,28,04,,,12,06,,,27*74 $GPGSV,4,2,14,07,,,21,10,,,23,11,,,27,13,,,23*78 $GPGSV,4,3,14,15,,,28,16,,,24,17,,,24,27,,,24*77 $GPGSV,4,4,14,28,,,22,33,,,28*7C $GPGLL,,,,,,V,N*64 $GPRMC,,V,,,,,,,,,,N*53 $GPVTG,,,,,,,,,N*30 getting this
- DA
Replying to @lokeshc
Hello, i'm having this same issue and ive gone outside and i still get the error. Could it be something else?
- VA
getting an error like this Traceback (most recent call last): File "/home/pi/gps7.py", line 42, in <module> ser = serial.Serial ("/dev/ttyS0") #Open port with baud rate File "/usr/lib/python2.7/dist-packages/serial/serialutil.py", line 236, in __init__ self.open() File "/usr/lib/python2.7/dist-packages/serial/serialposix.py", line 272, in open self._reconfigure_port(force_update=True) File "/usr/lib/python2.7/dist-packages/serial/serialposix.py", line 315, in _reconfigure_port raise SerialException("Could not configure port: {}".format(msg)) SerialException: Could not configure port: (5, 'Input/output error')
- LO
Hey Vaibhav first of all, make sure about serial configurations which are required for the raspberry pi. For that, you can refer link given below, http://www.electronicwings.com/raspberry-pi/raspberry-pi-uart-communication-using-python-and-c Also, make sure that packages you have installed are for python 2 only. If it is for python 3 then you should try the above python script on python 3 or install packages for python2. It seems that the above program is built on python 3. So compile code on python 3.
- AH
Replying to @lokeshc
I'm getting the same error despite making the serial configurations, but I dont understand 'It seems that the above program is built on python 3. So compile code on python 3'. What am I supposed to do?
- HE
Hi, thank you for sharing. I works very good. How can I display the data on a webpage? So that I can see the data from another Raspberry Pi or PC Thank you, Henrik
- RA
@Lokeshc: for reading NMEA data from USB dongle connected to Raspberry Pi, will the same code work?
- SJ
in python code , the code doesn't get compile after ''received_data = (str)(ser.readline())'' neither it show any error
- GU
I am getting the following error while in python 2.7. I am using RaPi-3B. Traceback (most recent call last): File "gps.py", line 38, in <module> ser = serial.Serial ("/dev/ttyS0") #Open port with baud rate File "/usr/lib/python2.7/dist-packages/serial/serialutil.py", line 236, in __init__ self.open() File "/usr/lib/python2.7/dist-packages/serial/serialposix.py", line 272, in open self._reconfigure_port(force_update=True) File "/usr/lib/python2.7/dist-packages/serial/serialposix.py", line 315, in _reconfigure_port raise SerialException("Could not configure port: {}".format(msg)) serial.serialutil.SerialException: Could not configure port: (5, 'Input/output error')
- LO
make serial configurations which are required for the raspberry pi. For that you can refer link given below, http://www.electronicwings.com/raspberry-pi/raspberry-pi-uart-communication-using-python-and-c Also, make sure that packages you have installed are for python2 only. If it is for python 3 then you should try the above python script on python3 or install packages for python2. It seems that above program is build on python3
- MR
I have this error when i run the code ('NMEA Time: ', '151322.102', '\n') ('NMEA Latitude:', '', 'NMEA Longitude:', '', '\n') Traceback (most recent call last): File "FinalGPS.py", line 50, in <module> GPS_Info() #get time, latitude, lon gitude File "FinalGPS.py", line 19, in GPS_Info lat = float(nmea_latitude) #convert string into float for c alculation ValueError: could not convert string to float:
- LO
I will recommend first you should go through all the steps to enable serial communication. For this, you can refer following link, http://www.electronicwings.com/raspberry-pi/raspberry-pi-uart-communication-using-python-and-c After performing all these settings and configurations the above code will work for you.
- LO
Replying to @MrTechy
while configurations, did you try any serial communication? If not then have a try. Which version raspberry pi you are using? because a serial port name is different for both raspberry pi. also check your GPS connection with raspberry pi too. Most of the time wrong connection is the problem.
- LO
Hi Sayali, have you made configurations for serial communication? if not then you can have a look into the below link, http://www.electronicwings.com/raspberry-pi/raspberry-pi-uart-communication-using-python-and-c Now, try again. May it will work for you. Also, change the name of serial port (ttyS0 or ttyAMA0) as per your raspberry pi version.
- BA
i need to know how to enable the serial0 port and I am using pi3
- LO
You have to enable serial using raspi-config. Then you should test your serial communication with pc/laptop. So that you will get idea about it is working or not. Sometimes it gives error because of some privilege to access that file. If you get proper output then you can use serial port with hardware.
- BA
Replying to @lokeshc
serial convertor is not available on surroundings are else I need to do alternative method to connect with laptop
- BA
the output remains idle...... I do each and every step except usb to serial convertion !! if serial convertor is compulsory necessary for this program?? I swapped the UART ports but I didn't understand the reason behind that!!
- LO
Replying to @balajirodez
There is no as such requirement to swap uart. In pi, one uart is connected to onboard Bluetooth and one uart is assigned as uart for pin headers(Rx and Tx). The UART (PL011) which is used for onboard Bluetooth has high throughput than uart used for Rx and Tx. So as per your application need you can use any uart.
- LA
Getting an error like this... " Traceback (most recent call last): File "/home/pi/gps_info.py", line 57, in <module> GPS_Info() #get time, latitude, longitude File "/home/pi/gps_info.py", line 26, in GPS_Info lat = float(nmea_latitude) ValueError: could not convert string to float: "
- LO
@Lakshana: This is happening because GPS module unable to get GPS information from Satellite. And so "GPGGA" NMEA string contains no information except time. That's why it is throwing error while parsing in GPS_Info() function. So, put your GPS receiver at a place where you will get a proper network.



