---
# System prepended metadata

title: GPS Bike tracker and theft alarm
tags: [Internet of Things, GPS, alarm, Tracker, IoT]

---

*The project has been done by me, Igor Sokolovic (is223dy).*
# Project Overview

The project aims to make a functioning Internet of Things device which trackes the location of the bike using GPS and sends that data using GSM (SIM card) to the cloud where it is being procesed and visualised. This project uses Ai-Thinkers A9G gps and gsm module.

Starting from scrach, the project could be done in 7 days with a few hours dedicated to do the project, following this tutorial, 3-4 hours.

# Objective

I study in Lund, Sweden and everyone uses bikes to go around town and to the university. My friend, Till, had his bike stolen right before the summer. He was devistated since he had that bike for years. So I wanted to make a way to track the bike even when it gets stolen to hopefully retreave it and not have to by a new bike and more locks. 
The purpose for this project is to make a functional tracker which can be implemented easily and simple to use and deploy. The tracker needs to not be obvious and should we robust and weather proof since it will live on the bike. 
This will give insight into how to design a compact and natural looking end product which will incoporate itself and look OEM.

# Materials




| Sensors | Names | Price |
| -------- | -------- | -------- |
| ![a9g](https://hackmd.io/_uploads/BJKzS7RO2.jpg =200x150)|[Ai-Thinker A9g](https://de.aliexpress.com/item/32973328848.html?spm=a2g0o.productlist.main.21.76f67ee3MRNgrk&algo_pvid=2af40276-7ced-4f04-a01a-5d6f8a1ae119&algo_exp_id=2af40276-7ced-4f04-a01a-5d6f8a1ae119-10&pdp_npi=3%40dis%21SEK%2188.06%2165.21%21%21%21%21%21%40210213c816882498077715308d076c%2166648287105%21sea%21SE%21847570160&curPageLogUid=G0b01raXUXFB)|Around 10€|
| ![antena](https://hackmd.io/_uploads/HyCH8QCd3.jpg =200x150)|GPS antenna|inc. with A9G|
| ![](https://hackmd.io/_uploads/BJEBP7Cd2.jpg =200x150) |GSM antenna|inc. with A9G|
|![ttl](https://hackmd.io/_uploads/rJuxdmC_3.jpg =200x150)|[USB to TTL converter](https://de.aliexpress.com/item/1005001621913221.html?spm=a2g0o.productlist.main.3.516e6386tXvZ7S&algo_pvid=61fbae5d-077e-4e13-a958-5e9bc4549788&aem_p4p_detail=202307011526229570835893783840009049865&algo_exp_id=61fbae5d-077e-4e13-a958-5e9bc4549788-1&pdp_npi=3%40dis%21SEK%2117.39%2117.39%21%21%21%21%21%40211be54b16882503825531728d07ff%2112000023970881792%21sea%21SE%21847570160&curPageLogUid=CTt1GSe6pGBk&search_p4p_id=202307011526229570835893783840009049865_2)|Around 2€|

The Ai-Thinker A9G board found above uses AT commands, which are custome built in comands with which the user can control the board and all its functions. It can be used with another microcontroler like the Raspberry pi Pico. In this project the board is flashed with a custom micropython build found [here](https://github.com/Ai-Thinker-Open/GPRS_C_SDK). The micro USB on the A9g cannot be used for flashing, which is where the USB to TTL converter found above comes in. It converts the USB protocol to serial protocol (TX and RX) WHich can be connected to the A9G.

Other hardware used in both prototiping and the final product.

| Hardware | Name | Price |
| -------- | -------- | -------- |
| ![bb](https://hackmd.io/_uploads/H1sa_XRu3.jpg =200x150)|[Breadboard](https://www.electrokit.com/en/product/solderless-breadboard-840-tie-points-2/)|Around 5€|
|![jw](https://hackmd.io/_uploads/S1AL4fkKn.jpg =200x150)|[Jumper wires](https://www.electrokit.com/en/product/jumper-wires-1-pin-male-male-150mm-10-pack/)|Around 2€|
|![pb](https://hackmd.io/_uploads/r1UCVM1K3.jpg =200x150)|Powerbank (any kind)|Around 10€|

# Computer Setup
Like mentioned above, the A9G board needs to have micropython flasehed on it. This has been done following this [tutorial](https://www.youtube.com/watch?v=8WAPMPTS3TQ&t). But here are steps that need to be followed:
* Dowload and install [Git](https://gitforwindows.org/) on your computer
* Open the terminal and install the following repository to the git folder
```
git clone https://github.com/Ai-Thinker-Open/GPRS_C_SDK.git --recursive
```
* Then dowload this [SDK](https://github.com/ZakKemble/GPRS_C_SDK/releases/download/v2.129/CSDTK42_Update2_18_7_27.7z) and extract it
* Run the **config_env_admin.bat**
* Go to the  directory **C:\Users\YOUR_USERNAME\GPRS_C_SDK**, press and hold the SHIFT button and right click on the balnk space and **Open Powershell Window here**.
* Type `./build.bat app` and press enter
* Now go to **CSDTK42_Update2_18_7_27\CSDTK42\cooltools** and find **coolwatcher** and run as administrator.
* In the profiles select 8955 and click ok and give all the permissions it asks for.
* If done succesfully, it will open **coolhost** where you will have to select a **COM PORT** where the board is connected to and hit **connect**.
* Exit coolhost and  coolwatch select the **Flash** tab and then **Chose Flash Programer...**
* Go to **CSDTK42_Update2_18_7_27\CSDTK42\cooltools\chipgen\Modem2G\toolpool\plugins\fastpf\flash_programmers** and select **host_8955_flsh_spi32m_ramrun.lod** file and press enter.
* Click the **LOD FLSH** button and download this [file](https://github.com/pulkin/micropython/releases/download/latest-build/firmware_debug_full.lod) and select the one named  **micropython firmware_debug_full** then click the flash icon.
* Now select the one called **micropython firmware_debug_flash** and click flash again
* Congradulations, you now have micropython installed!

Now that micropython is installed, we will be using [Thonny](https://thonny.org/) which is a python IDE made for beginers. To actually write code on the board, we need to click on the **Run** tab in Thonny and select **Configure interpreter...** Here we need to select Micropython (generic), then our board should appear. Now by writting a code names main.py and saving it on the board, the board will execute any command!

# Putting everything together

First step in putting everything together is figuring out where to actually put it. The location that I chose was under the seat of my bike. Now, we can wire up the components following this simple diagram.
![](https://hackmd.io/_uploads/rkGl5xbY2.jpg)

Now comes the hard part, modeling an enclosure and 3d printing it. Like mentioned, I chose the underneath of my seat, which is very complicated to model. Here is the final model of the shield and also the powerbank holder.


|![](https://hackmd.io/_uploads/SylZilbK3.jpg =300x200)| ![](https://hackmd.io/_uploads/Skw4jlWFh.jpg =300x200)|
| -------- | -------- |
|Component shield|Powerbank holder|

And here is the finished product:
<iframe width="560" height="315" src="https://www.youtube.com/embed/1DscFT3BtmM" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" allowfullscreen></iframe>




# Platform
For actually visualising the GPS postion and having the lock feature we need to have a platform where all of this needs to be done. The first platform which was a success was [Adafruit](https://io.adafruit.com/), which is a cloud based platform which does not require any code (appart from connecting your device to the server). It has a free option which is pleanty enough for this project. This platform was ultimetly chosen for its simplisity and also since it had an option for a button driven events.

Another more complex way is by using whats known as a TIG stack. This was named by its components, Telegraf which transferes data from the device to the broaker; InfluxDB which is a database where all the data is stored and Grafana which is a visualisation tool. This was also tested but this method failed for this project. The biggest problem was that the project needs human imput (locking and unlocking the bike) which cannot be done with Telegraf. So Node RED was needed, but nowhere online was there any tutorials for this setup, so nothing was working. But this setup can defenetly work, but it is quite complex as a begginer.

Another platform which was tried was making a Telegram bot and using that for human interaction instead of using Adafruit. The bot was made and it did work while the computer was on (*Fig. 1*), but when I tried putting the bot on a cloud using [Heroku servers](https://www.heroku.com/) and following this [instructions](https://github.com/EdenShivam/IOT-PROJECTS), the bot did not function anymore. So I went back to Adafruit and is the final choice for this project.

![](https://hackmd.io/_uploads/S1LXGAgYn.jpg =320x400)
*Fig. 1: Screenshot of the telegram bot and the functions it has*

# The Code
Since the project does not use any additional sensors (this is because of A9G not being able to connect to other sensors properly), we need to implemet a clever way for detecting movement with the GPS only. This has been done with the code below:
```
def cb(led_topic, msg):  # Callback function
    print('Received Data:  Topic = {}, Msg = {}'.format(Lock_status, msg))
    recieved_data = str(msg,'utf-8') #   Recieving Data
    if recieved_data=="LOCK": #If the bike is locked
        gps.on() #GPS turns on
        locked_coordinates = gps.get_location() #Saves current location
        while locked_coordinates != gps.get_location():
            gps_track()
            time.sleep(10) #Checks if the location changed every 10sec
    else:
        gps.off() #If unlocked, gps turns off
```
To acomplish the lock feature, we use the Adafruit button and assign it to a variable in the code. If the variable is "LOCK" it will arm the gps, record the position where it is and then compare it with new positions every 10 secends. If the coordinates change, it will call the `gps_track()` function. If the variable is "UNLOCK", it will turn off its gps and wait furter instructions.

For more capabilities, this repository can be used [https://github.com/pulkin/micropython/tree/master/ports/gprs_a9/examples](https://github.com/pulkin/micropython/tree/master/ports/gprs_a9/examples).

# Transmitting the data / connectivity
Since the A9G board has a SIM card and GSM, we can use LTE to send data to the user. The packages `cellular` and `gps` are found in on the board itself. The following code connects to the LTE and also appoints two variables to the adafruit feed.
```
import cellular
import machine
import time
import gps

cellular.gprs("tele2.se", "", "") # ("apn_name","username","password")

Lock_status = "USERNAME/feeds/Lockstatus"
gps_loc = "USERNAME/feeds/Location/csv"
```
The Apn of your SIM cards provider can be found online. CAUTION: The board only works on 2G conectivity, so make sure that your SIM card has a function "2G only". Otherwise it won't work.

It uses the MQTT protocol for sending data over LTE to the Adafruit servers. The following code establishes a conection with the server:
```
# Adafruit informations found in the dashboard
name = "a9g-micropython-board"
server = "io.adafruit.com"
port = 1883
username = "USERNAME"
password = "KEY"


client = simple.MQTTClient(name, server, port, username, password )
client.connect() #Connecting to the server
```

When the GPS is armed, it sends the location every 5 seconds. The format of the data send needs to be altered in the following way:
```
def gps_track():
    acc = '0.0, ' #Adding 0 acceleration
    long,lat = gps.get_location() #splitting lat and long
    msg = acc + str(long) + ', ' + str(lat) + ', 0.0' 
    print('Sending Data:  sattelites = {}, Msg = {}'.format(gps_loc, msg))
    client.publish(gps_loc, msg) #Sending the final version
```

The Adafruit location feed only accepts and displays location is displayed in the form of (acceleration,longatude,latitude,elevation). Since this sensor does not record acceleration and elevation, we have to add zeros instead. This then outputs the location.

# Presenting the data

Like mentioned above, after testing out different methods, Adafruit was chosen to be used as the final platform. When the bike is locked and the original position is not the same as the newly recorded one,the sensor is armed and sends location every 5 secods to Adafruit. The data is transformed into points on the map in the dashboard.

![](https://hackmd.io/_uploads/rJ11ClWK2.jpg)

When the button is flipped to red (UNLOCK), the bike is then unlocked and will disable GPS and not send any data.

# Finalizing the design
In the end, the project did work, for a short time and then the LTE antenna broke. It worked for a while after that, enough for me to get one screenshot which is the one above before it peacefully passed to the other world.

The original idea for the project involved an accelorometer which was meant to recrd acceleration and then that would activate the sensor. This was easily solved with just the GPS module. But another more advanced version involved the Raspberry Pi Pico W, which was meant to create a smart lock. This smart lock was supposed to send data to the A9G when the lock was cut. But since the A9G doesn't support other sensors, this was not possible.

In the end, I had to settle with the simplest versions, which was also doomed the moment the antenna broke. 

# Future improvements
One of the improvements would be to by the Gps and Gsm module to be seperate and connect them to the Raspberry Pi Pico. This would ensure that other sensors can be connected and work together.

Another improvement would be to shrink the project and possibly hide it in a less conspicuous place. 
