Wi-Fi Sensing has been a topic of discussion for quite a long time. We can see several open-source projects as well around this topic on the internet. But the question is: do they really work efficiently or not? So, in this tutorial, we are going to see if WiFi sensing can actually see a person moving in the WiFi field. We will be using a normal WiFi router that we all use in our homes and 4 ESP32 boards to do so. We need at least one ESP32 for this to work as we need a receiving device that needs to receive the WiFi signals and see how a moving object or a person in the Wi-Fi coverage area affects the propagation paths of the wireless signals.
A lot of research and development is going on to make this a reliable technology. Some other options available for motion detection include PIR sensors, microwave radar sensors, or a WiFi motion detection Camera. We already have a tutorial on Human Presence and Fall Detection using an mmWave Sensor, which teaches the same in detail. So, let's see how we can deploy WiFi Sensing and detect motion. You can also check out similar ESP32-based projects that are available in Circuit Digest. So now, let's see how we can deploy WiFi Sensing and detect motion. ESP32 WiFi sensing uses Channel State Information (CSI) from ordinary WiFi packets to detect when a person moves through a room.
Quick Summary: What You Will Build
- Goal: Detect human motion from WiFi signal changes, with no camera and no PIR sensor.
- Hardware: A home WiFi router and 1 to 4+ ESP32 boards (we used 4).
- Method: Each ESP32 measures CSI from router replies (AP-STA link) and from other boards via ESP-NOW.
- Output: A web dashboard with a link map, rolling graphs, and a "Motion detected" alert.
- Accuracy: Presence and movement detection works to some extent; precise location tracking is limited.
What Is CSI in WiFi Sensing?
Before getting started, let's learn a little bit about CSI in WiFi Sensing.

How ESP32 WiFi Sensing Works
Let's take a look at how it works. The image below shows the system map with the main router and 3 individual ESP32 Boards named as links, and the second image below it shows the system map with the main router and 4 individual ESP32 Boards named as links. The system can be expanded by adding more ESP32 sensing nodes. However, in our current setup, we have configured it to work with 4 individual ESP32 boards and the AP. In both of the images, we can see the results when a person moved into the Wi-Fi field. It alerts with a motion-detected message at the top, as well as indicating a ‘person head’ icon on the map to denote the detected person and their movements. The motion tracking is not very accurate, but still, as per our experiments, it works to some extent.
The signals that come from a Wi-Fi router don't travel in straight lines, instead, it hits the surrounding objects and walls and then only it reaches the receiver like a laptop or a smartphone. CSI(Channel State Information) describes the characteristics of a wireless communication channel between a transmitter and a receiver. It provides information about how the transmitted Wi-Fi signal is affected by factors such as reflections, multipath propagation, attenuation, and phase shifts. When a person moves within the Wi-Fi coverage area, their body changes the propagation paths of the wireless signals. These changes affect the CSI measurements received by an ESP32. By continuously monitoring these variations and comparing them against a baseline, the system can identify disturbances that may indicate human movement. This is what we call Wi-Fi sensing.

Both of the diagrams here are to demonstrate that this works with any number of ESP32s. It even works with a single AP and a single ESP32 as well.

Once we are on the live web page, we can see two rolling graphs as well. The first one shows every motion detected between the AP(Access Point/Router) and each of the ESP32 Links, and the second one shows every motion detected between individual ESP32 Links via ESP-NOW. These rolling graphs appear right below the map shown above. The sensitivity of these detections can be adjusted and is mentioned in detail in the following sections. Now, talking about ESP-NOW, it's really awesome as it's already integrated with ESP32 boards. We recently used ESP-NOW to build a contactless water level monitoring system. Do check out the Smart Contactless Water-Level Monitoring System Project if you’d like to know more about it and our custom-built sensor.
Components Required For ESP32 WiFi Sensing
For this tutorial, we need a minimal number of components.

You'll need a router (a standard home router for internet access) and ESP32 boards. Here we are using 4 ESP32s, but they can be increased to any number as required. This even works with a single ESP32 board and the router as well. One thing that will probably make some efficient improvements is mounting the ESP32 boards properly in stands, as shown above.
ESP32 WiFi Motion Detection
Let's break things down and try to understand what is happening here.

AP(Access Point)-STA(Station) Link:
Once powered, each ESP32 board joins the router, turns on CSI capture, and pings the router about 50 times a second. The router answers with a matching ping reply packet. The content of the reply doesn’t matter for this to work. The .ino sketch checks how the radio signal looked when it arrived. That signal has travelled from the router to the board through the room, bouncing off walls, furniture and people. When someone moves, the signal changes, and the CSI measured from the next reply is slightly different from the current one.

ESP32 - ESP32 Links
Now, for better efficiency, we are also making a channel between each ESP32 link as well. Each ESP32 sends periodic data packets 20 times per second to the other ESP32s, and the receiving ESP32 analyses the Channel State Information (CSI) of those incoming packets to detect any motion. This does not pass through the router. The detected disturbances will be between boards.

The motion level is measured by calculating how much the signal fluctuates and comparing it with a threshold learned during a 15-second calibration with the room empty. Calibration here refers to measuring the background noise of the room when it is empty and setting up a threshold just above it, meaning setting up the zero point. So, whenever a moving object comes into the field, it crosses this threshold value and results in a trigger. This calibration is done in the dashboard itself by clicking the ‘Recalibrate All’ button as shown above. Calibration alone did not give us better results, as in some cases we need to increase or decrease the threshold value for proper triggering and get rid of any false triggers. That's why there are two sensitivity adjustment sliders provided. The sensitivity of the AP-STA (Access Point - Station) as well as ESP-NOW can be adjusted by using these two sliders as shown above.
Adjust the sensitivity and make sure we have no false triggers and that we have triggers only when we have motion. The Beep on motion option makes a beeping sound on the laptop/device where we see the web page. Peers option in the bottom helps us to add Peer IPs there instead of hardcoding them in the Arduino sketch. But the only problem with this is that if we switch to another device on the same network to visualise the web page, then the ESP32 devices won't appear there, as they were not hard-coded in the sketch.

In addition to the sensitivity adjustment, we can also set the time window from 10 seconds to 60 seconds so that we can see and visualise more data in the time frame. The ‘No motion’ above the graph turns to ‘Motion detected’ in red when motion is detected. The code can be edited to log the events to a server or something so that they can be accessed later, keeping this as a starting point.
Hardware Setup
Now, let's look at how we can properly set up the hardware for this to work.

The above image shows how we mounted the ESP32 boards. It's always recommended to keep the ESP32s, especially the antenna part from any metal parts like near a metal door, cabinet or something like that as that affects the overall antenna performance. The more they are on a mounting jig, the more efficient they will be, as tiny motions due to improper mounting contribute to false alarms. One more thing is that the above is just a reference. We can actually use any kind of ESP32 board that supports ESPNOW. Even an ESP8266 can also be used. For this tutorial, we used the XIAO ESP32 S3, ESP32 x 2, and the ESP32S3 CAM module to demonstrate this. Let's take a look at another important thing: how to enrol the various ESP32 boards on the system. Naming the boards properly is very important to distinguish the different boards.

As said above, the main Wi-Fi router also acts as a link in this network. Let's take a look at what credentials need to be entered to make this work. We will be flashing the same code to every ESP32 board, but we need to change some of these credentials. On every board, we need to enter the Wi-Fi SSID and Password that connect them to the router. Then we need to give names to each of the boards in the NAME field. Once we enter these fields and flash the code, the board's IP address will be displayed in the serial monitor. Copy that to a notepad or something, as we need to use them in the next step. The same way, repeat this for all the boards, entering the Wi-Fi credentials, naming them, flashing the code and copying the IP address. This process registers the individual ESP32 boards to the Wi–Fi network.

Now, in the final ESP32, where we are going to run the web server, enter all the other ESP32s’ IP addresses in the PEER_IPS field along with other credentials and flash the code. This particular ESP32’s IP will also be displayed in the serial monitor; use it to visualise the web page. If you’re interested in building a WiFi jammer, do check out our WiFi jammer using NodeMCU tutorial.
ESP32 WiFi Sensing GitHub Code Explanation
Let's take a look at the code explanation for this project.
const char *WIFI_SSID = "YOUR-SSID";
const char *WIFI_PASS = "YOUR-PASSWORD";
const char *NAME = "NAME-OF-ESP32";
const char *PEER_IPS = "";Above are the credentials that need to be provided in the code for every individual board except the one whose IP Address is used for visualising the dashboard.
const char *PEER_IPS = "192.168.0.2,192.168.0.3,192.168.0.24";PEER_IP is to be filled as above in the board whose IP Address is used for visualising the dashboard. More about this is explained in the Hardware Setup Section, where this credentials part is also covered in detail.
static void addPeerIfNew(const uint8_t *mac) {
int n = peerStCount;
for (int p = 0; p < n; p++)
if (memcmp(peerSt[p].mac, mac, 6) == 0)
return;
if (n >= MAXPEERS)
return;
PeerState &ps = peerSt[n];
memset(&ps, 0, sizeof(ps));
memcpy(ps.mac, mac, 6);
ps.baseline = 0.03f;
ps.calibrating = true;
ps.calStart = millis();
peerStCount = n + 1; // publish last, after the slot is fully set up
}This portion of the code checks whether a newly detected ESP32 board already exists in the peer list. extracts and stores its MAC address, initialises its calibration and detection parameters and supports automatic discovery of up to 8 other boards.
void csiCb(void *ctx, wifi_csi_info_t *info) {
if (!info || !info->buf)
return;
if (info->len / 2 < NSUB)
return;This is the main function responsible for receiving and processing CSI (Channel State Information) data. Whenever the ESP32 receives a WiFi packet containing CSI information, this callback gets executed. It first checks whether valid CSI data is available. After that, the processing happens in two different paths.
// --- Router path ---
if (memcmp(info->mac, TX_MAC, 6) == 0) {
const int8_t *d = info->buf;
float a[NSUB], sum = 0;
for (int k = 0; k < NSUB; k++) {
float im = d[2 * k], re = d[2 * k + 1];
a[k] = sqrtf(re * re + im * im);
sum += a[k];
}...................}This part of the code calculates the magnitude of each of the 64 CSI subcarriers, normalises the amplitude values to reduce the influence of overall signal strength changes, stores the latest 50 CSI samples, calculates variations in each subcarrier to identify changes in the wireless channel, establishes a baseline, calculates the motion detection threshold and compares the CSI against the set threshold.
// --- Peer board path (ESP-NOW beacons) ---
int n = peerStCount;
for (int p = 0; p < n; p++) {
if (memcmp(info->mac, peerSt[p].mac, 6) == 0) {
processPeerPacket(peerSt[p], info->buf, info->len);
return;
}
}
Checks the list of discovered ESP32 boards, compares the incoming packet's MAC address with the stored peer MAC addresses, identifies which ESP32 transmitted the packet, passes its CSI data to processPeerPacket() and processes the signal independently for that particular board.
void espNowBeaconTask(void *pv) {
static const uint8_t broadcast[6] = {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF};
for (;;) {
esp_now_send(broadcast, BEACON_MAGIC, 4);
vTaskDelay(pdMS_TO_TICKS(50));
}
}Broadcasts a unique identification beacon every 50 milliseconds, allows nearby ESP32 boards to discover one another and provides wireless communication traffic for board-to-board CSI sensing.
void setup() {
Serial.begin(115200);
delay(1500); // give ESP32-S3 USB CDC time to connect to PC serial monitor
WiFi.mode(WIFI_STA);
WiFi.begin(WIFI_SSID, WIFI_PASS);
while (WiFi.status() != WL_CONNECTED) {
delay(300);
Serial.print(".");
}
...................................
server.begin();
}Initialises Serial communication, connects to the WiFi router, enables CSI collection, initialises ESP-NOW, registers the required callbacks, starts the beacon broadcasting task, starts continuous router pinging and configures the web server and its endpoints.
ESP32 WiFi Sensing Live Demo: Motion Detection in Action
Watch our four ESP32s and home router detect a person walking through the room in real time. The video shows the dashboard's link map, the rolling graphs, and the "Motion detected" alert as it happens. It also shows how calibration and the sensitivity sliders affect results, so you can compare them with your own build.
Conclusion
ESP32 WiFi Sensing is an interesting technology that opens up a lot of opportunities beyond traditional wireless technologies. We can use the already existing WiFi Signals, analyze variations in the Channel State Information (CSI) to detect any motions. It gives us all the foundations to learn the basics of this wireless technology brick by brick. In this tutorial, we learned how 4 ESP32 development modules can be paired with our home WiFi Router to detect motion. The motion tracking was not that accurate, but it still worked decently. With further refinements, this can be used for applications like smart home automation, occupancy detection, alarm systems and all.
GitHub Repository
The complete open-source sketch for this project is available in our ESP32 WiFi sensing GitHub repository. It includes CSI capture, ESP-NOW beaconing, calibration, and the web dashboard code used in this tutorial. Clone or download it, flash the same code to every board, and set only the WiFi credentials, board name, and peer IPs.

Complete Project Code
// WiFi motion detection - receiver v8 (ESP-NOW mesh, automatic peer discovery)
// Router as transmitter (ping -> CSI). Board-to-board sensing via ESP-NOW
// beacons: boards find each other automatically, no MAC addresses to type.
// Arduino-ESP32 core 3.x. Keep webpage.h in the same folder as this file.
#include "esp_idf_version.h"
#include "lwip/ip_addr.h"
#include "ping/ping_sock.h"
#include <WebServer.h>
#include <WiFi.h>
#include <esp_now.h>
#include <esp_wifi.h>
#include <math.h>
// ---------- EDIT THESE ----------
const char *WIFI_SSID = "Semicon ACT";
const char *WIFI_PASS = "cracksen1605";
const char *NAME = "XIAO"; // unique name per board
// Only needed on the board whose web page you open: the OTHER boards' IPs.
const char *PEER_IPS = "192.168.0.2,192.168.0.3,192.168.0.24";
// --------------------------------
uint8_t TX_MAC[6] = {0}; // router MAC - filled from WiFi.BSSID()
#define NSUB 64 // subcarriers used
#define WIN 50 // sliding window = 50 packets (~1 s at 50 pps)
#define STEP 5 // recompute every STEP packets
#define EVMAX 30 // motion events remembered
const uint32_t HOLD_MS = 3000; // keep "motion" on for 3 s after last trigger
const uint32_t CAL_MS = 15000; // calibration time (keep room empty)
// Beacon payload: lets boards recognise each other (ignores other ESP-NOW
// users)
static const uint8_t BEACON_MAGIC[4] = {'W', 'M', 'S', '1'};
// ---- Router CSI state ----
float buf[WIN][NSUB];
int widx = 0, filled = 0, sinceCalc = 0;
volatile float smoothMetric = 0, threshold = 0.05f, calMax = 0;
volatile float baseline = 0.03f, sensWifi = 1.15f, sensEn = 1.35f;
volatile bool calibrating = true, motion = false;
volatile uint32_t pktCount = 0, pps = 0, motionUntil = 0, calStart = 0;
// ---- ESP-NOW per-peer CSI state (filled automatically) ----
#define EN_WIN 30 // window for board-to-board links
#define MAXPEERS 8 // up to 8 other boards
struct PeerState {
uint8_t mac[6];
float buf[EN_WIN][NSUB];
int widx, filled, step;
float smooth, threshold, calMax, baseline;
bool motion, calibrating;
uint32_t motionUntil, calStart, pktCount;
float lastRatio; // smooth / threshold, shown on the web page
};
PeerState peerSt[MAXPEERS];
volatile int peerStCount = 0;
// ---- Motion event log ----
struct Ev {
uint32_t start, dur;
float peak;
};
Ev evs[EVMAX];
volatile uint32_t evN = 0;
uint32_t evStart = 0;
float evPeak = 0;
bool inEv = false;
// ---- Recent samples for the live graph ----
#define SMAX 64
struct Sm {
uint32_t t;
float v;
};
Sm sms[SMAX];
volatile uint32_t smN = 0;
WebServer server(80);
#include "webpage.h"
// Add a board to the peer list the first time we hear its beacon
static void addPeerIfNew(const uint8_t *mac) {
int n = peerStCount;
for (int p = 0; p < n; p++)
if (memcmp(peerSt[p].mac, mac, 6) == 0)
return;
if (n >= MAXPEERS)
return;
PeerState &ps = peerSt[n];
memset(&ps, 0, sizeof(ps));
memcpy(ps.mac, mac, 6);
ps.baseline = 0.03f;
ps.calibrating = true;
ps.calStart = millis();
peerStCount = n + 1; // publish last, after the slot is fully set up
}
// Process one packet's CSI from a peer board into its own sliding window
static void processPeerPacket(PeerState &ps, const int8_t *d, int len) {
if (len / 2 < NSUB)
return;
float a[NSUB], sum = 0;
for (int k = 0; k < NSUB; k++) {
float im = d[2 * k], re = d[2 * k + 1];
a[k] = sqrtf(re * re + im * im);
sum += a[k];
}
float mean = sum / NSUB;
if (mean < 1)
return;
for (int k = 0; k < NSUB; k++)
ps.buf[ps.widx][k] = a[k] / mean;
ps.widx = (ps.widx + 1) % EN_WIN;
if (ps.filled < EN_WIN)
ps.filled++;
ps.pktCount++;
if (++ps.step < STEP || ps.filled < EN_WIN)
return;
ps.step = 0;
float tot = 0;
int cnt = 0;
for (int k = 0; k < NSUB; k++) {
float m = 0;
for (int i = 0; i < EN_WIN; i++)
m += ps.buf[i][k];
m /= EN_WIN;
if (m < 0.2f)
continue;
float v = 0;
for (int i = 0; i < EN_WIN; i++) {
float dd = ps.buf[i][k] - m;
v += dd * dd;
}
tot += sqrtf(v / EN_WIN);
cnt++;
}
float mt = cnt ? tot / cnt : 0;
ps.smooth = 0.6f * ps.smooth + 0.4f * mt;
uint32_t now = millis();
if (ps.calibrating) {
if (ps.smooth > ps.calMax)
ps.calMax = ps.smooth;
if (now - ps.calStart > CAL_MS) {
ps.baseline = ps.calMax;
ps.threshold = ps.baseline * sensEn + 0.003f;
ps.calibrating = false;
}
ps.motion = false;
} else {
ps.lastRatio = ps.smooth / ps.threshold;
if (ps.smooth > ps.threshold)
ps.motionUntil = now + HOLD_MS;
ps.motion = (int32_t)(ps.motionUntil - now) > 0;
}
}
// CSI callback - runs for every received packet (router replies or peer
// beacons)
void csiCb(void *ctx, wifi_csi_info_t *info) {
if (!info || !info->buf)
return;
if (info->len / 2 < NSUB)
return;
// --- Router path ---
if (memcmp(info->mac, TX_MAC, 6) == 0) {
const int8_t *d = info->buf;
float a[NSUB], sum = 0;
for (int k = 0; k < NSUB; k++) {
float im = d[2 * k], re = d[2 * k + 1];
a[k] = sqrtf(re * re + im * im);
sum += a[k];
}
float mean = sum / NSUB;
if (mean < 1)
return;
for (int k = 0; k < NSUB; k++)
buf[widx][k] = a[k] / mean;
widx = (widx + 1) % WIN;
if (filled < WIN)
filled++;
pktCount++;
if (++sinceCalc < STEP || filled < WIN)
return;
sinceCalc = 0;
float tot = 0;
int cnt = 0;
for (int k = 0; k < NSUB; k++) {
float m = 0;
for (int i = 0; i < WIN; i++)
m += buf[i][k];
m /= WIN;
if (m < 0.2f)
continue;
float v = 0;
for (int i = 0; i < WIN; i++) {
float dd = buf[i][k] - m;
v += dd * dd;
}
tot += sqrtf(v / WIN);
cnt++;
}
float mt = cnt ? tot / cnt : 0;
smoothMetric = 0.6f * smoothMetric + 0.4f * mt;
uint32_t now = millis();
if (calibrating) {
if (smoothMetric > calMax)
calMax = smoothMetric;
if (now - calStart > CAL_MS) {
baseline = calMax;
threshold = baseline * sensWifi + 0.003f;
calibrating = false;
}
motion = false;
inEv = false;
} else {
float ratio = smoothMetric / threshold;
if (smoothMetric > threshold)
motionUntil = now + HOLD_MS;
bool m = (int32_t)(motionUntil - now) > 0;
if (m && !inEv) {
inEv = true;
evStart = now;
evPeak = ratio;
}
if (m && inEv && ratio > evPeak)
evPeak = ratio;
if (!m && inEv) {
inEv = false;
int32_t dur = (int32_t)((motionUntil - HOLD_MS) - evStart);
if (dur < 0)
dur = 0;
Ev &e = evs[evN % EVMAX];
e.start = evStart;
e.dur = (uint32_t)dur;
e.peak = evPeak;
evN++;
}
motion = m;
}
Sm &q = sms[smN % SMAX];
q.t = now;
q.v = calibrating ? 0 : smoothMetric / threshold;
smN++;
return;
}
// --- Peer board path (ESP-NOW beacons) ---
int n = peerStCount;
for (int p = 0; p < n; p++) {
if (memcmp(info->mac, peerSt[p].mac, 6) == 0) {
processPeerPacket(peerSt[p], info->buf, info->len);
return;
}
}
}
// ESP-NOW receive callback: learn who the other boards are
void onEspNowRecv(const esp_now_recv_info_t *info, const uint8_t *data,
int len) {
if (len == 4 && memcmp(data, BEACON_MAGIC, 4) == 0)
addPeerIfNew(info->src_addr);
}
// Ping the router ~50 times a second so CSI keeps flowing
void startPing() {
ip_addr_t target;
ipaddr_aton(WiFi.gatewayIP().toString().c_str(), &target);
esp_ping_config_t cfg = ESP_PING_DEFAULT_CONFIG();
cfg.target_addr = target;
cfg.count = ESP_PING_COUNT_INFINITE;
cfg.interval_ms = 20;
cfg.timeout_ms = 1000;
cfg.data_size = 1;
cfg.task_stack_size = 3072;
esp_ping_callbacks_t cbs = {};
esp_ping_handle_t h;
esp_ping_new_session(&cfg, &cbs, &h);
esp_ping_start(h);
}
// Broadcast a beacon at 20 Hz so the other boards can measure CSI from us
void espNowBeaconTask(void *pv) {
static const uint8_t broadcast[6] = {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF};
for (;;) {
esp_now_send(broadcast, BEACON_MAGIC, 4);
vTaskDelay(pdMS_TO_TICKS(50));
}
}
// ---------------------------------------------------------------------
// HTTP handlers
// ---------------------------------------------------------------------
void sendCors() { server.sendHeader("Access-Control-Allow-Origin", "*"); }
// Send large PROGMEM strings in 1 KB chunks so they never exceed the lwIP TCP
// send buffer
static void sendProgmemChunks(const char *data) {
size_t len = strlen_P(data);
const size_t CHUNK = 1024;
for (size_t i = 0; i < len; i += CHUNK) {
size_t n = (len - i < CHUNK) ? (len - i) : CHUNK;
server.sendContent_P(data + i, n);
}
}
void sendPage() {
server.setContentLength(CONTENT_LENGTH_UNKNOWN);
server.send(200, "text/html; charset=utf-8", "");
sendProgmemChunks(HTML_HEAD);
String peerLine = "const PEER=\"" + String(PEER_IPS) + "\";\n";
server.sendContent(peerLine);
sendProgmemChunks(HTML_TAIL);
server.sendContent("");
}
// /espnow -> what THIS board measures from each other board
void sendEspNow() {
String s = "[";
int n = peerStCount;
for (int p = 0; p < n; p++) {
if (p)
s += ",";
char mac[18];
snprintf(mac, sizeof(mac), "%02X:%02X:%02X:%02X:%02X:%02X",
peerSt[p].mac[0], peerSt[p].mac[1], peerSt[p].mac[2],
peerSt[p].mac[3], peerSt[p].mac[4], peerSt[p].mac[5]);
s += "{\"mac\":\"";
s += mac;
s += "\",\"motion\":";
s += peerSt[p].motion ? "true" : "false";
s += ",\"calib\":";
s += peerSt[p].calibrating ? "true" : "false";
s += ",\"ratio\":";
s += String(peerSt[p].lastRatio, 2);
s += ",\"pkt\":";
s += String(peerSt[p].pktCount);
s += "}";
}
s += "]";
sendCors();
server.send(200, "application/json", s);
}
void setup() {
Serial.begin(115200);
delay(1500); // give ESP32-S3 USB CDC time to connect to PC serial monitor
WiFi.mode(WIFI_STA);
WiFi.begin(WIFI_SSID, WIFI_PASS);
while (WiFi.status() != WL_CONNECTED) {
delay(300);
Serial.print(".");
}
WiFi.setSleep(false);
memcpy(TX_MAC, WiFi.BSSID(), 6);
Serial.println("\nIP : " + WiFi.localIP().toString() + " channel " +
String(WiFi.channel()));
Serial.println("MAC: " + WiFi.macAddress() + " Router: " + WiFi.BSSIDstr());
// --- CSI ---
wifi_csi_config_t csiCfg = {};
csiCfg.lltf_en = true;
csiCfg.htltf_en = false;
csiCfg.stbc_htltf2_en = false;
csiCfg.ltf_merge_en = false;
csiCfg.channel_filter_en = false;
csiCfg.manu_scale = false;
esp_wifi_set_csi_config(&csiCfg);
esp_wifi_set_csi_rx_cb(csiCb, NULL);
esp_wifi_set_csi(true);
// --- ESP-NOW ---
if (esp_now_init() == ESP_OK) {
esp_now_register_recv_cb(onEspNowRecv);
esp_now_peer_info_t bcast = {};
memset(bcast.peer_addr, 0xFF, 6);
bcast.channel = 0; // use the channel the router is on
bcast.ifidx = WIFI_IF_STA;
bcast.encrypt = false;
esp_now_add_peer(&bcast);
// ESP-NOW defaults to a 1 Mbps legacy rate, and the chip gives NO CSI for
// those frames. Send as 802.11n MCS0 so the receiving boards get CSI.
#if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(5, 0, 0)
esp_now_rate_config_t rc = {};
rc.phymode = WIFI_PHY_MODE_HT20;
rc.rate = WIFI_PHY_RATE_MCS0_LGI;
rc.ersu = false;
rc.dcm = false;
esp_now_set_peer_rate_config(bcast.peer_addr, &rc);
#else
esp_wifi_config_espnow_rate(WIFI_IF_STA, WIFI_PHY_RATE_MCS0_LGI);
#endif
xTaskCreatePinnedToCore(espNowBeaconTask, "enBeacon", 4096, NULL, 1, NULL,
0);
Serial.println("ESP-NOW ready. Beacons on; other boards are discovered "
"automatically.");
} else {
Serial.println("ESP-NOW init failed - running router-only mode.");
}
startPing();
calStart = millis();
// --- Web server routes ---
server.on("/", sendPage);
server.on("/espnow", sendEspNow);
server.on("/status", []() {
uint32_t n = smN;
uint32_t since =
server.hasArg("since") ? (uint32_t)server.arg("since").toInt() : n;
if (since > n)
since = 0;
if (n - since > SMAX)
since = n - SMAX;
String s;
s.reserve(900);
s += "{\"name\":\"";
s += NAME;
s += "\",\"mac\":\"";
s += WiFi.macAddress();
s += "\",\"motion\":";
s += motion ? "true" : "false";
s += ",\"calibrating\":";
s += calibrating ? "true" : "false";
s += ",\"metric\":";
s += String((float)smoothMetric, 4);
s += ",\"threshold\":";
s += String((float)threshold, 4);
s += ",\"pps\":";
s += String((unsigned)pps);
s += ",\"rssi\":";
s += String(WiFi.RSSI());
s += ",\"up\":";
s += String(millis());
s += ",\"n\":";
s += String(n);
s += ",\"enPeers\":";
s += String((int)peerStCount);
s += ",\"s\":[";
for (uint32_t i = since; i < n; i++) {
Sm q = sms[i % SMAX];
if (i > since)
s += ",";
s += "[" + String(q.t) + "," + String(q.v, 2) + "]";
}
s += "]}";
sendCors();
server.send(200, "application/json", s);
});
server.on("/events", []() {
uint32_t n = evN;
int cnt = n < EVMAX ? (int)n : EVMAX;
String s =
"{\"up\":" + String(millis()) + ",\"n\":" + String(n) + ",\"ev\":[";
for (int i = 0; i < cnt; i++) {
Ev e = evs[(n - cnt + i) % EVMAX];
if (i)
s += ",";
s += "{\"start\":" + String(e.start) + ",\"dur\":" + String(e.dur) +
",\"peak\":" + String(e.peak, 2) + "}";
}
s += "]}";
sendCors();
server.send(200, "application/json", s);
});
server.on("/calibrate", []() {
calMax = 0;
calStart = millis();
calibrating = true;
int n = peerStCount;
for (int p = 0; p < n; p++) { // also recalibrate the board-to-board links
peerSt[p].calMax = 0;
peerSt[p].calStart = millis();
peerSt[p].calibrating = true;
}
sendCors();
server.send(200, "text/plain", "ok");
});
server.on("/sens", []() {
String type = server.hasArg("type") ? server.arg("type") : "";
float val = server.hasArg("v") ? server.arg("v").toFloat() : 0.0f;
if (server.hasArg("wifi")) {
sensWifi = server.arg("wifi").toFloat();
threshold = baseline * sensWifi + 0.003f;
}
if (server.hasArg("en")) {
sensEn = server.arg("en").toFloat();
int n = peerStCount;
for (int p = 0; p < n; p++)
peerSt[p].threshold = peerSt[p].baseline * sensEn + 0.003f;
}
if (type == "wifi" && val > 0) {
sensWifi = val;
threshold = baseline * sensWifi + 0.003f;
} else if (type == "en" && val > 0) {
sensEn = val;
int n = peerStCount;
for (int p = 0; p < n; p++)
peerSt[p].threshold = peerSt[p].baseline * sensEn + 0.003f;
} else if (server.hasArg("v") && type == "") {
sensWifi = val;
sensEn = val;
threshold = baseline * sensWifi + 0.003f;
int n = peerStCount;
for (int p = 0; p < n; p++)
peerSt[p].threshold = peerSt[p].baseline * sensEn + 0.003f;
}
sendCors();
server.send(200, "text/plain", "ok");
});
server.begin();
}
void loop() {
server.handleClient();
static uint32_t lastT = 0, lastCnt = 0;
if (millis() - lastT >= 1000) {
lastT = millis();
pps = pktCount - lastCnt;
lastCnt = pktCount;
Serial.printf("pps=%u metric=%.4f thr=%.4f motion=%d events=%u peers=%d",
(unsigned)pps, (float)smoothMetric, (float)threshold,
(int)motion, (unsigned)evN, (int)peerStCount);
int n = peerStCount;
for (int p = 0; p < n; p++) {
char mac[7];
snprintf(mac, sizeof(mac), "%02X%02X%02X", peerSt[p].mac[3],
peerSt[p].mac[4], peerSt[p].mac[5]);
Serial.printf(" EN[%s] pkts=%u ratio=%.2f(%s)", mac,
(unsigned)peerSt[p].pktCount, peerSt[p].lastRatio,
peerSt[p].motion ? "MOV" : "---");
}
Serial.println();
}
}
Add a comment
No account needed. Your comment appears once a moderator has reviewed it.