I wrote four small apps for the M5Stack CoreS3 that use its Wi-Fi radio as a sensor rather than as a network connection. One notices people moving in a room. One counts your breaths. One turns your hand into swirling colour. One measures the distance between two boards by timing radio waves. None of them use a camera, a microphone or a motion sensor (the CoreS3 SE has none of those anyway), and none of them join a network or need a password.
This post walks through how each one works, with the actual code and the numbers I measured, including what didn't work. A second post covers the other half of my Wi-Fi experiments: what you can learn by only listening.
All four are open source (MIT) and build with PlatformIO:
Why a microcontroller can do this at all
The CoreS3 is an ESP32-S3 at 240 MHz with 16 MB of flash, 8 MB of PSRAM (extra RAM on a separate chip, slower than the built-in 512 KB but much bigger) and a 320 x 240 touch screen. The interesting part is what Espressif's Wi-Fi driver exposes:
- Channel state information (CSI). Since 802.11g, Wi-Fi uses OFDM: each 20 MHz channel is split into 64 narrow sub-carriers (sub-frequencies), and data is sent on many of them side by side. Every frame starts with a known training pattern, and the receiver measures how each sub-carrier arrived compared with how it was sent, so it can undo the distortion. The ESP32-S3 hands you those measurements: 64 complex numbers per frame, each one holding a sub-carrier's strength (amplitude) and timing shift (phase). Everything here uses the amplitude.
-
Raw transmit.
esp_wifi_80211_txsends a frame you built byte by byte. - Fine timing measurement (FTM). A round-trip timing protocol added to Wi-Fi in the 802.11mc revision, which turns radio timing into distance.
CSI is the one that makes sensing possible. A Wi-Fi signal doesn't travel in a straight line: it bounces off walls, furniture and people, and the copies arrive at slightly different times. Each sub-carrier has a different wavelength, so each one adds up those copies differently. Move a body near the path and the pattern across the 64 sub-carriers changes. That's the whole idea behind all three CSI apps. The rest is getting a steady supply of it and deciding which changes matter.
The limits, up front: 2.4 GHz only (the ESP32-S3 has no 5 GHz radio), one antenna, and 20 MHz channels for everything here.
Step 1: get a steady stream of CSI without joining anything
The obvious source is beacons, the "I'm here, this is my network" frames routers send about ten times a second. That looks like ten CSI readings a second for free.
It isn't. Beacons go out in the old 802.11b format at 1 Mbit/s. 802.11b predates OFDM, so its frames have no training pattern across sub-carriers and carry no CSI. Listening to every network around me gave 8 usable readings in 12 seconds. Useless for anything.
The fix was to make the router talk. A probe request is the "are you there?" frame a device sends before joining a network. If you address one to a specific router (rather than broadcasting it), the router acknowledges it straight away. That acknowledgement (ACK) is a tiny frame Wi-Fi sends for every frame addressed to one device, and it's sent in the same family of format as the frame it's acknowledging. So if the probe goes out at an OFDM rate, the ACK comes back at an OFDM rate, and OFDM frames carry CSI. No joining the network (association, in Wi-Fi terms), no password.
This is the frame, built by hand in the radar's hop task (a FreeRTOS task, the ESP32's equivalent of a thread, that moves between channels):
// A probe request addressed to the router, offering only OFDM rates, so its replies
// use the modulation that carries CSI.
memset(f, 0, sizeof f);
f[0] = 0x40; // management frame, subtype probe request
memcpy(f + 4, path[i].bssid, 6); // to: the router
memcpy(f + 10, me, 6); // from: the CoreS3
memcpy(f + 16, path[i].bssid, 6); // BSSID: the router
const uint8_t body[] = {0, 0, 1, 8, 0x8c, 0x12, 0x98, 0x24, 0xb0, 0x48, 0x60, 0x6c};
memcpy(f + 24, body, sizeof body);
while (millis() - hopAt < DWELL_MS) {
esp_wifi_80211_tx(WIFI_IF_STA, f, 24 + sizeof body, true);
vTaskDelay(pdMS_TO_TICKS(POKE_MS));
}
After the 24-byte header, a management frame's body is a list of information elements: an ID byte, a length byte, then that many bytes of data. This body is two of them:
-
0, 0: an empty network name (element 0, length 0). -
1, 8, ...: supported rates (element 1, length 8). Each byte is a rate in units of 500 kbit/s, with the top bit marking a basic rate (one every device on the network must support): 0x8c is 0x0c with the top bit set, 12 x 500 kbit/s = 6 Mbit/s; 0x12 is 9; 0x98 is 12; and so on up to 0x6c at 54. These are all OFDM rates. Leaving out 1, 2, 5.5 and 11 (the 802.11b rates) means the router has no reason to answer in 802.11b.
The transmit rate itself is fixed to 6 Mbit/s OFDM. The radio runs in station mode (WIFI_STA, a client rather than an access point) without connecting to anything, and the rate has to be set while Wi-Fi is stopped:
WiFi.mode(WIFI_STA);
WiFi.disconnect();
esp_wifi_stop(); // the raw frame rate is set while stopped
esp_wifi_config_80211_tx_rate(WIFI_IF_STA, WIFI_PHY_RATE_6M);
esp_wifi_start();
Then CSI is switched on. lltf_en asks for CSI from the legacy long training field (LLTF), the part of the training pattern every OFDM frame has. channel_filter_en = false turns off the driver's smoothing across neighbouring sub-carriers, so each one is reported as measured. Promiscuous mode, where the radio keeps every frame it hears rather than only those addressed to it, is turned on too. One setting matters more than the rest:
wifi_csi_config_t c = {};
c.lltf_en = true;
c.channel_filter_en = false;
c.dump_ack_en = true; // acknowledgements carry CSI too
esp_wifi_set_csi_config(&c);
esp_wifi_set_csi_rx_cb(onCsi, NULL);
esp_wifi_set_csi(true);
wifi_promiscuous_filter_t f = {.filter_mask = WIFI_PROMIS_FILTER_MASK_ALL};
esp_wifi_set_promiscuous_filter(&f);
esp_wifi_set_promiscuous(true);
Without dump_ack_en the ACKs never reach the CSI callback, and you're back to 8 readings in 12 seconds.
The callback turns each frame's 64 complex values into amplitudes and scales them so they always add up to the same total (normalising). The overall level moves around for reasons that have nothing to do with the room: the router's transmit power, and the receiver's automatic gain control, which turns its own amplification up and down to suit the signal. Normalising removes that and keeps only the shape across the sub-carriers:
static void onCsi(void *, wifi_csi_info_t *d) {
int p = current;
if (p < 0 || d->len < 2 * SUB || millis() - hopAt < SETTLE_MS) return;
static const uint8_t zero[6] = {0};
// Acknowledgements carry no sender address; anything else must come from the router.
if (memcmp(d->mac, zero, 6) && memcmp(d->mac, path[p].bssid, 6)) return;
if (d->rx_ctrl.rssi < -80) return; // garbled frames
float amp[SUB], sum = 0;
for (int k = 0; k < SUB; k++) {
float im = d->buf[2 * k], re = d->buf[2 * k + 1];
amp[k] = sqrtf(im * im + re * re);
sum += amp[k];
}
if (sum < 1) return;
for (int k = 0; k < SUB; k++) amp[k] *= SUB / sum;
...
}
Two details matter. An ACK has no sender address field, so the CSI callback sees all zeros for its MAC (hardware) address. That's why zero is accepted alongside the router's BSSID (the router's own address). And anything in the first 15 ms after a channel switch (SETTLE_MS) is ignored, along with frames weaker than -80 dBm (signal strength in decibels relative to a milliwatt: -40 is very close, -90 is barely there).
With a probe every 15 ms, each router gives about 30 to 60 readings a second.
Only do this to routers you own. The cost is small: about 20 to 35 tiny frames a second to each router, a few kilobytes a second and well under 1% of the channel's airtime (the share of time the channel is busy carrying frames). That's my estimate from frame sizes and rates, not a measurement. Being poked does keep a phone's Wi-Fi awake, so a hotspot's battery drains faster than when idle.
Step 2: the radar
The radar uses up to four links at once: in my testing two routers and a phone hotspot. It hops between them, 200 ms on each one's channel, so each router gives a separate path across the room.
The movement score for a path is how much each sub-carrier's amplitude has varied over the last 2 seconds, relative to its level (the coefficient of variation), averaged across the sub-carriers:
for (int k = 0; k < SUB; k++) {
float mean = 0, v = 0;
for (int j = 0; j < m; j++) mean += r[idx[j]][k];
mean /= m;
if (mean < 0.2f) continue; // empty and guard sub-carriers
for (int j = 0; j < m; j++) v += (r[idx[j]][k] - mean) * (r[idx[j]][k] - mean);
tot += sqrtf(v / m) / mean;
used++;
}
return used ? 100 * tot / used : -1;
Not all 64 sub-carriers carry anything. The ones at each edge are left empty as guard bands, so the channel doesn't spill into its neighbours. The one in the middle (the DC sub-carrier, at the channel's centre frequency) is left empty because receivers can't measure it cleanly. Their amplitude sits near zero, so their "variation" is pure noise. Skipping anything with a mean under 0.2 (after normalisation, where the average is 1) drops them.
Each path learns its own still level (its baseline) during a 3-second calibration, then keeps adapting slowly while nothing is happening: each quiet reading moves the baseline 0.5% of the way towards it, 10 times a second. The threshold is half as much again as the baseline, and at least 1.5 above it:
static float threshold(const Path &p) { return p.baseline + fmaxf(1.5f, 0.5f * p.baseline); }
...
else if (m > threshold(p)) p.lastOver = millis();
else p.baseline += 0.005f * (m - p.baseline);
The baseline only moves when the path is quiet, so someone standing in the room for a long time doesn't slowly become "normal". The screen says I see you! for 1.5 seconds after any path goes over.
How well it works
First tests at home on a CoreS3 SE, with two routers and a phone hotspot:
| Situation | Movement score |
|---|---|
| Nothing moving | about 3, steady |
| Hand waved between the CoreS3 and a phone half a metre away | 10 to 20 |
| Standing still, hotspot path | about 2 |
| Walking around the room, hotspot path | peaks over 40 |
The big lesson: where you move matters more than anything else. Movement across the line between the CoreS3 and a router shows clearly. Off to the side it barely registers. One path covers a surprisingly thin slice of the room, which is why the radar uses several. Spread the routers and hotspot around the room and you get much better coverage.
It also has no idea who is moving. In a busy room every person and phone disturbs the paths, so it sees movement most of the time. It's a "someone is here" sensor for an empty room, not a people counter.
Step 3: breathing
Breathing is the same signal with a very different problem. A chest rising and falling a centimetre or so is a much smaller change than a person walking past, and it's slow: 8 to 30 breaths a minute is 0.13 to 0.5 Hz.
The breathing app pokes a single router every 20 ms, then averages whatever CSI arrives into 10 readings a second. It keeps 30 seconds of those (300 rows of 64 values, in PSRAM) and analyses them again once a second.
Keep only breathing speeds
Each sub-carrier's 30 seconds is turned into change from its own average, then band-passed: everything slower or faster than breathing is removed. That's done with a fast Fourier transform (FFT) from Espressif's esp-dsp library. An FFT turns a signal over time into how much of each frequency it contains (its spectrum), split into frequency bins. So: transform, zero every bin outside 0.13 to 0.5 Hz, transform back. Along the way it adds up the power (the squared size of each bin) above 1 Hz and compares it with the power in the breathing band. Breathing is slow; fidgeting and moving are fast. So a lot of power above 1 Hz is the "you're moving" signal:
static float bandPass(const float *x, int n, float *out) {
memset(fftBuf, 0, sizeof fftBuf);
for (int i = 0; i < n; i++) fftBuf[2 * i] = x[i];
dsps_fft2r_fc32(fftBuf, NFFT);
dsps_bit_rev_fc32(fftBuf, NFFT);
int lo = lroundf(LOW_HZ * NFFT / RATE), hi = lroundf(HIGH_HZ * NFFT / RATE);
int fast = lroundf(1.0f * NFFT / RATE);
float band = 0, quick = 0;
for (int b = 0; b < NFFT; b++) {
int f = b <= NFFT / 2 ? b : NFFT - b; // the matching positive frequency
float p = fftBuf[2 * b] * fftBuf[2 * b] + fftBuf[2 * b + 1] * fftBuf[2 * b + 1];
if (f >= lo && f <= hi) band += p;
else {
if (f >= fast) quick += p;
fftBuf[2 * b] = fftBuf[2 * b + 1] = 0;
}
fftBuf[2 * b + 1] = -fftBuf[2 * b + 1]; // inverse = conjugate, forward, conjugate
}
dsps_fft2r_fc32(fftBuf, NFFT);
dsps_bit_rev_fc32(fftBuf, NFFT);
for (int i = 0; i < n; i++) out[i] = fftBuf[2 * i] / NFFT;
return band > 0 ? quick / band : 0;
}
The FFT in esp-dsp (radix-2, meaning it works on lengths that are a power of two) only goes forward, so the inverse is done with the forward one. Flip the sign of the imaginary part of every bin (take the complex conjugate), run the forward FFT again, and divide by the length. The inverse and forward transforms differ only in the sign of the exponent, and conjugating before and after swaps that sign. Strictly the result should be conjugated again at the end, but that only flips the imaginary part, and only the real part is kept. That's the fftBuf[2 * b + 1] = -fftBuf[2 * b + 1] line and the / NFFT. Because of the power-of-two rule, the 300 samples are followed by 212 zeros to make 512 (zero-padding). That doesn't add information, it just gives finer frequency bins: 10 / 512, about 0.02 Hz or 1.2 breaths a minute each.
Count breaths, don't look for a frequency
The obvious approach is to take the biggest bin in the spectrum as the rate. That assumes one steady rhythm, and real breathing speeds up, slows down and has the odd sigh, so over 30 seconds the peak smears out.
So instead it counts breaths in the filtered wave. A breath is a rise above +0.3 standard deviations (a measure of how far the wave typically swings from zero), then a fall below -0.3, with at least 1.7 seconds between breaths (the 17: 17 readings at 10 a second). That caps it at about 35 a minute, just above the band. The rate comes from the time between the first and last breath, not from how many fit in 30 seconds, so a breath cut off at either end of the window doesn't skew it:
static float breathRate(const float *y, int n) {
float sd = 0;
for (int i = 0; i < n; i++) sd += y[i] * y[i];
sd = sqrtf(sd / n);
float thr = 0.3f * sd;
int state = 0, count = 0, first = -1, last = -1000;
for (int i = 0; i < n; i++) {
if (state <= 0 && y[i] > thr && i - last >= 17) {
state = 1;
count++;
if (first < 0) first = i;
last = i;
} else if (state == 1 && y[i] < -thr) state = -1;
}
return count >= 3 ? (count - 1) * 60.0f * RATE / (last - first) : 0;
}
Needing a fall below the lower line before the next rise above the upper one counts (hysteresis) stops small wobbles around zero from counting as several breaths.
Only answer when the sub-carriers agree
Every usable sub-carrier gives its own count. Some of them happen to sit where your chest makes a big difference and some don't. So the answer is the median across sub-carriers, and it's only shown when:
- at least 8 sub-carriers found 3 or more breaths;
- half the spread of the middle half of their answers (half the interquartile range) is 3 breaths a minute or less;
- the power above 1 Hz is less than 1.5 times the power in the breathing band.
Fail the first two and it shows "--". Fail the last and it shows "Too much movement". It says nothing rather than invent a number.
The wave drawn on the screen is the filtered signal of the sub-carrier whose count was closest to the median, which makes a nice check by eye: you can see your own breaths go past.
How well it works
In a counted test it read within one or two breaths a minute of the real rate. It needs you sitting still, half a metre to a metre away, with your chest roughly between the CoreS3 and the router, and it takes 30 seconds to show its first number.
Step 4: the theremin
The theremin uses the same signal for something to play with rather than measure. The screen fills with swirling plasma, and moving your hand near the Wi-Fi link to the router changes how fast it swirls and which colours it shows. Like the instrument it's named after, you play it without touching anything.
It pokes the router every 10 ms, smooths the 64 amplitudes into a profile, and compares that with a picture of the empty room taken at calibration. The profile is an average that moves 15% of the way towards each new reading, 25 times a second, so it smooths over about a quarter of a second. Two numbers come out of the comparison:
-
How much it differs. For each sub-carrier, the relative change from the empty room (
profile / empty - 1); then the root mean square of those (square them, average, take the square root), a single size for the whole change. - Which way. Lay the changes out across the sub-carriers and fit one slow wave to them, one cycle from the first sub-carrier to the last (the first Fourier component). Where that wave peaks says which part of the band got stronger and which weaker. That position is an angle, and the angle becomes a place on the colour wheel:
static float difference(float *angle) {
float total = 0, c = 0, sn = 0;
int m = 0;
for (int k = 0; k < SUB; k++) {
if (!used[k]) continue;
float d = profile[k] / empty[k] - 1;
total += d * d;
c += d * cosf(2 * PI * m / 52);
sn += d * sinf(2 * PI * m / 52);
m++;
}
if (angle) *angle = (atan2f(sn, c) + PI) / (2 * PI);
return sqrtf(total / max(m, 1));
}
Only the sub-carriers with real signal are used (the guard and DC ones are dropped at calibration), which leaves about 52, the number that carry data in a 20 MHz channel. So one full turn of the colour wheel spans the used band.
Calibration takes 5 seconds: 3 seconds to learn the empty pattern, then 2 seconds measuring how much the empty room's own pattern wobbles against it. That wobble is kept as a margin: its average plus 3 standard deviations, and never less than 0.03. In testing a hand changed the pattern by about 0.06 to 0.4, against 0.01 to 0.05 for the empty room, so there's a clear gap. Anything below that margin counts as nothing. Above it, the difference becomes size, from 0 to 1 (full at 9 times the margin), which sets how lively the plasma is: how fast it swirls (0.6 + 9 * size) and how far round the colour wheel the palette spreads (0.12 + 0.75 * size). The angle sets the colours, and each frame the colour moves only 15% of the way to the new angle (hue += 0.15 * dh) so it doesn't flicker.
Hold your hand still and the colours hold. Move it and they shift. You can learn to aim for a colour, but it takes practice, because each position's colour depends on how the signal happens to bounce around that particular room.
The limit is drift. The empty picture is fixed on purpose, so a hand held still keeps its colours for as long as it's there. The cost is that the room's own pattern drifts slowly, and after a while the screen gets busy with nobody there. The fix is a Recalibrate button that works like taring a kitchen scale: hands away, tap, wait 5 seconds.
Step 5: a tape measure from radio timing
The tape measure doesn't use CSI. It uses Wi-Fi fine timing measurement (FTM), which the ESP32-S3 supports at both ends. One side (the initiator) sends a burst of timing frames, the other (the responder) answers each one, and both note the time each frame left and arrived. Subtract the time the responder spent before answering, and what's left is the time there and back. Radio waves travel at the speed of light, about 30 cm a nanosecond, so half the round trip gives the distance.
Most home routers don't answer FTM, so the far end is a second ESP32-S3 (another CoreS3, a Cardputer or anything with an S3). It runs a soft access point (a Wi-Fi network hosted by the ESP32 itself, rather than by a router) with the FTM responder turned on. Nobody joins it; timing works without joining, and the password is random each start:
char pass[17];
for (int i = 0; i < 16; i++) pass[i] = "abcdefghjkmnpqrstuvwxyz23456789"[esp_random() % 31];
pass[16] = 0;
WiFi.mode(WIFI_AP);
bool ok = WiFi.softAP(NAME, pass, CHANNEL, 0, 1, true); // last argument: answer FTM
The CoreS3 finds "wifi-tape" on channel 11 and asks for bursts of 16 exchanges, with the burst period set to 2 (in units of 100 ms, so 200 ms):
WiFi.onEvent(onFtm, ARDUINO_EVENT_WIFI_FTM_REPORT);
...
if (!WiFi.initiateFTM(16, 2, farChannel, farMac)) return;
When a burst is done, the report event gives a distance estimate in centimetres. Single readings jump around, so it takes about 3 readings a second and shows the median (the middle value) of the last 9, which ignores the odd wild one.
The first thing I noticed: with the two boards side by side it read about 0.4 m. That's the radios' own processing delay showing up as distance. So there's a Zero button: put the two together, tap it, and that offset is stored in flash and taken off every reading. Reset clears it.
It's a rough tape measure, not a precise one. But it is measuring distance by timing radio waves, on two boards you can hold in one hand.
One practical tip: power the far end from a battery or power bank, not a computer.
Testing on the device without touching it
Every one of these apps has the same small serial interface at 115200 baud:
-
logprints the numbers behind the screen (off by default, so nothing piles up when no computer is reading); -
shotsends the screen as raw pixel rows (RGB565, the display's 16 bits a pixel), whichtools/screenshot.pyturns into a PNG; -
tap X Ytouches the screen at that point.
The radar also has test, which runs a cued test on the screen: get ready, then keep still and walk around in turn, 10 seconds each, while logging every 100 ms. It makes before and after comparisons repeatable. The breathing app has stream, which prints every row of 64 values ten times a second for analysis on a laptop.
I wrote these with an AI coding assistant, and this interface is what made that work well. It found that the ESP32-S3 exposes CSI, worked out the probe request trick, and could flash a build, tap through the screens, read the logs and look at screenshots without me pressing anything. The hardware loop got a lot shorter once the device could be driven from the command line.
What I'd tell someone starting out
- Check you're getting CSI at a usable rate before you write any analysis. Count readings per second first. Mine was 0.7 a second until I made the router talk.
- Normalise each frame. The overall level jumps around for reasons that have nothing to do with the room.
- Throw away the guard and DC sub-carriers. They're noise dressed up as signal.
- Position matters more than the algorithm. Movement off the line between the two radios barely registers. Use more than one path if you can.
- Let it say "I don't know". The breathing app only shows a number when the sub-carriers agree, and says so when they don't.
- Build a serial test interface on day one. Cued tests and screenshots over USB save hours.
- Only poke routers you own.
Try them
Each app builds from its firmware/ folder:
pio run -t upload
The tape measure has two builds:
pio run -e m5stack-cores3 -t upload
pio run -e far-end -t upload
Use -e far-end-cardputer for a Cardputer as the far end.
For the radar, breathing app and theremin, the first start lists the 2.4 GHz networks in range: tap your own router or hotspot. The choice is kept in flash.
Top comments (0)