13.21 Phone control over Wi-Fi
A web page on the phone drives the car. One pad steers, the other is the throttle, and the battery voltage comes back to the page twice a second. The ESP32 runs its own Wi-Fi network and serves the page itself, so nothing is installed on the phone.
From the moment the access point is up, anyone with the password can drive the car. Make every first run with the wheels off the ground, keep the main switch within reach, and change the default password before the car leaves the bench.
The Guide
Every part of the car is built and tested in a chapter of its own before this guide starts:
| Part | Set up in |
|---|---|
| Main switch and XT60, optional fuse | LiPo batteries |
| Buck converter at 7.0 V | Buck converters |
| Steering servo, calibrated | Hobby servos |
| BTS7960 and motor | BTS7960 |
| Battery divider on GPIO 34, calibrated | Battery sensing |
Figure 13.21.1 and Table 13.21.1 collect them in one picture. Check every connection before the first upload. Two parts are optional and left out of the picture: a 20 A fuse between the XT60 and the main switch, and a 100 nF capacitor from the divider midpoint to GND next to the ESP32, which steadies the battery reading.
| From | To | Wire |
|---|---|---|
Battery + (XT60) |
main switch (after the optional fuse), then IBT-2 B+ and buck IN+ |
AWG 16 |
Battery − (XT60) |
IBT-2 B− and buck IN− |
AWG 16 |
IBT-2 M+, M− |
motor | AWG 16 |
IBT-2 RPWM, LPWM |
GPIO 16, GPIO 17 | AWG 22 |
IBT-2 R_EN and L_EN, joined |
GPIO 19, and 10 kΩ to GND, which holds them low while the ESP32 starts | AWG 22 |
IBT-2 VCC, GND |
ESP32 3V3, GND |
AWG 22 |
IBT-2 R_IS, L_IS |
not connected | |
| Rail after the switch | R1 = 33 kΩ to the midpoint, R2 = 10 kΩ on to B− |
AWG 22 |
| Divider midpoint | GPIO 34 (optional 100 nF to GND next to the ESP32) | AWG 22 |
Buck OUT+ (7.0 V) |
servo red, ESP32 VIN, 470 µF + |
AWG 16 to the servo |
Buck OUT− |
servo brown, ESP32 GND, 470 µF − (stripe) |
AWG 16 to the servo |
| GPIO 13 | servo signal (orange) | AWG 22 |
Flash the finished car program from Chrome or Edge, without PlatformIO. The page asks for the car number and names the Wi-Fi network after it, RC-Car-07 for car 7. It uses the book’s uncalibrated steering end points and battery numbers, so it tests the wiring before our own build with the calibrated servo.h and battery.h.
Step 1: Create the project
Create a PlatformIO project named car as in the PlatformIO chapter. The finished project is in code/car next to this chapter, with six source files in src/:
| File | What main.cpp uses |
From |
|---|---|---|
servo.h |
servoBegin(), steer(percent) |
Hobby servos |
motor.h |
motorBegin(), throttle(percent), motorMode, currentDuty |
BTS7960 |
battery.h |
batteryBegin(), batteryUpdate(), battState, batteryMv() |
Battery sensing |
web.h, web_page.h |
webBegin(), phoneConnected(), phoneSteer, phoneThrottle, webSend() |
this chapter |
main.cpp |
this chapter |
Copy the three module files unchanged from their own projects; servo.h already carries its calibrated end points and battery.h its calibration. The new files are in The code.
Step 2: Write platformio.ini and name the car
Replace platformio.ini with the file below, the plain file of the PlatformIO chapter with two libraries added: the asynchronous web server and the TCP layer under it, both maintained by the ESP32Async organisation.
[env:esp32dev]
platform = espressif32@8.0.0
board = esp32dev
framework = arduino
upload_speed = 921600
monitor_speed = 115200
lib_deps =
ESP32Async/ESPAsyncWebServer@^3.6.0
ESP32Async/AsyncTCP@^3.3.0PlatformIO downloads them on the first build; with the versions above, the project builds with ESPAsyncWebServer 3.12.1 and AsyncTCP 3.5.0, the newest matching versions in October 2026.
The car’s network is set in the first lines of web.h: wifiName, wifiPassword and wifiChannel. With twenty cars in a room, each needs its own wifiName, for example the group number as in RC-Car-07. The password must have at least 8 characters, or the access point does not start.
Step 3: Build and upload
Switch the car off and connect the ESP32 by USB only (see USB and VIN at the same time). Build and upload as in the PlatformIO chapter, holding BOOT while the uploader connects. Open the serial monitor and press EN. The car prints
Wi-Fi "RC-Car-07", open http://192.168.4.1/
Step 4: Connect the phone
In the phone’s Wi-Fi settings, join the car’s network with the password from web.h. The phone may warn that the network has no internet access; stay connected. Open http://192.168.4.1 in the browser with http:// written out, since some browsers try https:// first and the car does not answer it. The page (Figure 13.21.2) shows two thumbsticks and connecting ..., replaced by the battery voltage within half a second. On USB only, the voltage reads near zero and the state CUTOFF, because the divider sees no battery. The serial monitor prints phone 1 connected.
web_page.h: the battery line and the motor state on top, the steering pad on the left and the throttle pad on the right.This is the real page, run against a simulated car with made-up numbers: drag the pads with the mouse or a finger, and the grey line shows the message the page sends.
If the page does not load, turn off mobile data and try again; some phones send traffic over the mobile network when the Wi-Fi network has no internet.
Step 5: Drive with the wheels off the ground
Unplug the USB cable. Put the car on a box so that the driven wheels hang free, and turn on the main switch. The ESP32 now runs from the buck converter; reconnect the phone if it lost the network and reload the page. The battery voltage should now agree with a multimeter on the rail within about 0.1 V, and the state reads OK.
Slide a thumb sideways on the left pad and the front wheels follow. Slide up on the right pad and the wheels turn forward while the page shows DRIVE, its duty rising to the pad position over half a second. Lift the thumb and the pad returns to the middle; the motor coasts. Pull down while the wheels turn forward and the state becomes BRAKE; release, wait half a second and pull down again for DRIVE with a negative duty. This is the throttle logic of the BTS7960 chapter, unchanged.
Now test the failsafe. Hold the throttle at a quarter and, with the other hand, turn off Wi-Fi on the phone (or lock the screen). Within half a second the motor coasts and the steering returns to the centre. Turn Wi-Fi back on and reload the page: the car responds again. Do not drive on the floor before this test has passed.
Step 6: Drive on the floor
Put the car on the floor in an open space and start slowly. Indoors the range is some tens of metres, less through walls; the link turns jerky before it fails, and the failsafe stops the car when it does. Watch the battery line on the page: below 9.9 V it turns yellow (WARN) and the throttle is halved, and once it has stayed below 9.6 V for one second it turns red (CUTOFF) and the motor coasts to a stop.
After a CUTOFF, bring the car back by hand, switch it off at the main switch, unplug the pack and charge it as in Charging. Switching the car off and on again clears the cutoff but not the empty pack: the voltage recovers at rest and falls below 9.6 V again at the next start.
Troubleshooting
The network does not appear on the phone
Check the serial monitor. softAP failed means the password is shorter than 8 characters. If the ESP32 restarts over and over with Brownout detector was triggered, its supply is too weak; see Brown-out.
The page loads but shows no link
The WebSocket did not connect or was closed. Reload the page. If two phones are connected, close the page on the one that does not drive.
The car stutters or stops every few seconds while driving
The link drops messages for longer than linkTimeoutMs. Stay closer, or move the car to another Wi-Fi channel (wifiChannel 6 or 11) if many cars in the room share channel 1.
The car stops when the motor starts, and the page loses the link
The ESP32 restarted. See Brown-out.
The wheels steer left when the pad says right
The end points in servo.h belong to another linkage or are swapped. Find them again on the car as in Calibrating the steering.
Throttle up drives the car backwards
The motor is connected the other way round. Switch the car off and swap the two motor wires at M+ and M− of the IBT-2 (Wire the power side).
How It Works
In Figure 13.21.3, loop() in main.cpp reads the pad positions that web.h received, applies the battery state and the failsafe, and hands steering to servo.h and throttle to motor.h. It passes the battery and motor values back to webSend() for the phone.
Access point and station
A Wi-Fi device is either a station, joining an existing network, or an access point, the network itself: a phone at home is a station and the home router the access point. The ESP32 can be either (Figure 13.21.4). As a station it would join the school network, and the phone would have to find the address the car got from the router. Guest networks often block traffic between devices, and then the phone never reaches the car.
As an access point (WiFi.mode(WIFI_AP) and WiFi.softAP(...)), the ESP32 takes the address 192.168.4.1 and hands out 192.168.4.2 and up to the phones that join, so every car has the same address every day. The Arduino core allows four phones at a time by default. In exchange, a phone connected to the car has no internet over Wi-Fi.
HTTP and WebSocket
The browser fetches the page with an ordinary HTTP request: it opens a TCP connection to port 80, sends GET /, receives the page, and the connection ends (Figure 13.21.5). Twenty pad positions a second that way would mean twenty connections, each with a few hundred bytes of headers, and the car could never send anything it had not been asked for.
A WebSocket starts as an HTTP request to /ws that asks the server to upgrade the connection. The TCP connection then stays open, and either end may send short messages at any time, so the car pushes telemetry without being asked. A pad message such as -35,80 travels as 12 bytes. TCP still delivers every message in order and resends lost packets: a lost message arrives late instead of not at all, and the newer messages wait behind it. On a bad link this shows up as a stutter, and the failsafe below keeps the car safe through it.
The message format
The phone sends one text message every 50 ms, two integers separated by a comma, s,t: the steering and the throttle, both from \(-100\) to \(100\) in percent of full travel. Positive steering is to the right, positive throttle forward; 0,0 is the pads at rest and -35,80 is 35 % left and 80 % throttle. steer() and throttle() take the same range. The phone sends the message even when nothing has changed, so silence means a lost link.
The car answers every 500 ms with one JSON object to every connected phone, as in Figure 13.21.5. mV is the filtered battery voltage in millivolts, batt the battery state (OK, WARN or CUTOFF), motor the state of the bridge (COAST, DRIVE or BRAKE) and duty the signed duty from \(-255\) to \(255\). The browser decodes it with one call (JSON.parse), and a field added later does not break the page.
On the car, onWsEvent() copies the received bytes into a 16-character buffer, ends the text with a zero inside that buffer, and reads the two numbers with sscanf. A longer message cannot be ours and is ignored; values outside \(-100\) to \(100\) are clamped. The library hands over only a pointer and a length, so writing the zero at data[len] would land one byte past its buffer.
Who runs when
On the ESP32 the Wi-Fi driver runs on core 0, and the AsyncTCP library runs a separate task that calls onWsEvent() whenever a message arrives; it stores the command and its arrival time and returns without touching the motor or the servo. The Arduino loop() runs on core 1 and does everything else, most of it in a control step every 20 ms. Figure 13.21.6 shows what happens when the phone goes quiet.
phoneConnected() turns false 500 ms later, and the next control step, at 710 ms, coasts the motor and centres the steering.
The car reacts at most linkTimeoutMs plus one control step after the last message, \(500 + 20 = 520\) ms; at 3 m/s it rolls 1.6 m in that time and then coasts. A shorter timeout would stop the car on every hiccup of the link, since at 500 ms ten messages in a row must be lost first. A longer one would let the car run further without a driver.
The network task writes the command and loop() reads it, possibly at the same instant on two cores, so the shared variables in web.h are volatile: the compiler reads them from memory every time instead of keeping an old copy. Each is one 32-bit word, written and read whole, so loop() never sees half a number. At worst it pairs the steering of one message with the throttle of the next, which a thumb on a pad never notices.
The control step also paces the other modules: the servo gets one new pulse width per 20 ms frame, and the soft start of BTS7960 counts in these steps. batteryUpdate() runs in every pass of loop() and reads every 10 ms, so its filter keeps the time constant of Filtering the readings.
Failsafe and priorities
loop() weighs three sources in a fixed order, in the five lines under // Priorities in main.cpp. Figure 13.21.7 draws them, with the battery states that battery.h reports.
loop() changes the phone’s steering \(s\) and throttle \(t\) before steer() and throttle(). Bottom: the battery states of battery.h with their thresholds.
phoneConnected() is false when no message has arrived for linkTimeoutMs or when the driving phone has closed the connection, and the failsafe then sets steering and throttle to zero. The battery state is applied last and wins over both: in CUTOFF the throttle is zero whatever the phone sends, and in WARN it is halved so that the driver notices and drives home. Zero throttle into throttle() means coast, so after a lost link or with an empty battery the car rolls out freely. A brake would stop it shorter, but a car braking hard at full speed can skid, and on a lost link nobody is steering. Steering is centred on a lost link so that the car rolls out straight, but kept under CUTOFF so that the driver can steer the coasting car away from an obstacle.
Only one phone drives. The first to send becomes the driver, and another phone takes over only after the driver has been silent for linkTimeoutMs, so a second phone in the room cannot snatch the car from a driver who is still steering. Both receive the telemetry.
Wi-Fi and the analog inputs
The Wi-Fi driver uses the second analog-to-digital converter, ADC2, so every analog input of the car sits on an ADC1 pin, here the divider on GPIO 34 (Which pins can read).
Brown-out when the motor starts
A motor started from standstill draws its stall current and can pull a nearly empty pack below the 7.3 V the buck converter needs to hold 7.0 V (When the input sags: dropout). The ESP32 then resets with Brownout detector was triggered, as in Stall current and the supply. The radio adds bursts of about 240 mA while it transmits, so a supply that held during the BTS7960 tests can fail once the access point runs. The soft start is the main protection; short, thick battery wires, a charged pack and the bulk capacitor at the servo do the rest.
After a reset, motorBegin() puts the bridge in coast before anything else, the servo is centred, and nothing drives until a phone has reconnected and sends a message. A restart also clears the cutoff latch, so a car that browned out on a nearly empty pack may come back with the state OK; the next hard start ends in CUTOFF again after one second below the threshold.
One chapter per module
main.cpp contains no pin numbers, no PWM setup, no ADC code and nothing about Wi-Fi. It includes the four module files of the Step 1 table and calls them in the right order. The three earlier files were each tested on the bench in their own chapter and copied here unchanged, so a fault in the car can be traced back to the test project of the file that misbehaves. No module knows another: web.h gets the battery and motor values as arguments of webSend(), so it would work unchanged in a car without a battery monitor. The servo and the motor share the LEDC peripheral without disturbing each other, as in Generating the pulse with LEDC.
The headers define their variables and functions themselves. That works because main.cpp is the only source file that includes them; a second .cpp file including the same header would define everything again, and the linker would stop with a multiple definition error.
The code
main.cpp starts the modules and runs the loop described above.
// main.cpp: the RC car, driven from a phone over Wi-Fi. Each file has its chapter:
// servo.h (Servo), motor.h (BTS7960), battery.h (Battery sensing), web.h (Phone control).
#include <Arduino.h>
#include "servo.h"
#include "motor.h"
#include "battery.h"
#include "web.h"
unsigned long lastStepMs = 0;
unsigned long lastSendMs = 0;
void setup() {
Serial.begin(115200);
motorBegin(); // the bridge in coast before anything else
servoBegin(); // steering straight ahead
batteryBegin();
webBegin();
}
void loop() {
batteryUpdate();
// One control step every 20 ms
if (millis() - lastStepMs < 20) return;
lastStepMs = millis();
// Priorities: the battery first, then the link, then the phone
int steering = phoneSteer;
int percent = phoneThrottle;
if (!phoneConnected()) { steering = 0; percent = 0; } // lost link: straight, coast
if (battState == BATT_WARN) percent = percent / 2; // half power on a low battery
if (battState == BATT_CUTOFF) percent = 0;
steer(steering);
throttle(percent);
// Telemetry to the phone twice a second
if (millis() - lastSendMs >= 500) {
lastSendMs = millis();
webSend(batteryMv(), battStateName[battState], motorMode, currentDuty);
}
}web.h starts the access point, serves the page, receives the pad messages and sends the telemetry.
// web.h: the car's own Wi-Fi network, the web page and the WebSocket to the phone.
#pragma once
#include <Arduino.h>
#include <WiFi.h>
#include <AsyncTCP.h>
#include <ESPAsyncWebServer.h>
#include "web_page.h"
// Give every car its own network name
const char* wifiName = "RC-Car-01";
const char* wifiPassword = "mekatronik"; // at least 8 characters
const int wifiChannel = 1;
const unsigned long linkTimeoutMs = 500; // no message for this long: the link is lost
AsyncWebServer server(80);
AsyncWebSocket ws("/ws");
// Written by the WebSocket callback in the network task, read by loop(). Each is one
// 32-bit word, written and read whole; volatile makes loop() read it afresh every time.
volatile int phoneSteer = 0; // -100 (left) .. 100 (right)
volatile int phoneThrottle = 0; // -100 (reverse) .. 100 (forward)
volatile unsigned long lastMsgMs = 0;
volatile uint32_t driverId = 0; // the phone that drives; 0 = none
void onWsEvent(AsyncWebSocket* server, AsyncWebSocketClient* client, AwsEventType type,
void* arg, uint8_t* data, size_t len) {
if (type == WS_EVT_CONNECT) Serial.printf("phone %d connected\n", (int)client->id());
if (type == WS_EVT_DISCONNECT && client->id() == driverId) driverId = 0; // link lost at once
if (type != WS_EVT_DATA) return;
// The message is the text "steer,throttle", for example "-35,80"
char text[16];
if (len >= sizeof(text)) return; // too long to be ours
memcpy(text, data, len);
text[len] = '\0';
int s, t;
if (sscanf(text, "%d,%d", &s, &t) != 2) return;
// The first phone that sends drives. Another takes over only after it has gone silent.
if (driverId != 0 && client->id() != driverId && millis() - lastMsgMs < linkTimeoutMs) return;
driverId = client->id();
phoneSteer = constrain(s, -100, 100);
phoneThrottle = constrain(t, -100, 100);
lastMsgMs = millis();
}
void webBegin() {
WiFi.mode(WIFI_AP);
if (!WiFi.softAP(wifiName, wifiPassword, wifiChannel))
Serial.println("softAP failed (password shorter than 8 characters?)");
Serial.printf("Wi-Fi \"%s\", open http://%s/\n", wifiName, WiFi.softAPIP().toString().c_str());
ws.onEvent(onWsEvent);
server.addHandler(&ws);
server.on("/", HTTP_GET, [](AsyncWebServerRequest* request) {
request->send(200, "text/html", WEB_PAGE);
});
server.begin();
}
// True while a phone drives: its last message is less than linkTimeoutMs old
bool phoneConnected() { return driverId != 0 && millis() - lastMsgMs < linkTimeoutMs; }
// Send the battery and motor state to every connected phone
void webSend(int mV, const char* batt, const char* motor, int duty) {
ws.cleanupClients(); // forget phones that left without closing
char json[96];
snprintf(json, sizeof(json), "{\"mV\":%d,\"batt\":\"%s\",\"motor\":\"%s\",\"duty\":%d}",
mV, batt, motor, duty);
ws.textAll(json);
}web_page.h holds the page as one C++ raw string literal, so the quotes of HTML and JavaScript need no escaping. Its script sends the two pad positions as s,t every 50 ms while the socket is open, sets a pad back to zero when the finger lifts, and writes each telemetry object into the line at the top; it loads no external file, since a phone connected to the car has no internet.
web_page.h, the page on the phone
// web_page.h: the phone page, HTML + CSS + JavaScript in one raw string.
// The ESP32 sends it unchanged to every browser that opens http://192.168.4.1/.
//
// Up the WebSocket (every 50 ms while connected): "s,t" as text, two integers
// from -100 to 100, e.g. "-35,80" = 35 % left, 80 % throttle.
// Down the WebSocket (every 500 ms): one JSON object, see webSend() in web.h.
#pragma once
static const char WEB_PAGE[] = R"page(<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">
<title>RC car</title>
<style>
body { margin: 0; padding: 12px; font-family: sans-serif; text-align: center;
background: #222; color: #eee; user-select: none; -webkit-user-select: none; }
#telem { font-size: 1.1em; line-height: 1.6; }
.bad { color: #f55; } .warn { color: #fc3; } .ok { color: #6d6; }
.pads { display: flex; justify-content: space-around; margin-top: 16px; }
/* base: a dark bowl in a lighter bezel, lit from the top left */
.pad { position: relative; width: 40vmin; height: 40vmin; border-radius: 50%;
touch-action: none; box-sizing: border-box; border: 1.8vmin solid transparent;
background: radial-gradient(circle at 50% 40%, #2c2c2c, #151515 70%, #0b0b0b) padding-box,
linear-gradient(160deg, #6a6a6a, #2a2a2a 50%, #3c3c3c) border-box;
box-shadow: inset 0 1.5vmin 3vmin #000, 0 0.4vmin 0 #555, 0 1.5vmin 3vmin #000a; }
/* the slot the stick moves in: horizontal for steering, vertical for throttle */
.pad::before { content: ''; position: absolute; border-radius: 3vmin; background: #050505;
box-shadow: inset 0 0.6vmin 1vmin #000, 0 0.3vmin 0 #ffffff14; }
#steer::before { left: 12%; right: 12%; top: 44%; height: 12%; }
#throttle::before { top: 12%; bottom: 12%; left: 44%; width: 12%; }
/* cap: a dome lit from the top left; its shadow trails towards the centre as the stick
leans, like the stem under a tilted cap (--x, --y from show()) */
.knob { position: absolute; left: 35%; top: 35%; width: 30%; height: 30%;
border-radius: 50%; pointer-events: none; --x: 0; --y: 0;
background: radial-gradient(circle at 38% 30%, #cfe6ff 0, #6af 22%, #2a63b8 62%, #12305e 100%);
box-shadow: calc(var(--x) * 2vmin) calc(1.4vmin + var(--y) * 2vmin) 1.8vmin #000d,
inset 0 -0.8vmin 1.2vmin #0008, inset 0 0.4vmin 0.5vmin #fff6; }
/* the concave thumb rest in the middle of the dome */
.knob::after { content: ''; position: absolute; inset: 24%; border-radius: 50%;
background: radial-gradient(circle at 60% 70%, #8bc0ff, #3b7bd4 70%);
box-shadow: inset 0 0.5vmin 0.8vmin #0007, 0 0.2vmin 0 #fff5; }
</style>
</head>
<body>
<div id="telem">connecting ...</div>
<div class="pads">
<div class="pad" id="steer"><div class="knob"></div></div>
<div class="pad" id="throttle"><div class="knob"></div></div>
</div>
<p>left: steering right: throttle</p>
<script>
// One pad = one axis. The value is -1..1 while a finger is on the pad and
// returns to 0 when the finger is lifted. Pointer events handle touch and mouse,
// and pointerId keeps two fingers on two pads apart.
function makePad(id, axis) {
const pad = document.getElementById(id), knob = pad.firstElementChild;
let value = 0, finger = null;
function show() {
const r = pad.clientWidth * 0.35 * value;
knob.style.transform = axis === 'x' ? `translateX(${r}px)` : `translateY(${-r}px)`;
knob.style.setProperty(axis === 'x' ? '--x' : '--y', axis === 'x' ? -value : value);
}
function move(e) {
const b = pad.getBoundingClientRect();
const v = axis === 'x' ? (e.clientX - b.left) / b.width * 2 - 1
: 1 - (e.clientY - b.top) / b.height * 2;
value = Math.max(-1, Math.min(1, v));
show();
}
function release(e) {
if (e.pointerId !== finger) return;
finger = null; value = 0; show();
}
pad.addEventListener('pointerdown', e => {
finger = e.pointerId; pad.setPointerCapture(finger); move(e);
});
pad.addEventListener('pointermove', e => { if (e.pointerId === finger) move(e); });
pad.addEventListener('pointerup', release);
pad.addEventListener('pointercancel', release);
return () => value;
}
const steer = makePad('steer', 'x');
const throttle = makePad('throttle', 'y');
const telem = document.getElementById('telem');
let ws;
function connect() {
ws = new WebSocket(`ws://${location.host}/ws`);
ws.onclose = () => { telem.innerHTML = '<span class="bad">no link</span>'; setTimeout(connect, 1000); };
ws.onmessage = e => {
const t = JSON.parse(e.data);
const cls = { OK: 'ok', WARN: 'warn', CUTOFF: 'bad' }[t.batt];
telem.innerHTML = `<span class="${cls}">${(t.mV / 1000).toFixed(2)} V ${t.batt}</span><br>` +
`${t.motor} duty ${Math.round(t.duty * 100 / 255)} %`;
};
}
// Send the stick values every 50 ms, also when nothing changes: the car
// treats silence as a lost link.
setInterval(() => {
if (ws && ws.readyState === WebSocket.OPEN)
ws.send(Math.round(steer() * 100) + ',' + Math.round(throttle() * 100));
}, 50);
connect();
</script>
</body>
</html>
)page";Exercises
Horn button. The car has no horn, but it has the LED on GPIO 2. Add a button to the page that sends the message
hwhen pressed andHwhen released, and letonWsEvent()switch the LED on and off. Keep thes,tmessages working, and make sure a messagehcannot be read as a pad command. What should the LED do on a lost link?Telemetry rate. Change the telemetry interval in
loop()from 500 ms to 100 and to 2000 and drive the car. At which rate does the voltage on the page follow a hard acceleration? With 100 ms, how many bytes per second does the car send to one phone, counting the JSON and a 2-byte frame header? Compare with the bytes per second the phone sends to the car.Link latency. Measure the round trip from the phone to the car and back. Let the page send
pfollowed byperformance.now()every second, the car return the same text at once fromonWsEvent()withclient->text(...), and the page print the difference betweenperformance.now()and the returned value. Record the round trip next to the car and at 10 and 20 m. Half the round trip plus up to one 20 ms control step is the delay from thumb to wheel.Failsafe timing. Predict from Who runs when how long after the last message the car coasts, then measure it. Let
main.cppprintmillis()andlastMsgMs, the time of the last accepted message, wheneverphoneConnected()changes. Stop the messages once by turning off the phone’s Wi-Fi and once by closing the browser tab. Why do the two cases give different times?