Siddhant Kumar
Project 080 · Smart City

Public Transit Tracker.

Puts a GPS tracker on each bus and a live-ETA display at each stop, so riders see where their bus actually is and when it will arrive — the single thing that most improves the wait.

Intermediate 12–18 hours 28 min read GPSTransitApp
Jump to source Bill of materials
Public Transit Tracker — reference build illustration MCU VCC · GND · SIG · NC
Difficulty
Intermediate
Build time
12–18 hours
Indicative cost
₹2,000 – ₹4,000 per bus (+ displays)
Platform
ESP32 DevKit V1 (ESP-WROOM-32)
Category
Smart City
Last updated
28 July 2026
Contents — 26 sections

Project Overview

Puts a GPS tracker on each bus and a live-ETA display at each stop, so riders see where their bus actually is and when it will arrive — the single thing that most improves the wait.

The worst part of public transport is not the ride — it is the uncertain wait. Standing at a stop with no idea whether the bus left five minutes ago or is fifteen minutes away is stressful and drives people to other transport. The fix is remarkably effective and simple: show riders where their bus actually is and when it will actually arrive. Real-time arrival information is repeatedly found to be the single improvement that most increases rider satisfaction and even ridership — not because the buses run faster, but because the wait becomes known. This project builds that system: a GPS tracker on each bus and a live-ETA display (and app data) at each stop.

On the vehicle side, a GPS tracker on each bus reports its position (and speed) over cellular or LoRa. On the server side, that live position is combined with the route to compute an ETA for each downstream stop — how long until this bus reaches you — accounting for distance along the route and typical or current travel speed. On the rider side, that ETA is shown on a beacon/display at the stop ("Route 12: 4 min") and in an app/map, so a rider knows whether to hurry, wait, or find another option, and can even watch the bus approach on a map.

The value is entirely in reducing uncertainty. A known wait feels far shorter than an unknown one, riders can use their time instead of anxiously watching the road, and missed buses drop. It also gives the operator a live fleet view for management. The design is honest that ETA is a prediction — traffic, dwell time at stops and incidents make it uncertain, so it must be presented as an estimate that updates, and it improves with better modelling — and that reliable coverage (GPS fix, cellular/LoRa) matters. But as a tracker-plus-ETA system, it delivers the improvement that public-transit riders value most: turning the anxious, uncertain wait at a stop into a known, manageable one.

A GPS navigation satellite in orbit
Live bus tracking and ETAs turn the anxious, uncertain wait at a stop into a known one. 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

  • Tracks each bus's live GPS position and speed
  • Reports position over cellular or LoRa
  • Computes an arrival ETA for each downstream stop
  • Shows live ETA at stop displays and in an app/map
  • Lets riders see where the bus is and when it will arrive
  • Gives the operator a live fleet-management view
  • Presents ETA honestly as an updating estimate

Real-World Applications

SettingHow it is used
Bus arrival informationLive ETAs at stops and in an app to reduce wait uncertainty.
Fleet managementLive vehicle positions for operations and scheduling.
Campus / shuttle servicesTracking and ETAs for shuttles and staff transport.
Paratransit / on-demandLive vehicle location and arrival prediction for riders.

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

Features & Capabilities

  • Per-bus GPS tracking
  • Route-aware ETA computation
  • Stop-side live-ETA displays + app/map
  • Reduced wait uncertainty (the key benefit)
  • Live fleet management
  • Cellular/LoRa reporting
  • Honest ETA as an updating prediction

Difficulty, Time & Required Skills

AttributeValue
Difficulty levelIntermediate
Estimated completion time12–18 hours
Indicative build cost₹2,000 – ₹4,000 per bus (+ displays)
Primary disciplineSmart City
Reference platformESP32 DevKit V1 (ESP-WROOM-32)

Skills you should have (or will pick up)

  • GPS tracking and reporting
  • Route-aware ETA computation
  • Stop-side display and app/map integration
  • Cellular/LoRa telemetry
  • Presenting predictions honestly

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
SX1278 LoRa 433 MHz module (Ra-02)
Never power the radio without an antenna — the PA will destroy itself.
−148 dBm sensitivity, +20 dBm output, up to 10 km line of sight, SF7–SF121₹480
0.96″ SSD1306 OLED display
Static images burn in — invert or scroll the screen periodically.
128 × 64 monochrome, 1.3–3.3 V logic, 100 kHz–400 kHz I²C1₹250
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
GPS module + antenna (on-bus)GPS with a good sky-view antenna on each bus1₹400
Cellular/LoRa modemCellular for wide coverage, or LoRa where a network exists1₹900
Stop display/beacon
Or rely on the app for stops without displays
Display at the stop showing live ETAs1₹2,000
Vehicle power/enclosurePowered from the bus, rugged enclosure1₹300

Estimated total: ₹6,375, 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
SX1278 LoRa 433 MHz module (Ra-02)−148 dBm sensitivity, +20 dBm output, up to 10 km line of sight, SF7–SF123.3 VSPIDatasheet
0.96″ SSD1306 OLED display128 × 64 monochrome, 1.3–3.3 V logic, 100 kHz–400 kHz I²C3.3–5 VI²C (0x3C)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

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.
SX1278 LoRa 433 MHz module (Ra-02)3.3 V120Never power the radio without an antenna — the PA will destroy itself.
0.96″ SSD1306 OLED display3.3–5 V20Static images burn in — invert or scroll the screen periodically.
TP4056 Li-ion charger + DW01 protection4.5–5.5 V in1000Buy the version *with* protection ICs — the bare charger will over-discharge your cell.

Summed typical draw is 3345 mA. With a 1.5× design margin the supply should deliver at least 5100 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
PubSubClient 2.8Lightweight MQTT 3.1.1 client for constrained devices.Library Manager → "PubSubClient" by Nick O'Leary
TinyGPSPlus 1.0.3Streaming NMEA parser producing latitude, longitude, speed and time.Library Manager → "TinyGPSPlus" by Mikal Hart
LoRa (sandeepmistry) 0.8.0SX127x radio configuration, packet TX/RX and callbacks.Library Manager → "LoRa" by Sandeep Mistry
Adafruit SSD1306 + GFX 2.5.xFramebuffer and text/graphics primitives for the OLED.Library Manager → "Adafruit SSD1306"
NTPClient / configTime bundledWall-clock time from an NTP server for timestamping.Bundled (`configTime()` on ESP32)
ArduinoJson 7.xZero-allocation JSON serialisation and parsing.Library Manager → "ArduinoJson" by Benoit Blanchon

Block Diagram

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

Public Transit Tracker — system block diagramFunctional block diagram of the Public Transit Tracker system. On the busGPSposition/speedModemcellular/LoRaServerRoute + positionprogressETAper stopRidersStop displaylive ETAApp/mapwatch it comeOperatorFleet viewlive positionsrightrightnone
Public Transit 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.

Public Transit 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 USBGPS (on-bus)GPIO 16/17Position/speed(NMEA)Cellular/LoRaUART/SPIPosition reportStop displayETA at stopBus power3V3 regSupplyStatus LEDGPIO 2Fix/report
Public Transit Tracker — wiring schematic
PeripheralPeripheral pinController pinSignal
GPS (on-bus)TX/RXGPIO 16/17Position/speed (NMEA)
Cellular/LoRabusUART/SPIPosition report
Stop displayI²C/SPIETA at stop
Bus power+/–3V3 regSupply
Status LEDINGPIO 2Fix/report

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

  • Fit the GPS with a good sky-view antenna on each bus for a reliable fix; power from the bus supply.
  • Report position over cellular (wide coverage) or LoRa (where a network exists) at a sensible rate.
  • Compute ETAs on the server from position + route; drive stop displays and app/map from there.
  • Present ETA as an updating estimate; handle a lost fix/coverage gracefully.
  • Rugged, vehicle-powered enclosure for the on-bus unit.
A city skyline at night
An on-bus GPS tracker reports position; the server computes per-stop ETAs. Photograph sourced from Wikimedia Commons — Smart city.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.

Public Transit Tracker — architecture stackLayered architecture from hardware to user interface. Hardware layerESP32 DevKit V1 (ESP-WROOM-32) · u-blox NEO-6M GPS module + ceramic patchantennaDriver layerwifi · pubsub · tinygps · lorolibApplication logicsampling loop · filtering · thresholds · state machineTransport layerCellular/LoRa → transit server → stops/app · TLS · retry and backoffPresentation layerdashboard · mobile notifications · historical charts
Public Transit Tracker — architecture stack

Working Principle

The insight driving this project is that the biggest pain of public transport is uncertainty at the stop, not the journey time itself, and that resolving that uncertainty is disproportionately valuable. Research on transit consistently finds that real-time arrival information is among the most effective improvements an operator can make — it raises satisfaction and even ridership — because a known wait is psychologically far shorter and less stressful than an unknown one. You do not have to make the buses faster; you have to make the wait predictable. Everything the system does serves that single goal: tell the rider where the bus is and when it will arrive.

The mechanism is a three-part pipeline. On the vehicle, a GPS tracker reports each bus's live position (and speed) over cellular or LoRa. On the server, that position is placed onto the bus's route — matching it to how far along the route the bus is — and an ETA is computed for each downstream stop from the remaining distance and an estimate of travel speed (from current speed, historical travel times for that segment and time of day). On the rider side, that ETA is surfaced where it matters: a display at the stop ("Route 12: 4 min") and an app/map where the rider can watch the bus approach. The tighter and more accurate this loop, the more the wait-uncertainty shrinks.

The honest core of the design is that ETA is a prediction, not a promise. Real travel time is buffeted by traffic, by variable dwell time at each stop (boarding, alighting), by signals and incidents — so any single ETA carries uncertainty, and the right way to present it is as an estimate that continuously updates as new positions arrive, so a rider sees "4 min" become "3 min" as the bus really approaches. A good system communicates this honestly (an updating countdown, not a false-precision guarantee) and improves the prediction with better modelling (segment histories, live traffic, dwell patterns). Over-promising a precise arrival that then slips does more harm than a slightly softer estimate that proves reliable.

Two further points complete the picture. Reliable operation depends on coverage: a good GPS fix (sky-view antenna) and dependable cellular/LoRa reporting, with graceful handling of a lost fix or a coverage gap (fall back to the last known position and a wider ETA rather than showing nothing or something wrong). And the same live position stream gives the operator a real-time fleet view for management — bunching, delays, and schedule adherence become visible. The design is candid about its dependencies and the predictive nature of ETAs, but the value proposition is strong and well-proven: by tracking each bus and turning that into a live, honest, updating arrival estimate at every stop and in the app, it delivers the improvement transit riders value most — converting the anxious, open-ended wait at a bus stop into a known, manageable one.

The maths behind it

Position on route

plainPosition on route
Map the GPS fix to route progress:

  s = distance along the route to the bus
     (nearest-point projection of the fix onto the route)

Gives how far the bus is from each downstream stop.

ETA to a stop

plainETA to a stop
For a downstream stop at route distance s_stop:

  remaining = s_stop − s
  ETA ≈ remaining / v_est + dwell_ahead

v_est from current speed + historical segment speed (time of
day); dwell_ahead = expected stop dwell before the rider.

Updating estimate

plainUpdating estimate
ETA is a prediction, not a promise:
  recompute on each new position; show a countdown that
  updates (4 → 3 → 2 min).
  widen ETA / show "approx" when uncertainty is high or on a
  lost fix (fall back to last-known position).

Program Flowchart

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

Public Transit Tracker — firmware flowchartControl flow through the main program loop. Bus: get GPS fixReport position/speedServer: locate on routeCompute ETA per downstreamstopUpdate stop displays + appRider sees where + when
Public Transit 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. Fit the on-bus tracker

    Install GPS with a sky-view antenna and a cellular/LoRa modem on each bus, powered from the bus, reporting position/speed at a sensible rate.

  2. Set up route matching and ETA

    On the server, match each bus's position to its route and compute per-stop ETAs from remaining distance and estimated travel speed (with dwell).

  3. Surface ETAs to riders and the operator

    Drive stop displays and app/map with live, updating ETAs, and provide a fleet-management view; handle lost fix/coverage gracefully.

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. Track, match and compute ETA

    Report bus position, place it on the route, and compute the ETA to each downstream stop, updating as new positions arrive.

    pythoneta.py
    # Compute per-stop ETA from a bus's live position on its route.
    def route_progress(fix, route):
        # nearest-point projection of the GPS fix onto the route polyline
        return distance_along_route(fix, route)   # metres from route start
    
    def eta_to_stops(bus, route, stops, seg_speed):
        s = route_progress(bus.fix, route)
        v = max(bus.speed, 1.0)                    # current speed (m/s), floored
        etas = {}
        for stop in stops:
            if stop.s <= s:                        # already passed
                continue
            remaining = stop.s - s
            # blend current speed with historical segment speed for robustness
            v_est = 0.5*v + 0.5*seg_speed(stop.segment, now())
            dwell = expected_dwell_before(stop)
            etas[stop.id] = remaining / v_est + dwell   # seconds
        return etas                                # present as UPDATING estimates
    def route_progress(fix, route)Projects the GPS fix onto the route to find how far along the route the bus is — the basis for the remaining distance to each stop.
    v_est = 0.5*v + 0.5*seg_speed(stop.segment, now())The ETA blends the bus's current speed with the historical speed for that segment and time of day, making the estimate more robust than instantaneous speed alone.
    dwell = expected_dwell_before(stop)Expected stop dwell time ahead is added, since boarding/alighting delays are a real part of arrival time.
    return etas # present as UPDATING estimatesThe ETAs are estimates to be shown as an updating countdown, recomputed on each new position — a prediction, not a promise.
  2. Display and handle uncertainty

    Show updating ETAs at stops and in the app, watch the bus on a map, and degrade gracefully (last-known position, wider ETA) on a lost fix or coverage gap.

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.

cpptransit-tracker.ino
/* ═══════════════════════════════════════════════════════════════
   Public Transit Tracker (on-bus) — ESP32 + GPS, cellular/LoRa

   Reports each bus's live position/speed; the server computes per-stop
   ETAs and drives stop displays and the app. The key benefit is
   reducing wait uncertainty — ETA is an updating estimate.
   ══════════════════════════════════════════════════════════════════ */

#include <TinyGPS++.h>

#define GPS_RX 16
#define GPS_TX 17
#define BUS_ID 12
#define ROUTE_ID 12
#define REPORT_MS 5000        // report every 5 s (tune for coverage/cost)

TinyGPSPlus gps; HardwareSerial gpsSer(1);
uint32_t lastReport=0;

void reportPosition(double lat, double lon, double kmh){
  char m[160];
  snprintf(m,sizeof m,
    "{\"bus\":%d,\"route\":%d,\"lat\":%.6f,\"lon\":%.6f,\"kmh\":%.1f}",
    BUS_ID, ROUTE_ID, lat, lon, kmh);
  sendOverModem("transit/bus/position", m);   // cellular/LoRa to server
}

void setup(){
  Serial.begin(115200);
  gpsSer.begin(9600, SERIAL_8N1, GPS_RX, GPS_TX);
}

void loop(){
  while (gpsSer.available()) gps.encode(gpsSer.read());

  if (millis()-lastReport >= REPORT_MS){
    lastReport = millis();
    if (gps.location.isValid() && gps.location.age() < 5000){
      reportPosition(gps.location.lat(), gps.location.lng(),
                     gps.speed.isValid()? gps.speed.kmph() : 0);
    } else {
      // lost fix: report status so the server shows last-known + wider ETA
      sendOverModem("transit/bus/status", "{\"bus\":12,\"fix\":false}");
    }
  }
}
if (gps.location.isValid() && gps.location.age() < 5000)Only a fresh, valid GPS fix is reported, so the server's ETA is based on a real current position.
reportPosition(gps.location.lat(), gps.location.lng(), ... kmph())The bus reports its position and speed, which the server places on the route to compute per-stop ETAs.
sendOverModem("transit/bus/status", "{\"bus\":12,\"fix\":false}")On a lost fix the bus reports its status, so the server can fall back to the last-known position and a wider estimate rather than showing something wrong.
#define REPORT_MS 5000A few-second reporting rate keeps the map and ETAs live while balancing cellular data cost and coverage.

Configuration & Calibration

Configuration steps

  • Configure per-bus GPS/modem and the report rate (coverage/cost).
  • Set up route data and per-stop distances for ETA on the server.
  • Configure the travel-speed/dwell model and lost-fix handling.
  • Configure stop displays and app/map, and the fleet view.

Calibration procedure

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

  1. GPS/coverage

    Verify a reliable fix and reporting across the route; handle known coverage gaps.

  2. ETA model

    Compare predicted ETAs to actual arrivals; tune the segment-speed/dwell model to reduce error.

  3. Presentation

    Confirm the ETA updates smoothly (countdown) and communicates uncertainty when high.

Network Architecture & Connectivity

Public Transit Tracker — network topologyPath taken by telemetry from field node to end user. Edge nodesGatewayCloudClientsOn-bus trackerESP32+GPSFleetall busesCellular / LoRaCarrier/GWto serverMQTT/HTTPSTransit serverposition → ETAStop displaysETAApp/mapriders
Public Transit Tracker — network topology

Communication protocol

Buses report position/speed every few seconds; the server computes per-stop ETAs and pushes them to displays and the app, updating as positions arrive.

Topic / endpointDirectionPayload
transit/bus/positionbus → serverbus, route, lat/lon, speed
transit/stop/<id>/etaserver → display/approute ETAs (updating)
transit/fleet/statusserver → operatorlive fleet positions

Message contract between the device and the broker.

Cloud platform configuration

A transit server matches positions to routes, computes and updates ETAs, drives stop displays and the app/map, and gives the operator a live fleet view.

Dashboard setup

A live map of buses, per-stop ETAs, schedule adherence/bunching, and coverage/fix health.

Mobile app integration

Rider app with live bus map and updating ETAs; notifications for a chosen stop/route.

Security considerations

  • Authenticate bus reports so positions/ETAs are trustworthy.
  • Present ETAs as updating estimates; handle lost fix gracefully.
  • Protect any rider data appropriately.

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
Drive the routePosition reported; bus visible on the map
Check a downstream stopETA shown and counts down as the bus approaches
Hit traffic/dwellETA updates upward honestly, not a false precise time
Lose GPS in a tunnelFalls back to last-known + wider ETA gracefully
Compare ETA to actual arrivalReasonable accuracy; improves with modelling
Operator viewLive fleet positions for management

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

Expected output

Stop displays and the app show live ETAs ("Route 12: 4 min") and the bus on a map; the operator sees live fleet positions.

jsonbus-position.json
{
  "bus": 12,
  "route": 12,
  "lat": 28.61390,
  "lon": 77.20900,
  "kmh": 22.0
}

A live bus position that the server turns into "Route 12: 4 min" at the next stops — turning an anxious, open-ended wait into a known one; a lost fix falls back to last-known position with a wider estimate.

An ESP32 development board with the ESP-WROOM-32 module and USB connector
Stop displays and an app show riders where the bus is and when it will arrive. 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.

Troubleshooting: Common Errors & Fixes

ETA often wrong

Likely cause. Instantaneous speed only / no dwell model

Fix. Blend historical segment speed and time-of-day; add dwell; present as updating estimate

Bus disappears

Likely cause. Lost fix/coverage without fallback

Fix. Fall back to last-known position and a wider ETA; report fix status

Riders distrust ETAs

Likely cause. False-precision that slips

Fix. Show an updating countdown; communicate uncertainty; do not over-promise

Poor fix

Likely cause. Antenna placement

Fix. Sky-view antenna; verify coverage along the route

High data cost

Likely cause. Reporting too often

Fix. Tune the report rate; report on movement; use LoRa where available

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

  • Report position every few seconds (tune for coverage/cost); report on movement.
  • Compute ETAs on the server with a robust speed/dwell model; update on each position.
  • Handle lost fix/coverage gracefully with last-known + wider ETA.
  • Present updating countdowns to build trust.
  • 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

  • Install the on-bus unit safely and powered from the bus without interfering with vehicle systems.
  • ETA is a prediction — present it honestly as an updating estimate, not a guarantee.
  • Handle lost fix/coverage gracefully rather than mislead riders.
  • Protect rider/operator data appropriately.
  • 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

  • Verify GPS fix/coverage and reporting across routes.
  • Tune the ETA model against actual arrivals.
  • Maintain stop displays and app data.
  • Monitor fleet health and coverage gaps.
  • 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.
  • 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 live-traffic and richer dwell modelling for better ETAs.
  • Add GTFS-Realtime feeds for standard app integration.
  • Add occupancy/crowding info.
  • Add predictive bunching alerts for operations.
  • 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

Why is this so valuable if it doesn't make buses faster?

Because the worst part of transit is the uncertain wait, and a known wait feels far shorter and less stressful than an unknown one. Real-time arrival information is repeatedly found to be the single improvement that most raises rider satisfaction — and even ridership.

How is the ETA computed?

The bus's live GPS position is placed on its route to find the remaining distance to each stop, then divided by an estimated travel speed (blending current speed with historical segment speed and time of day) plus expected stop dwell.

How accurate is the ETA?

It is a prediction affected by traffic, dwell and incidents, so it carries uncertainty. It is presented as an updating estimate (a countdown), improves with better modelling, and should communicate uncertainty rather than over-promise.

What happens when the bus loses GPS?

It falls back to the last-known position and a wider estimate, and reports its fix status, so riders see something sensible rather than the bus vanishing or a wrong ETA.

What does the operator get?

A live fleet view — where every bus is, schedule adherence, bunching — useful for real-time management on top of the rider-facing information.

References & Learning Resources

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

  1. Real-time passenger informationReference
  2. Automatic vehicle location (AVL)Reference
  3. GTFS-Realtime feedsReference
  4. Transit ETA predictionReference
  5. Perceived vs actual wait timeReference