Building a Python-Powered GPS Tracking Device for Bikes

A few months ago, a bike of my friend got stolen on the streets. He had parked his bike to grab a quick snack from the roadside food truck but didn’t lock it, thinking who would steal it. To his misfortune, his bike did get stolen in those couple of minutes. However, this unfortunate incident fueled my determination to create a solution. While there exist amazing GPS trackers for bikes on the market, the idea of building one from scratch presented itself as an enticing Python challenge. In this blog, we will go through the idea of building a GPS tracking device for bikes and how to get notified in case your bike gets stolen.

Hardware used for the project

Whenever you want to build a system using Python programming, one device that I would recommend is Raspberry Pi. Single-board computers like Raspberry Pi are amazing tools for people who want to learn programming and like to build stuff. Programming on Raspberry Pi allows you to watch your program come to life. There are many compatible sensors that you can use along to create some great innovations and systems. And that is exactly what we are going to do in this tutorial.

There are different models of Raspberry Pi available in the market, the latest being Raspberry Pi 5. But you do not need to get the latest one; Raspberry Pi 3 or 4 would also work just fine.

GPS Tracking Device for Bikes

Click here to get one for yourself from Amazon.

Another piece of hardware that we require for this project is a GPS module. GPS module transmits and receives signals to satellites while ultimately giving us our coordinates. There are different types of GPS sensors available in the market depending on the required accuracy. Because this is just a fun, project and the accuracy required is moderate, a simple-mouse GPS module would work just fine:

GPS Tracking Device for Bikes

Click here to buy GPS sensor module from Amazon.

Python code to get GPS coordinates

Now that we have our hardware, let us write code to get our GPS coordinates. Below is the code to collect GPS data. To understand what the code means, have a look at this guide to collect GPS data in Raspberry Pi. I have provided full break down of the code in that blog.

import time
import time, serial


def get_coordinates():
  gps = serial.Serial("/dev/ttyACM0", baudrate=9600)
  line = gps.readline()
  decoded_line = line.decode('utf-8')
  data = decoded_line.split(",")
  try:
    if data[0] == "$GPRMC":
      lat_nmea = str(data[3])
      dd = float(lat_nmea[:2])
      mmm = float(lat_nmea[2:])/60
      latitude = dd + mmm

      long_nmea = str(data[5])
      dd = float(long_nmea[:3])
      mmm = float(long_nmea[3:])/60
      longitude = dd + mmm
      return [longitude, latitude]
    else:
      return 0,0

  except TypeError:
    get_coordinates()

while True:
  get_coordinates()

Save this file as gps_coordinates.py. Now that we have our coordinates, we would want to notify ourselves of our bike coordinates. Hence, we will write a Python code to send us an email that contains the bike coordinates.

Python code to send Email

We will use GMail to send email notifications. For this, we need to use Gmail’s SMTP server and port. Additionally, we might need to enable “Less secure app access” in our Google account settings or use an App Password if two-factor authentication is enabled.

Here’s the Python code to send email using GMail. Save this file in your project folder as email_notification.py.

import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart

def send_email(subject, body, to_email, smtp_server="smtp.gmail.com", smtp_port=587, smtp_username, smtp_password):
    # Create the email message
    message = MIMEMultipart()
    message['From'] = smtp_username
    message['To'] = to_email
    message['Subject'] = subject

    # Attach the body of the email
    message.attach(MIMEText(body, 'plain'))

    # Connect to the SMTP server
    with smtplib.SMTP(smtp_server, smtp_port) as server:
        # Login to the SMTP server
        server.starttls()  # Use TLS for security
        server.login(smtp_username, smtp_password)

        # Send the email
        server.sendmail(smtp_username, to_email, message.as_string())

Consider subscribing to my *FREE* newsletter get notified upon a new blog!

Putting it all together

Now that we have functions to get GPS coordinates and sending email, we will write our main.py Python script where we will first read the coordinates from our GPS sensor and send the data via email. We do not want to overload Raspberry Pi by contiuously sending emails every second. Hence, we will introduce the time library and let the script send an email notification every 5 minutes (i.e. 3600 seconds).

from gps_coordinates import get_coordinates
from email_notification import send_email
import time

subject = "GPS data of my bike"
to_email = "my_email@gmail.com"
smtp_username = "username"
smtp_password = "password"

while True:
  [longitude, latitude] = get_coordinates()
  body = str(longitude) + " " + str(longitude)
  send_email(subject, body, to_email, smtp_server="smtp.gmail.com", smtp_port=587, smtp_username, smtp_password)
  time.sleep(3600)

That’s it! Now you have a GPS tracking device for your bike. The main part of writing the program is done. You may now connect the Raspberry Pi to any power bank and mount the entire system, along with the GPS sensor module on your bike. Start the program and you will receive email notifications every hour.

Future Work

The project seems like a good anti-theft system for bikes, however, it is not foolproof. Remember that this will only work if Raspberry Pi has a power supply. What if someone just disconnects the Pi from the power source? You want to get notified immediately in such a case. Thus, this project can be extended to make the system more secure.

One idea would be to mount an MPU 6050 module on the bike and connect it to the Pi. The MPU 6050 is a 6-DOF (Degrees of Freedom) motion-tracking device that combines a 3-axis gyroscope and a 3-axis accelerometer into a single compact module. If someone tries to tamper with the system, it will create some movement in the bike. Use this code to read the acceleration values using MPU 6050 and create a Python script where if the acceleration crosses the threshold value, it will send an email notification with the current coordinates.

Another idea would be to integrate an IR motion sensor to detect human intervention. If someone tries to disconnect the power supply from the Pi, the hand movements near the system will trigger the sensor. Once triggered, the program would immediately send a notification email with the last known coordinates before the power supply is cut off.

Conclusion

In this blog, I talked about how an unfortunate event was used as a motivation for a Python exercise. It’s always an extraordinary feeling when you write a program for something that can be used in our daily lives. I encourage you to go ahead and bring your variations to this project. Moreover, if you have worked on any such project that is not only a good Python exercise but also has a practical application, I would love to hear about that. Feel free to get in touch with me on my Instagram: @machinelearningsite.

If you enjoyed this blog, come join me on my social media where I post tips and tricks on programming and machine learning:

You wouldn’t want to miss any of such interesting posts, would you? Then join my newsletter where you will get a *monthly* update of the posts that you might have missed:

This Post Has 2 Comments

Leave a Reply