Arduino Projects

Geofencing in Cars using Arduino, GPS, and GSM, Geofence GPS Tracker

Geofencing in Cars using Arduino:

 

Geofencing in Cars using Arduino, GPS, and GSM, Geofence GPS Tracker– In today’s article, you will learn how to define a geographical zone to track if your car is leaving or entering that zone using Geofencing technology. With Geofencing the system uses the GPS signals from the tracking device to pinpoint the location and marks the limits of an area. This ‘area’ is the Geofence.


A Geofence is a virtual fence or an imaginary border drawn around a point by a GPS tracking system. Once a Geofence is created, it can be used as a trigger for alerts and events. For example, your tracker system can tell you whenever one of your vehicles enters or leaves the area. A Geofence can be of any size or shape, it can be a straight line, a rectangle, a square, a circle, or an irregular shape.

Geofencing in cars

A circular type Geofence is very easy to implement, we simply define the center of the circle with the initial Latitude and longitude values, and then we compare these latitude and longitude values with the Latitude and longitude values of the GPS module fixed inside a car. We calculate the distance between any two GPS coordinates using the Haversine Formula.

Geofencing in cars

The calculated distance is then compared with the pre-defined distance value. So, if the calculated distance is greater than the pre-defined distance then it means the Car or any other object has moved outside the Geofence. Now, it depends on you, what activity do you want the Controller board to perform, you want to stop the car? Or do you want to send an Alert message? Or do you want to activate the Buzzer? It totally depends on you, what activity you want to perform when the car leaves the Geofence. In my case, I will use the SMS alert along with Google’s map GPS coordinates. So, this was a brief introduction about, what is a Geofence? And how I am going to implement this technology.

Due to the ongoing construction in my home, for the next few days, I will be parking my car at my friend’s place. This place is about half a kilometer away from my house, this area is quite secured but still, I want my car to be under my observation. I have already designed an anti-theft system for my car which is currently installed, but still, I want an extra level of security.

Anyways, to create a Geofence for my car, I am going to use Arduino Nano, Neo 6M GPS Module, and the SIM900A GSM module. Before I am going to explain the circuit diagram and programming, first let’s watch the Arduino-based Geofence technology in action.



Altium Designer:

altium designer sponsor

Altium Designer is the world’s most trusted PCB design system. Altium Designer enables engineers to effortlessly connect with every facet of the electronics design process. Over 35 years of innovation and development focused on a truly unified design environment makes it the most widely used PCB design solution. With Altium Designer you can create PCB designs with an intuitive and powerful interface that connects you to every aspect of the electronics design process. Route it your way through any angle, tune for the delay, Push, Slide, and Walkaround faster than ever. Interact and collaborate with mechanical designers like never before in a photo-realistic, 3D design environment. If you want to get started with the Altium designer, you can click on the get started.

Geofencing in cars

Here is my prototype model and I am still working on it as I am planning to add more features. So, don’t forget to click on the subscribe button, if you want to see advanced versions of the same project. Anyways, for now, I am going to place it inside the car.

I have already powered up the Arduino and I am not receiving any message as the car is still inside the Geofence.

When the car moved outside the Geofence I received an alert message that the car is outside the fence.

Geofencing in cars

Arduino sends me the first Alert message immediately when the Car leaves the fence, the other messages then I get after every 20 seconds. The time duration can be changed as per the requirement.

You can modify the code if you don’t want multiple messages, but personally, I recommend this multiple messages sending feature because after the car leaves the fence, the Arduino will keep sending the alert messages along with the current latitude and longitude values and along with the Google’s maps URL link which you can use to track the car in real-time.

When the car leaves the fence a buzzer is also turned ON for 5 seconds which signals the Driver that the car has moved outside the Geofence. This buzzer is activated only once while the messages are sent after every 20 seconds.

You can use this project for monitoring prisoners, Covid patients, a parcel, a robot, a drone, etc. by the way this is the same technology used in the Antman movie, and the actor had this tracking device attached to his leg as he was not allowed to leave the house. So, technically he was inside a virtual fence or Geofence. Anyways, now you have got an idea of what exactly you are going to learn after reading this article, so, without any further delay. Let’s get started!!!


Amazon Links:

Arduino Nano

Neo 6M GPS

GSM SIM900A

Other Tools and Components:

Top Arduino Sensors:

Super Starter kit for Beginners

Digital Oscilloscopes

Variable Supply

Digital Multimeter

Soldering iron kits

PCB small portable drill machines

*Please Note: These are affiliate links. I may make a commission if you buy the components through these links. I would appreciate your support in this way!


GSM module SIM900A:

This module is powered by: 5V-26V, 5V 2A power supply is recommended. After plugging in the motherboard, the power supply must be able to supply 2A. The reason is that the GPRS Shield startup current and the maximum top current are required to work up to 2A, but the USB port cannot provide such a large current, so the external power supply equipment must be provided.

Geofencing in cars

Interface Introduction:

  • Power select – select the power supply for GPRS shield.
  • Power jack – connected to external 4.8~5VDC power supply.
  • Antenna interface – connected to external antenna.
  • Serial port select – select either software serial port or hareware serial port to be connected to GPRS Shield.
  • Hardware Serial – D0/D1.
  • Software serial – D7/D8.
  • Status LED – tell whether the power of SIM900 is on.
  • Net light – tell the status about SIM900 linking to the net.
  • UART of SIM900 – UART pins break of SIM900.
  • Microphone – to answer the phone call.
  • Speaker – to answer the phone call.
  • GPIO,PWM and ADC of SIM900 – GPIO, PWM, and ADC pins break of SIM900.
  • Power key – power up and down for SIM900.


Neo 6M GPS Module:

GPS or Global Positioning System is a satellite navigation system that furnishes location and time information in all climate conditions to the user. GPS is used for navigation in planes, ships, cars, and so on. GPS provides continuous real-time, 3-dimensional positioning, navigation, and timing worldwide. The GPS is used to find the Longitude and Latitude values.

Geofencing in cars

Features:

  • Power supply: 3V-5V
  • Models: GY – GPS6MV2
  • Module with ceramic antenna, signal strong
  • EEPROM save the configuration parameter data when power down
  • With data backup battery
  • The LED signal lights
  • The default baud rate: 9600
  • Compatible with various flight control modules
  • Module size 25 x 35 mm  (0.98” x 1.37”)
  • Antenna size: 25 x 25 mm  (0.98”x 0.98”)



 Creating a Geofence for the Car:

  1. Open the Google Maps…
  2. Click on the area which you want to set as the initial position…
  3. Click on the GPS coordinates…
  4. Copy the Latitude and Longitude values, later you will need these values for defining the initial position in the programming.

If still, you don’t know how to find the GPS coordinates, then watch my video given at the end of this article.

Geofencing in cars

The distance of the Gate from the center of the room is 23 meters. I park my car about 10 meters away from the center of the room. The distance from the car to the gate is 13 meters. So, I am going to set the maximum distance at around 20 meters, this way I will get the alert message before the car crosses the gate. So, this is going to be my car’s Geofence.

So, I have my initial latitude and longitude values, and also the maximum distance value. Now, let’s take a look at the circuit diagram, and then I will explain the programming.


Circuit Diagram:

Geofencing in cars

All the electronics are powered up using the 5Volts regulated power supply, make sure the power supply is around 2A.

The RXD and TXD pins of the GSM Sim900A module are connected with the Arduino’s pins D3 and D2.

The RXD and TXD pins of the Neo 6M GPS Module are connected with the Arduino’s pins D9 and D8 respectively.

Before, you start the programming, first of all, make sure you download the AltSoftSerial and TinyGPS++ libraries. Click on the sketch Menu > Include Library > Manage Libraries…

First search for the AltSoftSerial library and install it.

Geofencing in cars

Then search for the TinyGPS++ library and install it.

Geofencing in cars


Arduino Geofencing Programming:

#include <SoftwareSerial.h>
#include <AltSoftSerial.h>
#include <TinyGPS++.h>

//--------------------------------------------------------------
//enter your personal phone number to receive sms alerts.
//phone number must start with country code.
const String PHONE = "+923335376419";
//--------------------------------------------------------------
//GSM Module RX pin to Arduino 3
//GSM Module TX pin to Arduino 2
#define rxPin 2
#define txPin 3
SoftwareSerial SIM900(rxPin,txPin);
//--------------------------------------------------------------
//GPS Module RX pin to Arduino 9
//GPS Module TX pin to Arduino 8
AltSoftSerial neogps;
TinyGPSPlus gps;
//--------------------------------------------------------------
#define BUZZER 4

// Alarm
int buzzer_timer = 0;
bool alarm = false;
boolean send_alert_once = true;

//----------------------------------
// keep track of time, after how much time the messages are sent

// Tracks the time since last event fired
boolean multiple_sms = false;
unsigned long previousMillis=0;
unsigned long int previoussecs = 0; 
unsigned long int currentsecs = 0; 
 unsigned long currentMillis = 0; 
 int secs = 0; 
 int pmints = 0; 
 int mints = 0; // current mints
 int interval= 1 ; // updated every 1 second

 
//--------------------------------------------------------------
// Size of the geo fence (in meters)
const float maxDistance = 20;

//--------------------------------------------------------------
float initialLatitude = 33.094691;
float initialLongitude = 71.166038;

float latitude, longitude;

//--------------------------------------------------------------


void getGps(float& latitude, float& longitude);


/*****************************************************************************************
 * setup() function
 *****************************************************************************************/
void setup()
{
  //--------------------------------------------------------------
  //Serial.println("Arduino serial initialize");
  Serial.begin(9600);
  //--------------------------------------------------------------
  //Serial.println("SIM800L serial initialize");
  SIM900.begin(9600);
  //--------------------------------------------------------------
  //Serial.println("NEO6M serial initialize");
  neogps.begin(9600);
  //--------------------------------------------------------------
  pinMode(BUZZER, OUTPUT);
  //--------------------------------------------------------------
  SIM900.println("AT"); //Check GSM Module
  delay(1000);
  SIM900.println("ATE1"); //Echo ON
  delay(1000);
  SIM900.println("AT+CPIN?"); //Check SIM ready
  delay(1000);
  SIM900.println("AT+CMGF=1"); //SMS text mode
  delay(1000);
  SIM900.println("AT+CNMI=1,1,0,0,0"); /// Decides how newly arrived SMS should be handled
  delay(1000);
  //AT +CNMI = 2,1,0,0,0 - AT +CNMI = 2,2,0,0,0 (both are same)
  //--------------------------------------------------------------
  delay(20000);
  buzzer_timer = millis();
}





/*****************************************************************************************
 * loop() function
 *****************************************************************************************/
void loop()
{
  //--------------------------------------------------------------
  getGps(latitude, longitude);
  //--------------------------------------------------------------
  float distance = getDistance(latitude, longitude, initialLatitude, initialLongitude);
  //--------------------------------------------------------------
  Serial.print("Latitude= "); Serial.println(latitude, 6);
  Serial.print("Lngitude= "); Serial.println(longitude, 6);
  Serial.print("initialLatitude= "); Serial.println(initialLatitude, 6);
  Serial.print("initialLngitude= "); Serial.println(initialLongitude, 6);
  Serial.print("current Distance= "); Serial.println(distance);
  //--------------------------------------------------------------
  // Set alarm on?
  if(distance > maxDistance) {
    multiple_sms = true;
    //------------------------------------------
    if(send_alert_once == true){
      digitalWrite(BUZZER, HIGH);
      sendAlert();
      alarm = true;
      send_alert_once = false;
      buzzer_timer = millis();
      
    }
    //------------------------------------------
  }
  else{
    send_alert_once = true;
    multiple_sms = false;
  }
  //--------------------------------------------------------------

  // Handle alarm
  if (alarm == true) {
    if (millis() - buzzer_timer > 5000) {
      digitalWrite(BUZZER, LOW);
      alarm = false;
      buzzer_timer = 0;
      
    }
  }

  if ( multiple_sms = true)
  {
       currentMillis = millis();
       currentsecs = currentMillis / 1000; 
       if ((unsigned long)(currentsecs - previoussecs) >= interval) {
       secs = secs + 1; 

       if ( secs >= 20)
       {
        sendAlert();
        multiple_sms = false;
        secs = 0;
       }
    }
  }
  //--------------------------------------------------------------  
  while(SIM900.available()){
    Serial.println(SIM900.readString());
  }
  //--------------------------------------------------------------
  while(Serial.available())  {
    SIM900.println(Serial.readString());
  }
  //--------------------------------------------------------------


}



/*****************************************************************************************
* getDistance() function
*****************************************************************************************/

// Calculate distance between two points
float getDistance(float flat1, float flon1, float flat2, float flon2) {

  // Variables
  float dist_calc=0;
  float dist_calc2=0;
  float diflat=0;
  float diflon=0;

  // Calculations
  diflat  = radians(flat2-flat1);
  flat1 = radians(flat1);
  flat2 = radians(flat2);
  diflon = radians((flon2)-(flon1));

  dist_calc = (sin(diflat/2.0)*sin(diflat/2.0));
  dist_calc2 = cos(flat1);
  dist_calc2*=cos(flat2);
  dist_calc2*=sin(diflon/2.0);
  dist_calc2*=sin(diflon/2.0);
  dist_calc +=dist_calc2;

  dist_calc=(2*atan2(sqrt(dist_calc),sqrt(1.0-dist_calc)));
  
  dist_calc*=6371000.0; //Converting to meters

  return dist_calc;
}


/*****************************************************************************************
 * getGps() Function
*****************************************************************************************/
void getGps(float& latitude, float& longitude)
{
  // Can take up to 60 seconds
  boolean newData = false;
  for (unsigned long start = millis(); millis() - start < 2000;){
    while (neogps.available()){
      if (gps.encode(neogps.read())){
        newData = true;
        break;
      }
    }
  }
  
  if (newData) //If newData is true
  {
    latitude = gps.location.lat();
    longitude = gps.location.lng();
    newData = false;
  }
  else {
    Serial.println("No GPS data is available");
    latitude = 0;
    longitude = 0;
  }
}




/*****************************************************************************************
* sendAlert() function
*****************************************************************************************/
void sendAlert()
{
  //return;
  String sms_data;
  sms_data = "Alert! The Car is outside the fence.\r";
  sms_data += "http://maps.google.com/maps?q=loc:";
  sms_data += String(latitude) + "," + String(longitude);

  //return;
  SIM900.print("AT+CMGF=1\r");
  delay(1000);
  SIM900.print("AT+CMGS=\""+PHONE+"\"\r");
  delay(1000);
  SIM900.print(sms_data);
  delay(100);
  SIM900.write(0x1A); //ascii code for ctrl-26 //sim800.println((char)26); //ascii code for ctrl-26
  delay(1000);
  Serial.println("SMS Sent Successfully.");
  
}


Geofencing Code Explanation:

Inside the loop() function, we call the getGps() function, the purpose of this function is to find the current latitude and longitude values.

Next, we find the distance using the getDistance() function. The distance is calculated using the current GPS location and the initial GPS location. GetDistance() function is a user-defined function and is based on the Haversine formula which is used to calculate the distance between any two GPS locations using current GPS and initial GPS coordinates. Once the distance is calculated, then the measured distance is compared with the maximum distance which is the fence size. So, if the calculated distance is greater than the maximum distance then the buzzer is turned ON, and also an alert message is sent on the pre-defined phone number along with the GPS coordinates. So, the first message is sent immediately when the car leaves the fence and the buzzer is turned ON only for 5 seconds. The buzzer is only turned ON once.

I also added code for sending multiple messages, right now the alert message is sent after every 20 seconds. You can increase or decrease the number of seconds as per your requirement. So, that’s all about the code.



Watch Video Tutorial:

 

Engr Fahad

My name is Shahzada Fahad and I am an Electrical Engineer. I have been doing Job in UAE as a site engineer in an Electrical Construction Company. Currently, I am running my own YouTube channel "Electronic Clinic", and managing this Website. My Hobbies are * Watching Movies * Music * Martial Arts * Photography * Travelling * Make Sketches and so on...

One Comment

  1. Super cool project, thank you! I’m going to try it. Just one question: what battery/power bank are you using? If I understood correctly, the GSM module SIM900A needs to be powered independently?

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button