Siddhant Kumar
Project 057 · Security

Asset GPS Tracker.

Tracks high-value equipment, wakes on movement, and raises an instant alert the moment an asset leaves its safe zone — all while sipping enough power to last weeks between charges.

Intermediate 12–18 hours 32 min read GPSGeofenceTheft
Jump to source Bill of materials
Asset GPS Tracker — reference build illustration MCU VCC · GND · SIG · NC
Difficulty
Intermediate
Build time
12–18 hours
Indicative cost
₹3,500 – ₹5,500
Platform
ESP32 DevKit V1 (ESP-WROOM-32)
Category
Security
Last updated
28 July 2026
Contents — 26 sections

Project Overview

Tracks high-value equipment, wakes on movement, and raises an instant alert the moment an asset leaves its safe zone — all while sipping enough power to last weeks between charges.

High-value equipment — generators, tools, plant machinery, trailers, medical devices — walks off, and by the time anyone notices it is missing, it is long gone. A GPS tracker attached to the asset closes that gap: it knows where the asset is, and — more usefully — it knows when the asset leaves where it is supposed to be and shouts about it immediately. This project builds a practical asset tracker centred on the two things that make such a device actually useful in the field: geofencing (an instant alert when the asset crosses out of a defined safe zone) and power endurance (lasting weeks or months on a battery, because a tracker you have to recharge every day will be flat when it matters).

Those two goals pull against each other, and resolving that tension is the core of the design. GPS and cellular are power-hungry; leaving them on continuously would flatten the battery in a day. The trick is that a stationary asset does not need tracking — so the tracker spends almost all its time in deep sleep, watching only a tiny accelerometer that wakes it the instant the asset actually moves. While parked, it costs almost nothing; when it moves, it wakes, gets a fix, checks the geofence, reports if needed, and goes back to sleep. This "sleep until moved" architecture is what turns a power-hungry radio stack into a device that lasts weeks.

When it does report, it reports over a network suited to the range: cellular (GSM/LTE-M) for go-anywhere coverage, or LoRa where a private gateway exists and running costs must be near zero. Every position and every geofence breach is logged and pushed, so an asset crossing its boundary triggers an immediate located alert while normal movement within the zone is handled quietly. The design is honest about the physics — GPS needs sky view and struggles indoors and in urban canyons, cellular has running costs and coverage gaps, and there is always a tension between how often you report and how long the battery lasts — and it manages those trade-offs deliberately rather than pretending them away. But as a wake-on-motion, geofenced, long-endurance tracker, it does exactly what asset protection needs: it stays quiet and alive for weeks, and the moment your equipment moves somewhere it should not, you know.

A GPS navigation satellite in orbit
A GPS tracker on high-value equipment knows where it is and alerts when it leaves its safe zone. Photograph sourced from Wikimedia Commons — GPS satellite.jpg. Reused under the licence stated on that page; please check it before republishing.

What this project does

  • Reports the asset's GPS location on movement or on a schedule
  • Wakes from deep sleep on motion via an accelerometer (sleep-until-moved)
  • Raises an instant alert when the asset leaves a defined geofence
  • Reports over cellular (anywhere) or LoRa (private, low running cost)
  • Logs positions and breaches; pushes located alerts
  • Lasts weeks–months on battery by sleeping while the asset is parked
  • Manages the report-rate vs battery-life trade-off deliberately

Real-World Applications

SettingHow it is used
Construction / plant equipmentTracking generators, compressors and tools across and between sites, with theft alerts when they leave a yard.
Trailers / containers / vehiclesGeofenced tracking of movable assets, alerting on unauthorised movement.
Logistics / high-value shipmentsFollowing valuable cargo and alerting if it deviates from its route/zone.
Medical / rental equipmentLocating expensive portable devices and flagging when they leave a facility.

Deployment contexts where a build of this kind earns its keep.

Features & Capabilities

  • Geofencing with instant breach alerts
  • Wake-on-motion deep-sleep for long battery life
  • Cellular or LoRa backhaul to suit coverage/cost
  • Position and breach logging
  • Adaptive reporting (more often when moving, rarely when still)
  • Honest handling of GPS/coverage limits
  • Compact, attachable, long-endurance design

Difficulty, Time & Required Skills

AttributeValue
Difficulty levelIntermediate
Estimated completion time12–18 hours
Indicative build cost₹3,500 – ₹5,500
Primary disciplineSecurity
Reference platformESP32 DevKit V1 (ESP-WROOM-32)

Skills you should have (or will pick up)

  • Reading GPS (NMEA) and getting a reliable fix
  • Wake-on-motion deep sleep with an accelerometer interrupt
  • Geofence maths (point-in-zone, distance)
  • Cellular/LoRa backhaul and power budgeting
  • Balancing report rate against battery life

Bill of Materials

Every part below is commonly available from Indian and international hobby-electronics suppliers. Prices are indicative 2026 retail figures in Indian rupees and will drift — treat them as a budgeting guide, not a quotation.

ComponentKey specificationQtyApprox. cost
ESP32 DevKit V1 (ESP-WROOM-32)
Wi-Fi transmit bursts peak near 500 mA — size the regulator accordingly.
Dual-core Xtensa LX6 @ 240 MHz, 520 KB SRAM, 4 MB flash, Wi-Fi 802.11 b/g/n + BLE 4.2, 34 GPIO, 18× 12-bit ADC, 2× 8-bit DAC1₹450
u-blox NEO-6M GPS module + ceramic patch antenna
Needs clear sky view; indoors it will never get a first fix.
50 channels, −161 dBm tracking, 2.5 m CEP, 1–5 Hz update, cold start 27 s1₹550
SIM800L GSM/GPRS module
Transmit bursts hit 2 A — needs a 4.0 V supply and a 1000 µF bulk capacitor.
Quad-band 850/900/1800/1900 MHz, GPRS class 12, SMS + TCP/IP1₹550
MPU-6050 6-axis IMU
Gyro bias drifts with temperature — re-zero at boot while the device is still.
3-axis gyro ±250–2000 °/s, 3-axis accel ±2–16 g, 16-bit ADC, on-chip DMP1₹190
18650 Li-ion cell 3400 mAh + holder
Never charge below 0 °C; always use a protected cell or a BMS.
3.7 V nominal, 4.2 V full, 3400 mAh, ~12.6 Wh, 2 C discharge1₹450
TP4056 Li-ion charger + DW01 protection
Buy the version *with* protection ICs — the bare charger will over-discharge your cell.
1 A programmable CC/CV charge to 4.2 V ±1 %, over-discharge and short protection1₹45
20 W 12 V polycrystalline solar panel
Rated watts assume 1000 W/m² — plan for 60–70 % of nameplate in real installs.
Vmp 17.5 V, Imp 1.14 A, Voc 21.6 V, 350 × 290 mm, aluminium frame1₹1,200
Cellular modem + SIM (or LoRa)
LTE-M/NB-IoT is more power-efficient than 2G where available
GSM/LTE-M modem + data SIM for anywhere coverage, or LoRa for private low-cost1₹1,200
GPS antenna (good sky view)Active GPS antenna positioned for sky visibility on the asset1₹250
Large battery + optional solar
Sleep-until-moved makes a big pack last months
High-capacity Li-ion pack; small solar to extend endurance on outdoor assets1₹700
Discreet rugged enclosureConcealable, weatherproof, hard to spot/remove1₹400

Estimated total: ₹5,985, excluding tools, shipping and consumables.

Tools and consumables

  • Soldering iron (temperature controlled, 350 °C) with 0.8 mm 60/40 or lead-free solder
  • Digital multimeter — continuity, DC volts and current ranges
  • Wire strippers, flush cutters and a small set of precision screwdrivers
  • Heat-shrink tubing and a heat gun (or a lighter, carefully)
  • A laptop with a USB port and the toolchain listed above

Hardware Specifications

PartSpecificationSupplyInterfaceReference
ESP32 DevKit V1 (ESP-WROOM-32)Dual-core Xtensa LX6 @ 240 MHz, 520 KB SRAM, 4 MB flash, Wi-Fi 802.11 b/g/n + BLE 4.2, 34 GPIO, 18× 12-bit ADC, 2× 8-bit DAC3.3 V logic / 5 V USBUART, SPI, I²C, I²S, CAN, PWMDatasheet
u-blox NEO-6M GPS module + ceramic patch antenna50 channels, −161 dBm tracking, 2.5 m CEP, 1–5 Hz update, cold start 27 s3.3–5 VUART NMEA 9600Datasheet
SIM800L GSM/GPRS moduleQuad-band 850/900/1800/1900 MHz, GPRS class 12, SMS + TCP/IP3.4–4.4 V (NOT 5 V)UART AT commandsDatasheet
MPU-6050 6-axis IMU3-axis gyro ±250–2000 °/s, 3-axis accel ±2–16 g, 16-bit ADC, on-chip DMP2.375–3.46 V (module 5 V tolerant)I²C (0x68/0x69)Datasheet
18650 Li-ion cell 3400 mAh + holder3.7 V nominal, 4.2 V full, 3400 mAh, ~12.6 Wh, 2 C discharge3.0–4.2 VHolder / spot-welded tabsDatasheet
TP4056 Li-ion charger + DW01 protection1 A programmable CC/CV charge to 4.2 V ±1 %, over-discharge and short protection4.5–5.5 V inmicro-USB / padsDatasheet
20 W 12 V polycrystalline solar panelVmp 17.5 V, Imp 1.14 A, Voc 21.6 V, 350 × 290 mm, aluminium frame12 V nominalMC4 / screw terminalsDatasheet

Consolidated electrical and interface specifications for every active part in the build.

Power Budget & Supply Sizing

Add up the typical active current of every part, then size the supply with at least 50 % headroom so transmit bursts and motor inrush never brown out the controller.

LoadSupply railTypical current (mA)Notes
ESP32 DevKit V1 (ESP-WROOM-32)3.3 V logic / 5 V USB160Wi-Fi transmit bursts peak near 500 mA — size the regulator accordingly.
u-blox NEO-6M GPS module + ceramic patch antenna3.3–5 V45Needs clear sky view; indoors it will never get a first fix.
SIM800L GSM/GPRS module3.4–4.4 V (NOT 5 V)2000Transmit bursts hit 2 A — needs a 4.0 V supply and a 1000 µF bulk capacitor.
MPU-6050 6-axis IMU2.375–3.46 V (module 5 V tolerant)3.9Gyro bias drifts with temperature — re-zero at boot while the device is still.
TP4056 Li-ion charger + DW01 protection4.5–5.5 V in1000Buy the version *with* protection ICs — the bare charger will over-discharge your cell.
20 W 12 V polycrystalline solar panel12 V nominal1140Rated watts assume 1000 W/m² — plan for 60–70 % of nameplate in real installs.

Summed typical draw is 4348.9 mA. With a 1.5× design margin the supply should deliver at least 6600 mA continuously at the stated rail voltage.

Software Requirements & Development Environment

Reference toolchain: Arduino IDE 2.3.x with the ESP32 board package 3.x (or PlatformIO on VS Code). Anything newer normally works; anything older may lack the board definitions used here.

  • Install the Arduino IDE 2.3.x (or PlatformIO if you prefer a real editor and dependency locking).
  • Add https://espressif.github.io/arduino-esp32/package_esp32_index.json under File → Preferences → Additional Board Manager URLs, then install esp32 from the Boards Manager.
  • Set the correct port under Tools → Port. On Linux add yourself to the dialout group: sudo usermod -aG dialout $USER and log out and back in.
  • Open the Serial Monitor at 115200 baud — every sketch here logs its state there.
  • Keep File → Preferences → Show verbose output during: compilation switched on while you are debugging build errors.

Required libraries

LibraryWhy it is neededInstall
WiFi (ESP32 core) bundledStation/AP connection management for the ESP32.Bundled with the ESP32 Arduino core
TinyGPSPlus 1.0.3Streaming NMEA parser producing latitude, longitude, speed and time.Library Manager → "TinyGPSPlus" by Mikal Hart
MPU6050_light / Adafruit MPU6050 1.3.xIMU register access, calibration and complementary-filter angles.Library Manager → "MPU6050_light" by rfetick
ArduinoJson 7.xZero-allocation JSON serialisation and parsing.Library Manager → "ArduinoJson" by Benoit Blanchon
Preferences (NVS) bundledWear-levelled key/value storage in ESP32 flash for settings.Bundled with the ESP32 core
HTTPClient bundledREST calls to cloud endpoints over HTTP/HTTPS.Bundled with the ESP32 core

Block Diagram

The block diagram shows the functional decomposition of the system — what senses, what decides, what acts, and where the data ends up.

Asset GPS Tracker — system block diagramFunctional block diagram of the Asset GPS Tracker system. Watch (asleep)Accelerometermotion wakeOn movementGPS fixNEO-6MESP32geofence checkReportCellular/LoRaposition + breachOwnerMaplocation + zonesAlertgeofence breachrightrightnone
Asset GPS Tracker — system block diagram

Circuit Diagram & Wiring

Every signal line in the build is shown below, followed by a pin-by-pin connection table you can work through with a multimeter in hand.

Asset GPS Tracker — wiring schematicConnection schematic showing which controller pin drives each peripheral. Sensors / InputsControllerActuators / OutputsESP32 DevKit V1(ESP-WROOM-32)3.3 V logic / 5 V USBNEO-6M GPSGPIO 16/17NMEA position (UART)MPU-6050GPIO 21/22/34Motion wake (I²C +INT)ModemGPIO 26/27Cellular backhaulLoRa (alt)GPIO 18/19/23/5Private low-costbackhaulBattery senseGPIO 35Battery levelTP4056 + solar3V3 regCharge + supplyStatus LEDGPIO 2Fix/report indicator
Asset GPS Tracker — wiring schematic
PeripheralPeripheral pinController pinSignal
NEO-6M GPSTX/RXGPIO 16/17NMEA position (UART)
MPU-6050SDA/SCL/INTGPIO 21/22/34Motion wake (I²C + INT)
ModemTX/RXGPIO 26/27Cellular backhaul
LoRa (alt)SPIGPIO 18/19/23/5Private low-cost backhaul
Battery senseADCGPIO 35Battery level
TP4056 + solarOUT3V3 regCharge + supply
Status LEDINGPIO 2Fix/report indicator

Wire one row at a time and tick it off — most "it does not work" reports trace back to a single swapped pair.

Wiring explanation

  • Wire the accelerometer's interrupt to a deep-sleep wake pin so motion brings the tracker out of sleep with almost no idle power.
  • Give the GPS a good sky-view antenna placement; GPS is useless without a view of the sky.
  • Power the cellular modem from a supply that can handle its transmit current spikes without browning out the ESP32.
  • Sense the battery so low-battery is reported before the tracker dies silently.
  • Mount discreetly and protect the battery/antenna; a visible tracker is removed, and a shaded antenna does not fix.
An ESP32 development board with the ESP-WROOM-32 module and USB connector
ESP32 module getting a GPS fix on movement and checking it against the geofence. Photograph sourced from Wikimedia Commons — ESP32 Espressif ESP-WROOM-32 Dev Board.jpg. Reused under the licence stated on that page; please check it before republishing.

System Architecture

Read the stack from the bottom up: physical hardware, the firmware that drives it, the transport that moves data off the device, and the software a human actually looks at.

Asset GPS Tracker — architecture stackLayered architecture from hardware to user interface. Hardware layerESP32 DevKit V1 (ESP-WROOM-32) · u-blox NEO-6M GPS module + ceramic patchantenna · MPU-6050 6-axis IMUDriver layerwifi · tinygps · mpu · arduinojsonApplication logicsampling loop · filtering · thresholds · state machineTransport layerCellular (or LoRa) → tracking platform · TLS · retry and backoffPresentation layerdashboard · mobile notifications · historical charts
Asset GPS Tracker — architecture stack

Working Principle

An asset tracker's usefulness hinges on two properties that fight each other: it must report meaningfully (know where the asset is and, crucially, when it leaves where it should be), and it must last (survive weeks or months on a battery, because a dead tracker protects nothing and constant recharging is impractical for equipment left in a yard or a field). GPS receivers and cellular radios are the power villains — each can draw far more than the rest of the system combined — so naive "get a fix and send it every minute" designs flatten a battery in a day. The entire art is delivering the reporting value at a tiny fraction of that power cost.

The resolution is a simple, powerful observation: a stationary asset does not need tracking. Its position is not changing, so acquiring fresh fixes and sending them is pure waste. So the tracker's default state is deep sleep, in which the power-hungry GPS and modem are off and the only thing awake is a micro-power accelerometer configured to fire an interrupt on motion. Parked, the whole device costs microamps. The instant the asset moves, the accelerometer wakes the processor, which powers up GPS, gets a fix, checks it, reports if warranted, and returns to sleep. This "sleep-until-moved" architecture is what makes a large battery last for months instead of a day — the expensive work happens only when something is actually happening.

The reporting value comes from geofencing. A raw stream of positions is far less useful than a single, timely alert that says "the asset just left its safe zone". A geofence is a defined area — a circle around a yard, a polygon around a site — and the tracker checks each new fix against it: as long as the asset is inside, movement is logged quietly; the moment a fix falls outside, it fires an immediate breach alert. This is exactly the theft/loss signal an owner cares about, and it is cheap to compute on-device (a point-in-circle is a distance comparison; point-in-polygon is a simple ray-cast). Geofencing also lets the tracker be adaptive: report frequently while the asset is moving or has breached, and rarely (or only on the periodic heartbeat) while it sits safely in its zone.

The remaining design is honest engineering around real limits. GPS needs a view of the sky, so it is unreliable indoors, under dense cover, and in urban canyons — the tracker must tolerate failed fixes (retry, fall back to the last known position, or cell-tower approximation) rather than assume a fix always comes. The backhaul is chosen for the job: cellular (ideally power-efficient LTE-M/NB-IoT) for go-anywhere coverage at some running cost, or LoRa where a private gateway exists and per-message cost must be near zero. And the report rate is understood as a direct trade against battery life and cellular cost, tuned deliberately (frequent when moving, sparse when still) rather than left as an afterthought. Physical design matters too — discreet, rugged mounting so the tracker is not spotted and ripped off, and a protected antenna with sky view. None of these limits are hidden; they are the constraints the design is built around. The result is a tracker that lives quietly for months and, the moment your equipment crosses a line it should not, tells you at once and where.

The maths behind it

Circular geofence (point-in-circle)

plainCircular geofence (point-in-circle)
Breach if the asset is farther than R from the zone centre.
Haversine distance between fix (φ1,λ1) and centre (φ2,λ2):

  a = sin²(Δφ/2) + cosφ1·cosφ2·sin²(Δλ/2)
  d = 2R_earth·atan2(√a, √(1−a))

  breach if d > R_geofence   (with a small hysteresis margin)

Wake-on-motion power budget

plainWake-on-motion power budget
Battery life is set by how rarely the expensive stack runs:

  life ≈ capacity / ( I_sleep + f_move·(E_fix+E_tx)/T )

I_sleep (accel-only, µA) dominates when parked.
A large battery + sleep-until-moved → weeks/months,
whereas always-on GPS+modem → ~a day.

Adaptive report rate

plainAdaptive report rate
moving   → report every T_move (e.g. 30–60 s)
breached → report immediately + fast until re-secured
parked   → heartbeat every T_park (e.g. 6–24 h)

Rate trades directly against battery life and cellular cost;
tie it to state (motion + geofence) rather than a fixed timer.

Program Flowchart

The firmware is a single cooperative loop. Nothing blocks for long, so networking, sensing and the user interface all stay responsive.

Asset GPS Tracker — firmware flowchartControl flow through the main program loop. Deep sleep (watch accel)Motion wake or schedule?Get GPS fixDeep sleep (watch accel)Get GPS fixOutside geofence?Instant breach alert + reportReport position (if moving)Instant breach alert + reportReport position (if moving)Back to deep sleep
Asset GPS Tracker — firmware flowchart

Assembly Instructions

Build on a breadboard first and only commit to solder once the whole system has run for an hour without a fault.

  1. Wire wake-on-motion sleep

    Configure the accelerometer's motion interrupt and route it to an ESP32 deep-sleep wake pin, so the device sleeps at microamps and wakes only on movement.

    Confirm the GPS and modem are fully powered down during sleep.

  2. Fit GPS and backhaul

    Place the GPS antenna for sky view; wire the cellular modem (or LoRa) with a supply that tolerates its transmit current spikes. Sense the battery for supervision.

  3. Mount discreetly with protected power

    House the tracker in a concealable, rugged enclosure with a large battery (and optional solar for outdoor assets), positioned so the antenna sees the sky but the device is not obvious.

Step-by-Step Implementation Guide

Work through these in order. Each step ends in something you can observe, so a failure is always localised to the step you just finished.

  1. Check the geofence and decide reporting

    On each fix, compute the distance to the geofence and raise a breach alert if outside; otherwise report at the rate set by the current state (moving/parked).

    cppgeofence.ino
    struct Geofence { double lat, lon; float radius_m; };
    
    // Haversine distance in metres.
    double haversine(double la1,double lo1,double la2,double lo2){
      const double R=6371000.0, d2r=M_PI/180.0;
      double dla=(la2-la1)*d2r, dlo=(lo2-lo1)*d2r;
      double a=sin(dla/2)*sin(dla/2)
              +cos(la1*d2r)*cos(la2*d2r)*sin(dlo/2)*sin(dlo/2);
      return 2*R*atan2(sqrt(a),sqrt(1-a));
    }
    
    bool outsideGeofence(double lat,double lon,const Geofence &g){
      double d = haversine(lat,lon,g.lat,g.lon);
      return d > g.radius_m + GEO_HYSTERESIS;      // margin avoids edge flapping
    }
    
    // Decide report cadence from movement + geofence state.
    uint32_t nextReportDelay(bool moving,bool breached){
      if (breached) return 15;                     // fast while lost
      if (moving)   return 45;                      // frequent while moving
      return 6*3600;                                // heartbeat while parked
    }
    double haversine(Computes the great-circle distance between the fix and the geofence centre, the basis of the point-in-circle breach test.
    return d > g.radius_m + GEO_HYSTERESISA hysteresis margin around the boundary prevents the tracker from flapping in and out of "breach" when a noisy fix sits right on the fence.
    if (breached) return 15;Once outside the safe zone the tracker reports fast, so a moving-away asset is followed closely.
    return 6*3600;A safely-parked asset only heartbeats every few hours, which is what lets the battery last for months.
  2. Get a fix robustly and report

    Power up GPS on wake, wait for a valid fix with a timeout, and on success check the geofence and report; on a failed fix, fall back to last-known/cell approximation and retry rather than blocking.

Complete Source Code

The listing below is complete and compiles as written — there are no elided sections. Read the annotations under each block before you upload it.

cppasset-gps-tracker.ino
/* ═══════════════════════════════════════════════════════════════
   Asset GPS Tracker — ESP32, wake-on-motion, geofenced, low-power

   Sleeps at microamps watching an accelerometer; on motion, gets a GPS
   fix, checks the geofence, and reports over cellular/LoRa — raising an
   instant alert on a breach. Adaptive report rate for weeks of life.
   ══════════════════════════════════════════════════════════════════ */

#include <TinyGPS++.h>
#include <Preferences.h>
#include <math.h>

#define GPS_RX 16
#define GPS_TX 17
#define PIN_ACCEL_INT 34    // accelerometer motion interrupt (wake)
#define GPS_TIMEOUT_MS 90000
#define GEO_HYSTERESIS 30.0f

TinyGPSPlus gps;
HardwareSerial gpsSer(1);
Preferences prefs;

struct Geofence { double lat, lon; float radius_m; } fence;
RTC_DATA_ATTR bool wasBreached = false;

double haversine(double la1,double lo1,double la2,double lo2){
  const double R=6371000.0,d2r=M_PI/180.0;
  double dla=(la2-la1)*d2r,dlo=(lo2-lo1)*d2r;
  double a=sin(dla/2)*sin(dla/2)+cos(la1*d2r)*cos(la2*d2r)*sin(dlo/2)*sin(dlo/2);
  return 2*R*atan2(sqrt(a),sqrt(1-a));
}

bool getFix(double &lat,double &lon){
  gpsSer.begin(9600,SERIAL_8N1,GPS_RX,GPS_TX);
  uint32_t t0=millis();
  while(millis()-t0 < GPS_TIMEOUT_MS){        // bounded wait — never forever
    while(gpsSer.available()) gps.encode(gpsSer.read());
    if(gps.location.isValid() && gps.location.age()<2000){
      lat=gps.location.lat(); lon=gps.location.lng();
      return true;
    }
  }
  return false;                                // fall back to last-known
}

void report(double lat,double lon,bool breach,float batt){
  // Send over cellular/LoRa (modem code elided).
  char msg[200];
  snprintf(msg,sizeof msg,
    "{\"lat\":%.6f,\"lon\":%.6f,\"breach\":%d,\"batt\":%.2f}",
    lat,lon,breach?1:0,batt);
  sendOverModem("asset/57/pos", msg);
  if (breach) sendOverModem("asset/57/alert", "GEOFENCE BREACH");
}

void loadFence(){
  prefs.begin("trk",true);
  fence.lat=prefs.getDouble("flat",0);
  fence.lon=prefs.getDouble("flon",0);
  fence.radius_m=prefs.getFloat("fr",200.0f);
  prefs.end();
}

void goToSleep(uint64_t seconds){
  // Wake on accelerometer motion OR after a scheduled heartbeat.
  esp_sleep_enable_ext0_wakeup((gpio_num_t)PIN_ACCEL_INT, 1);
  esp_sleep_enable_timer_wakeup(seconds*1000000ULL);
  esp_deep_sleep_start();
}

void setup(){
  Serial.begin(115200);
  loadFence();

  esp_sleep_wakeup_cause_t cause = esp_sleep_get_wakeup_cause();
  bool byMotion = (cause == ESP_SLEEP_WAKEUP_EXT0);

  double lat, lon; float batt = readBattery();
  bool haveFix = getFix(lat, lon);

  if (haveFix){
    double d = haversine(lat,lon,fence.lat,fence.lon);
    bool breach = d > fence.radius_m + GEO_HYSTERESIS;
    if (breach || byMotion || !wasBreached==breach)   // report on change/motion
      report(lat, lon, breach, batt);
    wasBreached = breach;

    uint64_t sleep_s = breach ? 15 : (byMotion ? 45 : 6*3600);
    goToSleep(sleep_s);
  } else {
    // no fix (indoors/cover) — brief retry then long sleep to save power
    goToSleep(byMotion ? 60 : 6*3600);
  }
}

void loop(){}   // deep sleep restarts setup()
esp_sleep_enable_ext0_wakeup((gpio_num_t)PIN_ACCEL_INT, 1)The accelerometer's motion interrupt is a deep-sleep wake source, so the tracker sits at microamps until the asset actually moves.
while(millis()-t0 < GPS_TIMEOUT_MS)The GPS wait is bounded, so a device that cannot see the sky times out and sleeps again rather than draining the battery waiting for a fix that will not come.
bool breach = d > fence.radius_m + GEO_HYSTERESISEach fix is tested against the geofence with a hysteresis margin, and a breach triggers an immediate alert.
uint64_t sleep_s = breach ? 15 : (byMotion ? 45 : 6*3600)The sleep interval adapts to state — seconds when lost, tens of seconds when moving, hours when safely parked — which is the report-rate-versus-battery trade made concrete.
goToSleep(byMotion ? 60 : 6*3600)Even a failed fix leads straight back to sleep, so an asset stuck indoors does not burn the battery retrying continuously.

Configuration & Calibration

Configuration steps

  • Set the geofence (centre/radius or polygon) and the hysteresis margin.
  • Set the moving/breached/parked report intervals and the GPS fix timeout.
  • Choose cellular vs LoRa backhaul and configure credentials/APN or gateway.
  • Set battery-low thresholds and any solar-charging behaviour.

Calibration procedure

An uncalibrated sensor produces confident, precise, wrong numbers. Do this once per physical unit and record the constants.

  1. GPS fix

    Confirm a reliable fix outdoors with sky view and measure typical time-to-fix; set the timeout accordingly and place the antenna well.

  2. Geofence

    Walk/drive the asset across the boundary and confirm the breach fires cleanly (no flapping) thanks to the hysteresis margin.

  3. Power

    Measure sleep current and per-report energy; verify the projected battery life meets your requirement at the chosen report rate.

Network Architecture & Connectivity

Asset GPS Tracker — network topologyPath taken by telemetry from field node to end user. Edge nodesGatewayCloudClientsAsset trackerESP32Other assetsfleetCellular / LoRaCarrier / LoRa GWto platformMQTT/HTTPSTracking platformpositions + geofencesMap/apptrack + zonesPhonebreach alerts
Asset GPS Tracker — network topology

Communication protocol

Positions publish on movement/heartbeat and breaches immediately. Reporting cadence is tied to state to balance battery life and (on cellular) data cost.

Topic / endpointDirectionPayload
asset/57/postracker → platformlat, lon, breach flag, battery
asset/57/alerttracker → platformgeofence breach / low battery
asset/57/configplatform → trackergeofence, report rates

Message contract between the device and the broker.

Cloud platform configuration

A tracking platform maps each asset and its geofences, stores tracks, and pushes instant breach and low-battery alerts; geofences can be updated remotely.

Dashboard setup

A map of assets and zones, per-asset track history, and an alert log of breaches and low-battery events.

Mobile app integration

Instant geofence-breach alerts with location, and low-battery/maintenance alerts.

Security considerations

  • Authenticate the tracker and encrypt reports so location cannot be spoofed or snooped.
  • Protect geofence/config updates so only the owner can change them.
  • Alert on unexpected silence — a jammed or destroyed tracker is itself significant.

Testing Procedure & Expected Output

Test from the bottom up. Confirm power, then each sensor in isolation, then the integrated loop — the first failing step tells you exactly where to look.

TestWhat you should see
Leave the asset parkedDeep sleep at microamps; only periodic heartbeats
Move the assetAccelerometer wakes it; a fix is taken and reported
Carry it out of the geofenceInstant breach alert; fast reporting follows
Take it indoorsNo fix within timeout; sleeps and retries without draining
Run a multi-day endurance testBattery lasts to the projected life at the set report rate
Drain the battery lowLow-battery reported before it dies

Bench-test checklist. If a row fails, stop and fix it before moving on.

Expected output

The map shows the asset's track and its geofence; a breach produces an instant located alert, and normal parked periods show only sparse heartbeats.

jsonasset-pos.json
{
  "lat": 28.61390,
  "lon": 77.20900,
  "breach": 1,
  "batt": 3.71
}

A breach report places the asset outside its safe zone and fires an alert; while the asset is parked inside the zone, the tracker sleeps and sends only occasional heartbeats to preserve battery.

Pallet racking in a distribution warehouse
The tracker sleeps for weeks watching an accelerometer, waking only when the asset actually moves. Photograph sourced from Wikimedia Commons — Warehouse racking.jpg. Reused under the licence stated on that page; please check it before republishing.

Troubleshooting: Common Errors & Fixes

Battery dies in a day

Likely cause. GPS/modem not powered down in sleep

Fix. Ensure true deep sleep with only the accelerometer awake; wake on motion

No fix / wrong location

Likely cause. Indoors, poor antenna, or urban canyon

Fix. Place antenna for sky view; time out and retry; fall back to last-known/cell approx

Geofence alerts flap

Likely cause. Noisy fixes at the boundary

Fix. Add a hysteresis margin; require the breach to persist a fix or two

Misses movement

Likely cause. Accelerometer wake threshold too high

Fix. Lower the motion threshold; verify the interrupt wakes deep sleep

High cellular cost

Likely cause. Reporting too often

Fix. Report on state (moving/breach) not a fixed fast timer; use LTE-M/NB-IoT/LoRa

The sketch will not upload — "Failed to connect" or "avrdude: stk500_recv()"

Likely cause. The bootloader is not being reached: wrong port, wrong board, a serial monitor holding the port open, or a USB cable that only carries power.

Fix. Close every serial monitor, confirm Tools → Board and Port, and swap to a known data-capable USB cable. On an ESP32 hold BOOT while the IDE prints "Connecting…", then release. If a peripheral is wired to the UART pins (GPIO 1/3 on ESP32, D0/D1 on Uno) unplug it — it fights the programmer.

The board resets in a loop, or the serial monitor prints "Brownout detector was triggered"

Likely cause. The supply cannot deliver peak current. Wi-Fi transmit bursts, relay coils and servos all pull far more than their average draw.

Fix. Power peripherals from a separate regulated supply with a common ground rather than from the board 5 V pin. Add a 470–1000 µF electrolytic capacitor across the supply near the load, and use a real power adapter rather than a laptop USB port.

Serial monitor shows garbage characters

Likely cause. Baud rate mismatch between Serial.begin() and the monitor, or a floating/shared UART line.

Fix. Set the monitor to 115200 to match the sketch. If it still garbles, the crystal or the USB bridge is being confused by noise — shorten the cable and keep motor wiring away from the USB lead.

An I²C device is not detected

Likely cause. Wrong address, missing pull-ups, swapped SDA/SCL, or a bus too long for the pull-up value.

Fix. Run an I²C scanner sketch first — it should print the device address. Most breakout boards include 4.7 kΩ pull-ups, but if you have chained four of them the parallel resistance is too low; remove the pull-ups from all but one board. Keep the bus under 30 cm at 100 kHz.

Wi-Fi connects but MQTT never does (state -2)

Likely cause. Wrong broker address or port, a firewall in the way, or the broker requiring credentials the sketch is not sending.

Fix. Test from a laptop on the same network first: mosquitto_sub -h <broker> -t "#" -v. If that works, the problem is on the device — check the IP literal, port 1883 (or 8883 for TLS), and that client.setServer() runs before connect(). PubSubClient state codes are documented in its header.

Readings arrive for a while and then stop

Likely cause. The Wi-Fi or MQTT session dropped and the sketch never reconnects, or the broker dropped the client on keep-alive timeout.

Fix. Never assume the link stays up. Check WiFi.status() and client.connected() at the top of every loop and reconnect with exponential backoff. Add a watchdog so a wedged network stack reboots the device instead of going silent.

Performance Optimisation

  • Deep-sleep with only the accelerometer awake; this dominates battery life.
  • Bound the GPS-on time and report on state, not a fixed fast timer.
  • Use power-efficient backhaul (LTE-M/NB-IoT or LoRa) and small payloads.
  • Cache the geofence and last state in RTC memory so wakes are quick and cheap.
  • Replace every delay() with a millis() comparison — blocking delays are the single most common cause of dropped readings.
  • Sample sensors on a fixed cadence and publish on a slower one; you almost never need to transmit at the sampling rate.
  • Move networking into its own FreeRTOS task so a slow DNS lookup cannot stall the control loop.
  • Use uint8_t / uint16_t where the range allows; on an 8-bit AVR a 32-bit add costs four times as much.
  • Batch several samples into one MQTT publish. Radio time, not CPU time, dominates the energy budget.
  • Set the MQTT keep-alive to a value that matches your reporting interval so the broker does not churn reconnections.
  • For battery builds use deep sleep between samples: an ESP32 drops from ~160 mA awake to about 10 µA asleep, which is the difference between days and months of runtime.

Safety Precautions

  • Track only assets you own or are authorised to track; covert tracking of people is unlawful and unethical.
  • Protect location data — it is sensitive; authenticate and encrypt.
  • Mind battery/enclosure safety, especially for vehicle-mounted or outdoor trackers.
  • Do not rely on GPS where it cannot work (indoors/underground); design for its limits.
  • Lithium cells vent and burn when abused. Only use protected cells or a proper BMS, never charge below 0 °C, and never leave a charging pack unattended on a wooden desk.
  • Never power an RF module without its antenna fitted — the reflected power destroys the output stage. Check your local licence-free band and duty-cycle limits before transmitting.
  • Wear eye protection when soldering or cutting, and solder in a ventilated space — rosin flux fumes are a respiratory irritant.
  • Power the circuit through a bench supply with a current limit while you are testing. A 300 mA limit turns a wiring mistake into a beep instead of a dead board.
  • Disconnect power before changing any wiring. Hot-plugging a sensor onto a live bus is the fastest way to lose a controller.

Maintenance

  • Recharge/replace batteries per the endurance test; verify solar (if used) keeps up.
  • Check antenna placement and fix quality after any remounting.
  • Review geofences and report rates as usage changes.
  • Confirm cellular coverage/plan or LoRa gateway reach at the asset's locations.
  • Re-check every screw terminal and header after the first week — thermal cycling loosens connections that felt tight on day one.
  • Log pack voltage. When resting voltage after a full charge drops below about 4.0 V, the cell is near end of life — replace it.
  • Wash the panel every few weeks in dusty conditions; a visible dust film costs 15–25 % of the harvest.
  • Keep the broker and dashboard containers patched, and rotate device credentials at least once a year.
  • Recalibrate at the interval given in the calibration section, and keep the constants in a text file next to the firmware — not only in flash.
  • Keep a short logbook of firmware versions and what changed. Six months later you will not remember why that constant is 1.083.

Future Improvements & Upgrades

A working v1 is a platform, not a finish line. These are the upgrades that add the most capability for the least rework.

  • Add cell-tower/Wi-Fi positioning fallback for indoor/urban approximate location.
  • Add tamper/removal detection (light/tilt) to alert if the tracker is found and removed.
  • Add route/corridor geofences for shipments, not just static zones.
  • Fuse motion classification (idle/transport/theft-like) to refine reporting.
  • Design a proper PCB. Once the breadboard version has run for a month, moving to a two-layer board removes the intermittent-contact failures that dominate prototype faults.
  • Add over-the-air firmware updates so you never have to physically reach a deployed node again.
  • Add persistent local storage (microSD or the on-chip flash) so a network outage does not create a hole in your data.
  • Move configuration out of the source: a captive-portal setup page or a JSON config file makes the build reusable without a recompile.
  • Add a battery and solar option so the unit survives a power cut and can be sited away from a socket.
  • Write a small test harness that feeds synthetic sensor values through the decision logic, so you can validate thresholds without physically triggering the event.

Frequently Asked Questions

How does it last weeks on a battery?

By sleeping. A parked asset does not need tracking, so the tracker deep-sleeps at microamps watching only an accelerometer, and wakes the power-hungry GPS/modem only when the asset actually moves.

What is a geofence and why is it the key feature?

A defined safe zone. The tracker checks each fix against it and alerts instantly if the asset leaves — which is the theft/loss signal you actually care about, far more useful than a raw stream of positions.

Will it work indoors?

GPS needs a view of the sky, so indoors/underground it may not get a fix. The design times out and retries rather than draining the battery, and can fall back to last-known or cell-tower approximation.

Cellular or LoRa?

Cellular (ideally LTE-M/NB-IoT) for anywhere coverage at some running cost; LoRa where you have a private gateway and want near-zero per-message cost. The design supports either.

How do I keep it from being found and removed?

Mount it discreetly in a rugged enclosure, protect the battery and antenna, and consider tamper/removal detection so you are alerted if someone tries to disable it.

References & Learning Resources

These are the primary sources worth reading in full. Manufacturer datasheets always outrank forum posts when the two disagree.

  1. GPS tracking — principlesReference
  2. GeofencingReference
  3. NEO-6M GPS module (datasheet)u-blox
  4. LTE-M / NB-IoT low-power cellularReference
  5. Haversine distance formulaReference