Overview
This project demonstrates how to build a real-time elephant tracking system using the Particle B Series SoM. The system enables live GPS tracking of elephants and implements geofencing to notify forest rangers if the animal leaves a predefined boundary. Data is displayed on a web interface with OpenStreetMap integration and stored in Firebase for analysis.
Motivation
The tragic loss of a 40-year-old man in our locality due to a wild elephant attack has deeply shaken our community. This heartbreaking incident is not isolated; it reflects a growing global crisis of human-elephant conflicts that threaten both human lives and the survival of these majestic animals. Such conflicts are becoming increasingly frequent, highlighting the urgent need for innovative solutions to mitigate these encounters and foster coexistence.
In many regions around the world, human-elephant conflicts have reached alarming levels, often resulting in devastating consequences such as crop destruction, property damage, and the loss of both human and animal lives. For instance:
- In Sri Lanka, approximately 70 humans and 300 elephants die annually due to conflicts.
- In Kenya, elephants frequently stray into villages in search of food, leading to property damage and fatalities.
- In Thailand, rapid urbanization and habitat loss have intensified human-elephant conflicts, endangering both communities and wildlife.
These incidents underscore the critical need for sustainable and humane solutions to address human-elephant conflicts. This project aims to contribute to such efforts by developing an elephant tracking and geofencing system powered by advanced IoT technology
Key Features
- Live Tracking: Continuously fetch GPS data from the B Series SoM.
- Geofencing: Define a circular boundary (latitude, longitude, and radius). Notify if the elephant exits this boundary.
- Sustainable Power: Powered by solar panels for extended field operation.
Setting Up the Particle B Series SoM
The B-SoM module serves as the heart of this project, tailored for cellular IoT applications. It is Particle's flagship IoT module, designed to work seamlessly with the Particle IoT Platform-as-a-Service, which offers free usage for up to 100 devices. Additionally, it includes a global embedded SIM card and data plan, ensuring reliable cellular connectivity worldwide.
We specifically chose the B524 SoM for this project due to its robust cellular connectivity, as Wi-Fi is not a feasible option in remote wildlife areas. The cellular capability ensures uninterrupted communication, even in challenging outdoor environments where other connectivity options are unavailable.
To fully harness the capabilities of the B524 SoM, the M.2 Evaluation Board is an essential tool. This breakout board simplifies development and streamlines prototyping, enabling seamless access to the full potential of the module. The board includes USB ports for both the nRF52840 MCU and the cellular modem, an SD card connector, an Ethernet connector, a barrel jack power connector, buttons, an RGB LED, a charge status LED, and a connector for a LiPo battery (battery not included).
Here is how we connect the B524 SoM to the Eval Board.
- Attach the cellular antenna to the U.FL connector labeled CELL on the SoM. This step is crucial for enabling reliable cellular connectivity.
- Align the B524 SoM with the M.2 NGFF connector on the Eval Board.
- Carefully insert the module into the connector, ensuring it is properly seated.
- Secure the module using the screws provided in the eval board kit to prevent movement or disconnection.
To utilize the full capabilities of the B524 SoM with the Particle platform, you’ll need to set up your Particle.io account and configure your device. Follow the steps below:
1. Access the Particle Setup Website:
- Open your browser and go to setup.particle.io.
2. Log Into Your Particle Account:
- If you already have an account, enter your credentials and log in.
- If you don’t have an account, create one by following the signup process.
3. Select Your Device:
- On the setup page, choose the appropriate option for your device by connecting the Eval board to the computer.
- Then it automatically updates the device with the latest device OS and firmware.
4. Organize your Particle device
- Select your organization and the product and also name the device.
5. Complete the Setup:
- Once the setup process is complete, your device will appear as registered in your Particle account.
- You’ll see confirmation messages indicating the device is ready for development.
Particle Workbench
Particle Workbench is an advanced development environment that integrates with Visual Studio Code, making it easy to write, compile, and debug firmware for the B524 SoM. Here’s how you can set it up:
1. Install Visual Studio Code
- Download and install Visual Studio Code from the official website.
2. Install Particle Workbench Extension
- Open Visual Studio Code.
- Go to the Extensions Marketplace by clicking the Extensions icon on the left sidebar.
- Search for Particle Workbench and install the extension.
3. Set Up Your Project
- Open Visual Studio Code.
- Press Ctrl+Shift+P (or Cmd+Shift+P on macOS) to open the Command Palette.
- Type Particle: Create New Project and select it.
- Follow the prompts to choose a project directory, select the B524 SoM, and set the target firmware version.
Preparing the GPS Module
For this project, we used the RYS352A GPS module for precise location tracking. The specifications of the module are below.
The RYS352A module features a 3.3V UART connection, allowing seamless communication with microcontrollers. It supports multiple GNSS systems, including GPS, GLONASS, Galileo, BeiDou, QZSS, and SBAS, providing high-accuracy location data. The module integrates 12 multi-tone active interference cancellers to effectively minimize signal noise.
Additionally, it includes enhanced components such as a SAW filter, LNA (Low-Noise Amplifier), and TCXO (Temperature-Compensated Crystal Oscillator) for superior signal processing. The embedded GPS/GLONASS/BeiDou antenna ensures consistent satellite signal reception. With an RTC (Real-Time Clock) battery backup, the module can maintain time even when powered off. It also delivers a maximum navigation update rate of 10Hz, making it suitable for high-speed tracking applications.
Connect the Reyax GPS module to the Particle B Series SoM:
- TX from GPS to RX on the SoM.
- RX from GPS to TX on the SoM.
- 3.3V from GPS to 3.3V on SoM
- GND from GPS to GND on SoM
TinyGPS++ library is used to parse the NMEA sentences coming from the module.
Here is the sample code for fetching your latitude and longitude.
// Include required libraries #include "Particle.h" #include <TinyGPSPlus.h> // System configuration SYSTEM_MODE(AUTOMATIC); SYSTEM_THREAD(ENABLED); // Global variables TinyGPSPlus gps; // Function to print only latitude and longitude void printLatLng() { if (gps.location.isValid()) { // Print latitude and longitude to Serial Serial.print("Latitude: "); Serial.print(gps.location.lat(), 6); Serial.print(", Longitude: "); Serial.println(gps.location.lng(), 6); // Optionally publish to cloud String locationMsg = String::format( "%.6f,%.6f", gps.location.lat(), gps.location.lng() ); Particle.publish("location", locationMsg); } } void setup() { // Initialize GPS on Serial1 Serial1.begin(115200); // Initialize USB serial for output Serial.begin(); // Notify device is ready Particle.publish("status", "Device online and ready"); } void loop() { // Read GPS data while (Serial1.available() > 0) { if (gps.encode(Serial1.read())) { printLatLng(); } } // Check for GPS signal timeout if (millis() > 5000 && gps.charsProcessed() < 10) { Serial.println("No GPS data received: check wiring"); Particle.publish("error", "No GPS data received"); delay(1000); } }
If the GPS obtains a fix, it will display as follows.
Setting Up Firebase Real-Time Database
Firebase Real-Time Database is a NoSQL database that stores data as JSON objects. It synchronizes data in real-time across all connected clients, ensuring that every user sees the same data at the same time. Key features include:
- Real-time synchronization: Data changes are propagated instantly to all connected devices.
- Offline support: Firebase SDKs cache data locally, allowing apps to function offline and sync changes when reconnected.
- Scalability: Firebase RTDB can handle large-scale applications with millions of users.
Setting Up a Firebase Project
1. Create a Firebase Project:
- Go to the Firebase Console.
- Click "Add Project".
- Enter a project name and follow the prompts to create the project.
2. Add Firebase to Your App:
- After creating the project, click on the </>(web) icon to add Firebase to your web app.
- Register your app by providing a nickname.
- Firebase will generate a configuration object containing your API keys and other settings. Keep this handy when initializing Firebase in your app.
Enabling Firebase Realtime Database
1. Navigate to Real-Time Database:
- In the Firebase Console, go to the Build section in the left sidebar and select Realtime Database.
2. Create a Database:
- Click "Create Database".
- Choose a location for your database (preferably close to your users for better performance).
- Select "Start in test mode" to allow read/write access to all users temporarily (You can configure security rules later).
3. Database URL
- Once the database is created, Firebase will provide a unique URL for your database in the format: https://.firebaseio.com/.
- This URL is used to reference your database in your app.
4. Firebase Project ID:
The Firebase Project ID is a unique identifier for your Firebase project. It distinguishes your project from others and is required when making API calls or configuring Firebase services.
From the Firebase Console:
- Go to the Firebase Console.
- Select your project.
- Click on the gear icon (⚙️) next to "Project Overview" in the sidebar.
- Select "Project settings".
- Under the General tab, you will find the Project ID listed.
From the Firebase Configuration Object:
When you add Firebase to your app, Firebase provides a configuration object. This object contains the projectId field.
const firebaseConfig = {
apiKey: "YOUR_API_KEY",
authDomain: "YOUR_AUTH_DOMAIN",
projectId: "YOUR_PROJECT_ID", // This is your Firebase Project ID
storageBucket: "YOUR_STORAGE_BUCKET",
messagingSenderId: "YOUR_MESSAGING_SENDER_ID",
appId: "YOUR_APP_ID"
};
5. Firebase Auth Token (Firebase Database Secret)
The Firebase Database Secret is a legacy authentication mechanism for the Firebase Realtime Database. It is a long, randomly generated string that grants full read and write access to your entire database. It was primarily used for server-side applications or tools that needed unrestricted access to the database.
Go to the Firebase Console:
- Log in to the Firebase Console.
- Select your project.
Navigate to Project Settings:
- Click on the gear icon (⚙️) next to "Project Overview" in the sidebar.
- Select "Project settings".
Access the Database Secret:
- Go to the Service Accounts tab.
- Scroll down to the Database Secrets section.
- Click "Show" to reveal the secret. You can also click "Add secret" to generate a new one if needed.
- Copy the secret and store it securely. Treat it like a password, as it grants full access to your database.
Database Structure and Data Model
Firebase Real-time Database stores data as a JSON tree. Each node in the tree can contain key-value pairs or nested child nodes.
This is the database structure that we use:
{
"elephants": {
"elephantX": {
"geofence": {
"coordinates": "latitude1,longitude1|latitude2,longitude2|latitude3,longitude3|..."
},
"livelocation": {
"lat": "latitudeX",
"lng": "longitudeX"
},
"locations": {
"uniqueLocationId1": {
"latitude": "latitudeValue1",
"longitude": "longitudeValue1",
"timestamp": "timestampValue1"
},
"...": {
"latitude": "latitudeValueN",
"longitude": "longitudeValueN",
"timestamp": "timestampValueN"
}
}
},
"elephantY": {
"geofence": {
"coordinates": "latitude1,longitude1|latitude2,longitude2|latitude3,longitude3|..."
},
"livelocation": {
"lat": "latitudeY",
"lng": "longitudeY"
},
"locations": {
"uniqueLocationId1": {
"latitude": "latitudeValue1",
"longitude": "longitudeValue1",
"timestamp": "timestampValue1"
},
"...": {
"latitude": "latitudeValueN",
"longitude": "longitudeValueN",
"timestamp": "timestampValueN"
}
}
}
}
}
Setting Up Particle Integration with Firebase
Particle provides a built-in integration for Firebase, allowing you to send data directly to the Firebase Realtime Database.
We need 3 different integrations between Particle And Firebase to
- Get Geo-fence Data from Firebase to Particle
- Put real-time Location from Particle to Firebase
- Post real-time Location from Particle to Firebase
1. Get Geo-fence Data from Firebase to Particle
This integration involves fetching geofence data (e.g., boundary coordinates) from Firebase and sending it to the Particle device.
Create a Firebase Integration in Particle Console:
- Go to the Particle Console.
- Navigate to Integrations and create a new Firebase Integration.
- Configure the Firebase Integration:
- Event Name: getGeofence
- URL: https://.firebaseio.com/elephants/elephant/geofence.json
- Request Type: GET
Particle Firmware Code:
- Use Particle.subscribe() to listen for the geofence data.
#include "Particle.h"
void setup() {
Serial.begin(9600);
Particle.subscribe("hook-response/get-geofence", handleGeofenceData, MY_DEVICES);
}
void loop() {
// Request geofence data every 10 seconds
Particle.publish("get-geofence");
delay(10000);
}
void handleGeofenceData(const char *event, const char *data) {
Serial.println("Geofence Data:");
Serial.println(data);
}
2. Put Real-time Location from Particle to Firebase
This integration involves sending real-time location data from the Particle device to Firebase using a PUT request.
Create a Firebase Integration in Particle Console:
- Navigate to Integrations and create a new Firebase Integration.
- Configure the Firebase Integration:
- Request Type: PUT
- URL: https://.firebaseio.com/elephant/elephant/livelocation.json
- Event Name: putLocation
Particle Firmware Code:
- Use Particle.publish() to send location data.
#include "Particle.h"
void setup() {
Serial.begin(9600);
}
void loop() {
// Simulate location data
float lat = 37.7749 + (random(100) / 1000.0);
float lng = -122.4194 + (random(100) / 1000.0);
String data = String::format("{\"lat\": %f, \"lng\": %f, \"timestamp\": %d}", lat, lng, Time.now());
// Send location data
Particle.publish("put-location", data, PRIVATE);
delay(5000); // Send data every 5 seconds
}
3. Post Real-time Location from Particle to Firebase
This integration involves sending real-time location data from the Particle device to Firebase using a POST request to create a location history.
Create a Firebase Integration in Particle Console:
- Go to the Particle Console.
- Navigate to Integrations and create a new Firebase Integration.
- Configure the Firebase Integration:
- Event Name: post-location
- URL: https://.firebaseio.com/elephants/elephant/locations.json
- Request Type: POST
Particle Firmware Code:
- Use Particle.publish() to send location sample location data.
#include "Particle.h"
void setup() {
Serial.begin(9600);
}
void loop() {
// Simulate location data
float lat = 37.7749 + (random(100) / 1000.0);
float lng = -122.4194 + (random(100) / 1000.0);
String data = String::format("{\"lat\": %f, \"lng\": %f, \"timestamp\": %d}", lat, lng, Time.now());
// Send location data
Particle.publish("post-location", data, PRIVATE);
delay(5000); // Send data every 5 seconds
}
Integrating Twilio For SMS Alerts
Integrating Twilio with a Particle device allows you to send SMS alerts directly from the BSoM, making it ideal for applications where immediate notifications are crucial, such as in alert systems. Follow these steps to set up and integrate Twilio with your BSoM for sending SMS alerts.
Set Up a Twilio Account and Get Your Credentials
- If you don’t already have one, sign up for a Twilio account at Twilio's website.
- Once your account is set up, obtain your Account SID and Auth Token from the Twilio Console, as well as a Twilio phone number. You’ll need these to authorize and send SMS messages through Twilio.
Set Up a Twilio Integration in the Particle Console
- Log in to the Particle Console and navigate to the Integrations section.
- Click on New Integration and select Twilio.
- Event Name: Choose an event name, like twilio_sms_alert, which BSoM will trigger when it needs to send an SMS.
Parameters: Set up parameters fields as follows:
- Username: Your Twilio Account SID.
- Password: Your Twilio Auth Token.
- Twilio SID: Your Twilio Account SID.
Form Data: Set up form data fields as follows:
- From: Your Twilio phone number.
- To: The recipient’s phone number (the one to which SMS alerts will be sent).
- Body: The message text, which can include dynamic values such as {{PARTICLE_EVENT_VALUE}} if you want to customize the message from the BSoM code.
Website
The Elephant Geofence webpage serves as a sophisticated and user-friendly interface for monitoring elephant movement, managing geofence zones, and analyzing location data. Designed for conservationists, researchers, and field personnel, it provides a seamless blend of functionality and intuitive design. Key functionalities include
Real-Time Tracking
- Displays live positions of elephants on the map, ensuring up-to-date monitoring.
Geofence Management
- Load Geofence: Quickly load previously saved geofence zones.
- Save Geofence: Draw custom boundaries and save them for future monitoring.
Location History
- Tracks and visualizes the movement history of selected elephants using spline paths, enabling users to study patterns or behavior.
Technologies Used
Frontend
- HTML5 & CSS3: The core structure and styling of the webpage.
- Leaflet.js: Powers the interactive mapping features, including geofence drawing and live location tracking.
- Font Awesome: Provides high-quality icons to enhance the user experience.
- Google Fonts: Uses the "Smooch Sans" font for a clean and modern look.
Backend Integration
1. Firebase Realtime Database:
- Stores geofence data, elephant tracking information, and historical paths.
- Provides real-time updates to the front end for live location tracking.
2. JavaScript: Handles geofence creation, saving/loading functionalities, and map interaction.
Solar Power Setup
The project utilizes a solar power system comprising two 6V solar panels.
These panels will be connected to the solar power manager.
It is a high-efficiency solar power management module specifically designed for 5V solar panels. Featuring advanced MPPT (Maximum Power Point Tracking) technology, it maximizes solar panel efficiency and can provide up to 900mA charging current for 3.7V Li batteries through USB or solar panel inputs. The module includes controllable DC-DC converters with 5V 1A output, making it versatile for various solar power and low-power applications. Its comprehensive protection mechanisms safeguard the battery, solar panel, and output circuits, significantly enhancing the stability and safety of solar projects.
To power up the Eval Board we used an 1800mAh lipo battery.
Enclosure
We designed a custom enclosure using Fusion 360 to protect and house the device's components effectively. The enclosure has two parts: the upper section, which holds the solar panels, and the bottom section, which accommodates the charge controller, battery, and other electronics.
These parts are 3d printed with the PLA+
Assembly
First, we securely mounted the solar panels, connecting them in parallel to enhance the current output.
Next, we positioned the GPS module and connected it to the evaluation board using male-to-female jumper wires.
Then, we connected the charge controller to the battery and the evaluation board's VIN pin, as it supports an input voltage range of 5V to 12V.
Finally, we attached the solar panel wires to the charge controller, completing the entire assembly.
Final Testing and Deployment
This project showcases an efficient and sustainable solution for wildlife monitoring, leveraging IoT, GPS, and renewable energy technologies to ensure the safety of elephants and their natural habitats