Precision agriculture relies on measured field geometry and automated electrical control to place planting rows with centimeter-level consistency instead of relying on manual operator steering and visual estimation.
This project turns an ESP32 microcontroller into a compact, self-contained controller for row-by-row planting. The ESP32 combines built-in Wi-Fi, hardware serial UARTs, non-volatile flash storage, and GPIO pins in a single low-cost board, making it well suited for coordinating high-precision RTK GPS input, a browser-based Soft-AP control dashboard, and high-speed electrical solenoid actuation.
The firmware continuously reads NMEA streams from an RTK receiver over UART, projects the tractor’s position against a configured field baseline (the A-B line), applies speed and antenna offset look-aheads, and fires timed solenoid pulses through GPIO 23 each time the planter advances into the next planting interval lane.
01. System overview & precision agriculture
In traditional mechanical row planting, spacing variations compound across acres, leading to overlapping rows, wasted seed, irregular light distribution, and mechanical interference during later weeding or harvesting passes. By locking onto an RTK Fixed GNSS receiver (providing 1–2 cm positioning accuracy) and establishing two anchoring points at the field edge (Point A and Point B), the tractor can establish an infinite mathematical baseline.
As the tractor traverses the field, the controller computes the perpendicular distance from the current GPS antenna position to the A-B reference line in real time. Whenever that distance steps across the configured interval multiple (e.g., every 0.75 m), the ESP32 energizes the planter’s solenoid mechanism via an optoisolated switch for a precise duration (e.g., 100 ms).
| System Layer | Component | Responsibility |
|---|---|---|
| Positioning | RTK GNSS Receiver | Streams NMEA GGA sentences with fix quality 4 at 115200 baud. |
| Processing | ESP32 Dev Module | UART parsing, local metric projections, vector cross product, and state machine. |
| Persistence | LittleFS Flash | Preserves A-B coordinates and configuration across power cycles as JSON. |
| Operator UI | ESP32 Soft-AP (802.11 b/g/n) | Serves mobile HTML dashboard and /status JSON endpoint over Wi-Fi. |
| Actuation | GPIO 23 → Relay / MOSFET | Fires isolated logic pulses to trigger the planter's 12 V solenoid valves. |
02. System design & firmware architecture
The firmware is built in tractor_gps_controller.ino and leverages modern, battle-tested Arduino
libraries to keep the system modular and non-blocking:
- TinyGPS++: Decodes incoming NMEA 0183 data streams. NMEA is a text-based protocol sending
comma-separated sentences. The firmware binds a custom
TinyGPSCustomextractor to the 6th field of$GPGGAsentences to verify RTK Fixed quality (value4) while reading speed, location, satellites, and HDOP. - WebServer & WiFi Soft-AP: Starts an access point named
Tractor_Planter_GPSon channel 1, allowing the operator to calibrate coordinates and tweak parameters directly from a smartphone browser without internet access. - LittleFS & ArduinoJson 7: Persists the active configuration file
(
/config.json) in flash memory so field coordinates survive battery resets or engine cranks. - HardwareSerial (UART2): Receives raw GPS bytes at 115200 baud on GPIO 16 (RX2) and GPIO 17 (TX2), leaving the default USB UART (UART0) completely dedicated to real-time debug telemetry.
+-----------------------+ UART2 (115200 baud)
| RTK GNSS Receiver | ------------------------------------+
| (NMEA GGA / RMC / VTG)| |
+-----------------------+ v
+-----------------+
+-----------------------+ HTTP / Wi-Fi (Soft-AP) | | GPIO 23 (Active High)
| Smartphone / Tablet | <========================> | ESP32 MCU | -----------------------------> [Optocoupler / MOSFET]
| Browser Dashboard | 192.168.4.1 | - TinyGPS++ | |
+-----------------------+ | - LittleFS | v
| - ArduinoJson | [Planter Solenoid 12V]
+-----------------------+ USB Debug / Monitoring | - WebServer |
| PC / Python Emulator | <------------------------> | |
| (Bench Testing Suite) | 115200 baud +-----------------+
+-----------------------+
03. Build and upload instructions
Open tractor_gps_controller/tractor_gps_controller.ino in the Arduino IDE. Open the Library
Manager and install:
- TinyGPSPlus by Mikal Hart
- ArduinoJson by Benoît Blanchon (version 7.x or later)
In the Tools menu, select ESP32 Dev Module, choose an upload speed of
115200, pick the corresponding serial port (on macOS typically /dev/cu.usbmodem*
or /dev/cu.usbserial*, on Linux /dev/ttyUSB0, on Windows COM3), and click
Upload.
tractor_gps/
├── tractor_gps_controller/
│ └── tractor_gps_controller.ino # ESP32 firmware sketch
├── tools/
│ └── gps_emulator.py # Python GPS NMEA simulator & serial log monitor
├── docs/ # Architecture guides and diagrams
├── index.jpg # Web UI mobile screenshot
├── README.md # Quick start reference
└── POST.md # Full technical design guide
04. Electrical connections & power conditioning
Agricultural tractors present a harsh electrical environment. Starter motor cranking causes severe voltage dips, while alternator load dumps and inductive solenoid collapsing fields can generate voltage spikes exceeding 60–100 V. The tractor 12 V battery must never be connected directly to the ESP32.
The power conditioning front-end uses a 1 A fast-acting fuse, a 1N4007 reverse-polarity protection diode, a 470 μF
electrolytic reservoir capacitor, and a 15 V transient voltage suppression (TVS) diode (such as a 1.5KE15A or 5KP15A).
An efficient step-down buck converter (LM2596 or MP1584) steps the clean 12 V down to a regulated 5.0 V rail feeding
the ESP32 VIN/5V pin and the relay driver logic.
Tractor 12V Battery (+)
│
[1A Inline Fuse]
│
[1N4007 Diode] (Reverse Polarity Protection)
│───────────────────────────────┬───────────────────────────────┐
│ │ │
[470 μF / 35V] [1.5KE15A TVS Diode] [Planter Solenoid (+)]
Electrolytic Capacitor Transient Clamping to GND │
│ │ [Flyback Diode 1N5408]
└───────────────┬───────────────┘ │
│ [MOSFET Drain / Relay NO]
Protected 12V Rail │
│ [GND Common]
[Buck Converter 12V->5V]
(LM2596 / MP1584)
│
┌──────────┴──────────┐
│ 5.0V Regulated │
v v
ESP32 VIN / 5V Opto-Relay VCC
(3.3V Logic on MCU) (Isolated Logic Ground)
GPIO 23 outputs a 3.3 V logic signal. It should drive the input of an optocoupled relay or logic-level N-channel power MOSFET module (such as IRLZ44N or an isolated relay board), never the solenoid coil directly. If driving a bare DC solenoid coil, always place a 1N5408 or 1N4007 flyback diode in reverse bias across the solenoid terminals to snub inductive kickback.
| Component | Recommended Part | Engineering Purpose |
|---|---|---|
| Inline Fuse | 1 A Fast-Blow Blade Fuse | Guards against wiring shorts and catastrophic overcurrent. |
| Series Diode | 1N4007 (1 kV, 1 A) | Blocks negative voltage if tractor battery terminals are reversed. |
| Filter Capacitor | 470 μF / 35 V Low-ESR | Buffers energy during engine cranking and transient brownouts. |
| TVS Diode | 1.5KE15A / 5KP15A | Clamps overvoltage spikes and load-dump transients above 15 V. |
| Buck Converter | LM2596 or MP1584 | Steps down noisy 12–14.4 V tractor power to stable 5.0 V DC. |
| Actuator Switch | Optoisolated MOSFET / Relay | Provides galvanic isolation between MCU 3.3 V logic and 12 V solenoid coil. |
05. Establishing the field baseline (A-B lines)
Before planting begins, the operator records two distinct reference points along the field perimeter:
- Point A: Anchors the origin of the field baseline. The operator drives to the start of
the first planting run and presses Mark Point A. The firmware accepts the coordinates only if
liveFixType == 4(RTK Fixed lock) and valid coordinates are present. - Point B: Anchors the baseline heading. The operator drives to the opposite end of the first row and presses Mark Point B.
Once both points are recorded, lineReady transitions to true, and the firmware persists
all values to /config.json via LittleFS. The operator can tune four runtime parameters via the web UI:
| Parameter | Default | Range | Function |
|---|---|---|---|
interval_m |
0.75 m | 0.10 – 10.0 m | Physical distance between consecutive planting rows/lanes. |
offset_m |
1.25 m | 0.00 – 15.0 m | Distance from the GPS roof antenna to the rear planter drop tube. |
pulse_ms |
100 ms | 10 – 2000 ms | Duration that GPIO 23 remains HIGH to energize the solenoid valve. |
lookahead_s |
0.05 s | 0.00 – 1.00 s | Speed-proportional advance time compensating for valve opening latency. |
06. Position math & perpendicular distance
Because field dimensions span hundreds of meters rather than continental scales, the controller utilizes a local flat-plane projection centered at Point A. This avoids costly spherical trigonometry while preserving sub-centimeter fidelity.
Latitude differences are converted to north-south meters using a constant meridian scale:
LAT_TO_METERS = 111132.95 m/deg. Longitude differences are scaled by the cosine of the current latitude:
// 1. Convert current latitude to longitude-to-meters conversion factor
lonToMeters = cos(currentLat * M_PI / 180.0) * 111319.9;
// 2. Project Point B and Tractor Position relative to Point A (Origin)
xB = (lonB - lonA) * lonToMeters;
yB = (latB - latA) * LAT_TO_METERS;
xP = (currentLon - lonA) * lonToMeters;
yP = (currentLat - latA) * LAT_TO_METERS;
// 3. Calculate baseline vector magnitude |AB|
AB_mag = sqrt((xB * xB) + (yB * yB));
// 4. Compute perpendicular cross-track distance using 2D vector cross-product
perpDistance = fabs(((xP * (-yB)) + (yP * xB)) / AB_mag);
// 5. Apply physical antenna offset and velocity look-ahead compensation
correctedDistance = perpDistance + distanceOffset + (currentSpeedMPS * timeLookahead);
// 6. Compute discrete lane interval index
currentIntervalIndex = floor(correctedDistance / distanceInterval);
The mathematical beauty of the 2D cross-product point-to-line formula is that it calculates the exact perpendicular distance to the infinite line extending through A and B, functioning identically whether the tractor is working to the left or right of the initial baseline.
07. Solenoid timing & non-blocking state machine
Traditional Arduino sketches often use blocking delay() calls, which pause CPU execution and drop
incoming serial GPS bytes or HTTP dashboard requests.
This controller implements a fully non-blocking delta-time state machine using
millis(). When a new interval index crossing is detected (currentIntervalIndex > lastIntervalIndex):
- GPIO 23 is driven
HIGH. pulseActiveis flaggedtrue.pulseEndTime = millis() + pulseTimeis calculated.pulseCountis incremented.
On every pass of the main loop(), the firmware evaluates if (pulseActive && millis() >= pulseEndTime).
When the time expires, GPIO 23 is driven LOW and pulseActive is reset to false.
This allows the ESP32 to concurrently service web clients and decode 10 Hz NMEA streams without jitter.
08. Local web dashboard & real-time telemetry
The ESP32 broadcasts a private Wi-Fi network with SSID Tractor_Planter_GPS and WPA2 passphrase
agri-precision. When the operator navigates to http://192.168.4.1 on their mobile browser,
the controller renders an intuitive dashboard:
For automated diagnostic equipment or headless data loggers, the controller exposes a lightweight JSON telemetry
endpoint at /status:
curl -s http://192.168.4.1/status | jq .
{
"fix_type": "RTK FIXED",
"fix_quality": 4,
"satellites": 14,
"latitude": -33.9998210,
"longitude": 145.0013420,
"speed_mps": 2.22,
"line_ready": true,
"line_a_lat": -34.0000000,
"line_a_lon": 145.0000000,
"line_b_lat": -34.0000000,
"line_b_lon": 145.0020000,
"interval_m": 0.75,
"offset_m": 1.25,
"pulse_ms": 100,
"lookahead_s": 0.050,
"pulse_count": 47,
"pulse_active": false,
"last_fix_age_ms": 120,
"uptime_ms": 342500
}
09. Bench testing with simulated GPS Python harness
Field testing with agricultural machinery is time-consuming and weather-dependent. To make development rapid
and repeatable on the workbench, the repository provides a Python GPS simulator: tools/gps_emulator.py.
The emulator uses pyserial to stream synthetic, fully checksummed NMEA sentences ($GPGGA,
$GPRMC, $GPGSA, $GPVTG) at 10 Hz over a USB-to-TTL UART adapter into ESP32
GPIO 16 (RX2), while an integrated background thread captures and parses the ESP32's native USB debug stream.
pip install pyserial
# macOS Example
python tools/gps_emulator.py \
--gps-port /dev/cu.usbserial-A10KH1TF \
--debug-port /dev/cu.usbmodem-1101 \
--lat -34.000000 --lon 145.000000 \
--speed 8.0 --heading 90.0
# Linux Example
python tools/gps_emulator.py \
--gps-port /dev/ttyUSB0 \
--debug-port /dev/ttyACM0 \
--speed 6.5
# Windows Example
python tools/gps_emulator.py \
--gps-port COM4 \
--debug-port COM5
| CLI Option | Default | Description |
|---|---|---|
--gps-port |
/dev/cu.usbserial-0001 |
Serial port wired to ESP32 GPIO 16 (RX2). |
--debug-port |
/dev/cu.usbmodem-1101 |
ESP32 native USB debug port for monitoring controller logs. |
--baud |
115200 |
UART baud rate (must match firmware configuration). |
--lat |
-34.000000 |
Starting latitude for the simulated tractor path. |
--lon |
145.000000 |
Starting longitude for the simulated tractor path. |
--speed |
8.0 km/h |
Simulated vehicle forward velocity. |
--heading |
90.0 deg |
Simulated compass direction (90.0° = Due East). |
10. Bench-test sequence & in-field workflow
6-Step Bench Validation
- Upload firmware and power the ESP32 via USB.
- Connect laptop/phone to
Tractor_Planter_GPSWi-Fi and openhttp://192.168.4.1. - Configure a wide row interval (e.g.
5.00 m) for easy observation. - Start
gps_emulator.pyand click Mark Point A on the dashboard. - Define Point B along the path with a valid RTK lock.
- Verify terminal logs print
Target crossed! Fired Pulse Index: #and inspect GPIO 23 pulse with an oscilloscope or LED.
5-Step Field Operation
- Drive to the field boundary and confirm dashboard status reads RTK FIXED (Quality 4).
- Mark Point A at the initial furrow entrance.
- Drive along the first swath to the field edge and mark Point B.
- Begin planting passes: the ESP32 automatically pulses the solenoid each time the vehicle crosses into a new lane index.
- Press Reset Field Lines when transitioning to a new field parcel.
11. Control flow & runtime architecture
The control loop balances communication, computation, and output timing across continuous cycles:
- Pass 1 (HTTP Server):
server.handleClient()processes pending operator requests without lag. - Pass 2 (Pulse Watchdog): Checks if a solenoid actuation period has elapsed and restores GPIO 23 to
LOW. - Pass 3 (UART Feed): Reads every byte available from UART2 into TinyGPS++.
- Pass 4 (GGA & Fix Evaluation): When a new position sentence completes with fix quality 4, calculates cross-track distance, applies offset corrections, and triggers a pulse if an interval index step occurred.
12. Step-by-step firmware code walkthrough
The following 17 code blocks detail the complete implementation inside tractor_gps_controller/tractor_gps_controller.ino.
Step 1: Load libraries and define hardware settings
Includes required subsystems: ESP32 Wi-Fi, WebServer, LittleFS flash, ArduinoJson, HardwareSerial, and TinyGPS++. Configures GPIO 23 as solenoid output and sets UART2 pins (GPIO 16 RX, GPIO 17 TX).
#include <WiFi.h>
#include <WebServer.h>
#include <LittleFS.h>
#include <ArduinoJson.h>
#include <HardwareSerial.h>
#include <TinyGPS++.h>
const char* ssid = "Tractor_Planter_GPS";
const char* password = "agri-precision";
WebServer server(80);
TinyGPSPlus gps;
TinyGPSCustom ggaFixQuality(gps, "GPGGA", 6);
const int OUTPUT_PIN = 23;
HardwareSerial GPSSerial(2); // UART2: RX2=GPIO16, TX2=GPIO17
const char* CONFIG_PATH = "/config.json";
const double LAT_TO_METERS = 111132.95;
double distanceInterval = 0.75;
double distanceOffset = 1.25;
int pulseTime = 100;
double timeLookahead = 0.05;
double latA = 0.0, lonA = 0.0;
double latB = 0.0, lonB = 0.0;
bool lineReady = false;
int liveFixType = 0;
double lastLat = 0.0, lastLon = 0.0;
double lastSpeedMPS = 0.0;
int lastSatellites = 0;
unsigned long lastFixMillis = 0;
bool pulseActive = false;
unsigned long pulseEndTime = 0;
long pulseCount = 0;
long lastIntervalIndex = -1;
Step 2: Save the current configuration to LittleFS
Serializes operating parameters and A-B coordinates into JSON format and writes to flash storage.
bool saveConfig() {
JsonDocument doc;
doc["interval_m"] = distanceInterval;
doc["offset_m"] = distanceOffset;
doc["pulse_ms"] = pulseTime;
doc["lookahead_s"] = timeLookahead;
doc["line_a_lat"] = latA;
doc["line_a_lon"] = lonA;
doc["line_b_lat"] = latB;
doc["line_b_lon"] = lonB;
File file = LittleFS.open(CONFIG_PATH, "w");
if (!file) {
Serial.println("Failed to open config file for writing");
return false;
}
bool ok = serializeJson(doc, file) > 0;
file.close();
return ok;
}
Step 3: Restore saved values from flash storage
Parses /config.json at startup using fallback operators (|) for missing or unwritten fields.
void loadConfig() {
if (!LittleFS.exists(CONFIG_PATH)) return;
File file = LittleFS.open(CONFIG_PATH, "r");
if (!file) return;
JsonDocument doc;
DeserializationError error = deserializeJson(doc, file);
file.close();
if (error) {
Serial.println("Failed to parse config file");
return;
}
distanceInterval = doc["interval_m"] | distanceInterval;
distanceOffset = doc["offset_m"] | distanceOffset;
pulseTime = doc["pulse_ms"] | pulseTime;
timeLookahead = doc["lookahead_s"] | timeLookahead;
latA = doc["line_a_lat"] | latA;
lonA = doc["line_a_lon"] | lonA;
latB = doc["line_b_lat"] | latB;
lonB = doc["line_b_lon"] | lonB;
}
Step 4: Build the browser dashboard
Dynamically renders the responsive HTML user interface for operator control over the Soft-AP network.
void handleRoot() {
String fixStr = "NO FIX";
if (liveFixType == 1) fixStr = "GPS 2D/3D";
else if (liveFixType == 2) fixStr = "DGPS";
else if (liveFixType == 4) fixStr = "RTK FIXED (Precision Mode)";
else if (liveFixType == 5) fixStr = "RTK FLOAT";
String html = "<!DOCTYPE html><html><head><meta name='viewport' content='width=device-width, initial-scale=1'>";
html += "<title>ESP32 Planter Control</title><style>body{font-family:sans-serif;padding:20px;background:#f4f4f4;}</style></head><body>";
html += "<h2>Tractor GPS Planter Control</h2>";
html += "<p>GPS Status: <b>" + fixStr + "</b> (Sats: " + String(lastSatellites) + ")</p>";
html += "<p>Line Status: <b>" + String(lineReady ? "READY" : "NOT SET") + "</b></p>";
if (!lineReady) {
html += "<p><a href='/setA'><button>Mark Point A (Current Fix)</button></a></p>";
html += "<p><a href='/setB'><button>Mark Point B (Current Fix)</button></a></p>";
} else {
html += "<p><a href='/resetLines'><button>Reset Field Lines</button></a></p>";
}
html += "<form action='/save' method='POST'>";
html += "<label>Row Interval (m):</label><br><input name='interval' step='0.01' value='" + String(distanceInterval) + "'><br><br>";
html += "<label>Antenna-to-Planter Offset (m):</label><br><input name='dist_offset' step='0.01' value='" + String(distanceOffset) + "'><br><br>";
html += "<label>Solenoid Pulse Time (ms):</label><br><input name='pulse' type='number' value='" + String(pulseTime) + "'><br><br>";
html += "<label>Look-ahead Time (s):</label><br><input name='lookahead' step='0.01' value='" + String(timeLookahead) + "'><br><br>";
html += "<input type='submit' value='Save Parameters'></form></body></html>";
server.send(200, "text/html", html);
}
Step 5: Mark Point A
Locks Point A coordinates when fix quality is 4 (RTK Fixed) and redirects back to dashboard.
void handleSetA() {
if (liveFixType == 4 && gps.location.isValid()) {
latA = gps.location.lat();
lonA = gps.location.lng();
saveConfig();
server.send(200, "text/html", "Point A baseline anchored. <a href='/'>Back</a>");
} else {
server.send(200, "text/html", "Error: Requires RTK Fixed lock (Quality 4). <a href='/'>Back</a>");
}
}
Step 6: Mark Point B and prepare the baseline
Stores Point B, activates lineReady, and resets the interval index tracker to -1.
void handleSetB() {
if (liveFixType == 4 && gps.location.isValid()) {
latB = gps.location.lat();
lonB = gps.location.lng();
saveConfig();
lineReady = (latA != 0.0 && latB != 0.0);
lastIntervalIndex = -1;
server.send(200, "text/html", "Point B anchored. A-B Baseline Ready! <a href='/'>Back</a>");
} else {
server.send(200, "text/html", "Error: Requires RTK Fixed lock (Quality 4). <a href='/'>Back</a>");
}
}
Step 7: Reset the field line
Clears both baseline coordinates and persists the zeroed state to LittleFS.
void handleResetLines() {
latA = 0.0; lonA = 0.0;
latB = 0.0; lonB = 0.0;
saveConfig();
lineReady = false;
lastIntervalIndex = -1;
server.send(200, "text/html", "Field Lines Reset. <a href='/'>Back</a>");
}
Step 8: Accept parameter changes from HTML form
Handles HTTP POST requests to /save, updates in-memory variables, and saves to flash.
void handleSave() {
if (server.hasArg("interval"))
distanceInterval = server.arg("interval").toDouble();
if (server.hasArg("dist_offset"))
distanceOffset = server.arg("dist_offset").toDouble();
if (server.hasArg("pulse"))
pulseTime = server.arg("pulse").toInt();
if (server.hasArg("lookahead"))
timeLookahead = server.arg("lookahead").toDouble();
saveConfig();
server.sendHeader("Location", "/");
server.send(303);
}
Step 9: Initialize the controller in setup()
Initializes UART ports, GPIO 23 output pin, LittleFS partition, Wi-Fi Soft-AP, and HTTP routes.
void setup() {
Serial.begin(115200);
GPSSerial.begin(115200, SERIAL_8N1, 16, 17);
pinMode(OUTPUT_PIN, OUTPUT);
digitalWrite(OUTPUT_PIN, LOW);
if (!LittleFS.begin(true)) {
Serial.println("LittleFS Mount Failed");
}
loadConfig();
lineReady = (latA != 0.0 && latB != 0.0);
WiFi.softAP(ssid, password);
Serial.print("Soft-AP IP Address: ");
Serial.println(WiFi.softAPIP());
server.on("/", HTTP_GET, handleRoot);
server.on("/save", HTTP_POST, handleSave);
server.on("/setA", HTTP_GET, handleSetA);
server.on("/setB", HTTP_GET, handleSetB);
server.on("/resetLines", HTTP_GET, handleResetLines);
server.on("/status", HTTP_GET, handleStatus);
server.begin();
Serial.println("HTTP server started");
}
Step 10: Service requests and expire pulses
Non-blocking watchdog checking client requests and turning off GPIO 23 when the active pulse duration ends.
void loop() {
server.handleClient();
if (pulseActive && millis() >= pulseEndTime) {
digitalWrite(OUTPUT_PIN, LOW);
pulseActive = false;
}
// (GPS parsing continues below)
}
Step 11: Feed bytes into TinyGPS++
Transfers available UART2 bytes into TinyGPS++ and extracts custom GGA fix quality indicator.
while (GPSSerial.available()) {
gps.encode(GPSSerial.read());
}
if (ggaFixQuality.isUpdated()) {
liveFixType = atoi(ggaFixQuality.value());
}
Step 12: Record the latest valid GPS fix
Updates live telemetry variables and returns early if fix is not RTK Fixed or baseline is not ready.
if (gps.location.isUpdated() && gps.location.isValid()) {
lastLat = gps.location.lat();
lastLon = gps.location.lng();
lastSpeedMPS = gps.speed.mps();
lastSatellites = gps.satellites.value();
lastFixMillis = millis();
if (liveFixType != 4 || !lineReady) return;
// (Proceed to metric distance calculation)
}
Step 13: Convert baseline and tractor position to meters
Computes latitude-dependent longitude scaling and sets Point A as the local cartesian origin.
double currentLat = lastLat;
double currentLon = lastLon;
double currentSpeedMPS = lastSpeedMPS;
double lonToMeters = cos(currentLat * M_PI / 180.0) * 111319.9;
double xB = (lonB - lonA) * lonToMeters;
double yB = (latB - latA) * LAT_TO_METERS;
double xP = (currentLon - lonA) * lonToMeters;
double yP = (currentLat - latA) * LAT_TO_METERS;
Step 14: Calculate perpendicular distance to the A-B line
Calculates baseline vector magnitude and applies 2D cross-product point-to-line formula.
double AB_mag = sqrt((xB * xB) + (yB * yB));
if (AB_mag < 0.1) return;
double perpDistance = ((xP * (-yB)) + (yP * xB)) / AB_mag;
perpDistance = fabs(perpDistance);
Step 15: Apply corrections and identify the interval
Adds antenna offset, applies speed look-ahead, and derives the integer row interval index via floor().
double correctedDistance = perpDistance
+ distanceOffset
+ (currentSpeedMPS * timeLookahead);
long currentIntervalIndex = floor(
correctedDistance / distanceInterval
);
Step 16: Fire a solenoid pulse when the index advances
Detects transition into a new planting interval, energizes GPIO 23, and arms the timer.
if (lastIntervalIndex != -1 &&
currentIntervalIndex > lastIntervalIndex &&
!pulseActive) {
Serial.print("Target crossed! Fired Pulse Index: ");
Serial.println(currentIntervalIndex);
digitalWrite(OUTPUT_PIN, HIGH);
pulseActive = true;
pulseEndTime = millis() + pulseTime;
pulseCount++;
}
lastIntervalIndex = currentIntervalIndex;
Step 17: Report live status over JSON telemetry
Constructs machine-readable JSON status payload at /status for external logging and test runners.
void handleStatus() {
String fixStr = "NO FIX";
if (liveFixType == 1) fixStr = "GPS";
else if (liveFixType == 2) fixStr = "DGPS";
else if (liveFixType == 4) fixStr = "RTK FIXED";
else if (liveFixType == 5) fixStr = "RTK FLOAT";
String json = "{";
json += "\"fix_type\":\"" + fixStr + "\",";
json += "\"fix_quality\":" + String(liveFixType) + ",";
json += "\"satellites\":" + String(lastSatellites) + ",";
json += "\"latitude\":" + String(lastLat, 7) + ",";
json += "\"longitude\":" + String(lastLon, 7) + ",";
json += "\"speed_mps\":" + String(lastSpeedMPS, 2) + ",";
json += "\"line_ready\":" + String(lineReady ? "true" : "false") + ",";
json += "\"line_a_lat\":" + String(latA, 7) + ",";
json += "\"line_a_lon\":" + String(lonA, 7) + ",";
json += "\"line_b_lat\":" + String(latB, 7) + ",";
json += "\"line_b_lon\":" + String(lonB, 7) + ",";
json += "\"interval_m\":" + String(distanceInterval, 2) + ",";
json += "\"offset_m\":" + String(distanceOffset, 2) + ",";
json += "\"pulse_ms\":" + String(pulseTime) + ",";
json += "\"lookahead_s\":" + String(timeLookahead, 3) + ",";
json += "\"pulse_count\":" + String(pulseCount) + ",";
json += "\"pulse_active\":" + String(pulseActive ? "true" : "false") + ",";
json += "\"last_fix_age_ms\":" + String(lastFixMillis > 0 ? millis() - lastFixMillis : 0) + ",";
json += "\"uptime_ms\":" + String(millis());
json += "}";
server.send(200, "application/json", json);
}
13. Achieved goals & system capabilities
The completed project delivers a fully autonomous control path from satellite receiver to agricultural planter:
- High-Rate RTK Reception: Ingests 10 Hz NMEA data over hardware UART2 at 115200 baud.
- Centimeter Enforcement: Rejects baseline calibration and actuator pulses unless an RTK Fixed lock (quality 4) is verified.
- Non-Volatile Persistence: Stores field coordinates and tuning parameters in LittleFS flash using structured JSON.
- Real-Time Metric Projections: Accurately converts spherical WGS-84 coordinates into local metric Cartesian vectors.
- Kinematic Compensation: Adjusts for antenna mounting offset and valve actuation latency proportional to vehicle speed.
- Non-Blocking Actuation: Manages microsecond-precise solenoid pulses on GPIO 23 concurrently with WebServer requests.
- Embedded Web Dashboard: Provides a responsive Soft-AP browser interface and JSON telemetry endpoint at
192.168.4.1. - Automated Test Harness: Exercises all positioning and pulse logic via a repeatable Python serial emulator suite.
14. Technical references & datasheets
Hardware & Arduino Core
-
Arduino-ESP32 Core Documentation
Official Espressif board package and peripheral APIs.
-
ESP32 Wi-Fi Soft-AP API
Local standalone access point network configuration.
-
ESP32 HardwareSerial UART
Hardware UART pin mapping and high-baud data reception.
GPS & Data Protocols
-
TinyGPSPlus Library
C++ NMEA 0183 object-oriented parser for Arduino.
-
ArduinoJson 7 Documentation
Efficient JSON serialization and deserialization in flash.
-
PySerial Documentation
Python serial communications library used for the bench emulator.
15. License & GitHub repository
The project is released under the MIT License. You are free to fork, adapt, and deploy the controller on your own agricultural machinery.
Explore the Source Code on GitHub
Clone the full repository with the ESP32 firmware sketch and Python GPS testing emulator.
20+ years building industrial SCADA telemetries, microcontrollers, and autonomous AI-driven systems.
About Félix