Rather than getting stuck into the sponsored kit right away, I decided to take a different approach and solve the issue that was bugging me most – connectivity. As much as I’ve used the ESP32 before, it seems a lot has changed in the meantime. The Bluedroid-based Bluetooth stack has given way to its light-weight successor, NimBLE and Bluetooth v5.0 capabilities including Long-Range Coded PHY are now in hardware too. Because of this, I grabbed some ESP32-S3 boards, knowing that they’d be able to do this, whereas my “traditional” ESP32 boards could only do Bluetooth v4.2 1M PHY at best.
Why BLE Coded PHY?
For those not familiar, Bluetooth is a 2.4GHz-based wireless standard which focuses on low-power, short-range and interoperability. It comes in multiple “flavours” including Classic (which, itself went through several iterations of physical-layers (PHYs) including Basic Rate (1Mbit/s GFSK), EDR (2Mbit/s π/4-DQPSK and 3Mbit/s 8DPSK) and HS which borrowed Wi-Fi at around 24Mbit/s) and the more recent Low Energy (frequently abbreviated LE) which also has “grown” a few different PHYs. These include the LE 1M mode (1Mbit/s GFSK, distinct from the Classic implementation, since v4.0), LE Coded (using forward error correction, 1Mbit/s GFSK with S=2 and S=8, since v5.0), LE 2M mode (2Mbit/s GFSK, also since v5.0).
Plenty of devices today still operate in either Bluetooth Classic (including all pre-LE-Audio Bluetooth headsets, keyboards and mice), while others operate using LE 1M mode such as tracking tags, beacon tags and sensor tiles. The main reason for this is compatibility and interoperability.

There is a cost though. In the case of LE 1M mode, the datasheet for the ESP32-S3 tells me that it can receive with a 30.8% packet error rate down to -97.5dBm in ideal conditions. This seems to be a fairly reasonable specification – most Wi-Fi cards will reach 9% PER at 1Mbit/s at -90dBm to -99dBm, which is in a similar ball-park. This sets a practical limit on the amount of range we can expect, as signals get weaker due to spreading, with losses due to attenuation propagating through materials and the potential for interference.
So, if LE 1M and Coded PHY share the same 1Mbit/s GFSK modulation, how does LE Coded PHY help with this problem? Well, the secret is two-fold. The first is in the name coded. What this means is that the data rate is lower and additional coding is added to provide the ability to perform forward-error-correction on the data hence improving sensitivity. The “S” in S=2 and S=8 modes stands for spreading – in the case of S=2, one data bit is spread across two data bits, thus halving the throughput (hence why it’s advertised with a 500kbit/s rate). The S=8 mode is even more robust, spreading one data bit across eight bits, but hence only achieving an-eighth of the data rate at 125kbit/s. Because of this “spreading”, it’s more resilient to individual bit-errors caused by interference or fading. This is a similar reason to how GNSS (e.g. GPS) can work with such limited transmit powers all the way from space – but it uses a spreading factor of S=20,460 (running at 1.023Mbit/s, but sending a 50bit/s stream) – taking this to the extreme!
The second way this can help boils down to how advertisements are handled in Bluetooth v5.0. The three channels used by advertisements in v4.0 are starting to get quite crowded and so collisions with data loss are occurring more frequently. As a result, the use of extended advertising is required – in essence, a short advertisement is made on the three advertising channels that acts as a “pointer” – it’s a message that tells the receiver to go to a given channel after a certain amount of time to receive the broadcast. This “frees” capacity on the advertising channel and reduces the likelihood of collisions – especially important as extended advertising also allows for longer advertisement packets and when combining with Coded PHY, these advertisements can get quite long (in terms of Bluetooth air-time, relative to ordinary LE 1M standard advertisements).

The datasheet claims that going to S=8 gives us an improvement, down to -104.5dBm which means that the coded PHY gave us an advantage of 7dB simply through changes to how bits are translated into symbols transmitted over the air. This is not quite the 12dB that theory predicts, but the real-life performance is often going to fall short due to noise-floor limitations. Of course, it’s not a free lunch – your transmissions are a bit more than eight-times longer, meaning that you’ll be spending a little more than eight times the energy. In return, you’d be expecting to see close to four-times the range (in theory).
In my case, this is worth it – eight times a small amount of energy is still a small amount of energy! Even if you don’t need all of the range, you might want the reliability to have the margin to handle the day your bin gets kidnapped by the bin-truck and gets taken two houses further down than normal!
Not Quite PHY-ne …
Since the hardware supports the LE Coded PHY mode, we’re ready-to-go right? Not quite.
While one can use the NimBLE library which supports such functionality, for ESP32, it’s not as simple as toggling a few settings in nimconfig.h. Unfortunately, for me, it turns out that arduino-esp32 Arduino Core has build-time configurations in defconfig.esp32s3 that are not set to enable this out-of-the-box. The result is that projects simply won’t be able to do any extended advertisements at all!

The above versions are the current versions available via the board manager/library manager URLs as of writing. I decided to install them anyway just to get started. Some people even suggest changing over to Nordic-based boards … but I only just got these ESP32-S3s!
Starting with 1M PHY
As a raccoon, I was itching to get started. My hands just couldn’t stop …

Step 1 was simply to assume I had no Coded PHY at all – let’s just build with standard advertising to see how well that works. For energy efficiency, I’ve decided to go with a plain advertising solution rather than a connection/notification method. This is less secure and doesn’t guarantee delivery, but should allow the collecting node to sleep for longer. After all, a single lost bin data sample or two won’t stop it from working.
One thing I was curious was whether the board could still maintain a Wi-Fi connection under such heavy advertisement scanning and whether it could serve a simple webpage. So there are two sketches – one for the bin node that transmits the data frame and one for the home receiver that receives the data and formats it for display.
To minimise power requirements and to fit within standard advertising limits, I’ve decided to stick to an eight-byte frame format with just four payload bytes to start with. That’s quite a bit of space if used wisely. There is some overhead from other advertisement data that needs to be put in there to meet standards and ensure other scanners are happy. To ensure receivers get the message, the broadcast is sent a few times. Receivers will validate frames based on fixed magic bytes and filter duplicates based on matching sequence numbers and packet data. To differentiate between different bins, a Node ID byte is also used.
The code is as below –
[esp32s3-BatteryNode.ino]
# ESP32-S3 Arduino BLE Advertising (1M PHY) with NimBLE Sketch
# Battery-Operated Sensor Node
# by Gough Lui with debugging assistance from OpenAI ChatGPT GPT-6 Luna (Nov 2026)
# for My Project is Trash Design Challenge
#include <Arduino.h>
#include <NimBLEDevice.h>
#include <esp_sleep.h>
#include <esp_attr.h>
#include <esp_system.h>
#include <string.h>
#include <freertos/FreeRTOS.h>
#include <freertos/task.h>
#include "PacketFormat.h"
#define BATTERY_NODE_DEBUG 0
#if BATTERY_NODE_DEBUG
#define NODE_PRINT(...) Serial.print(__VA_ARGS__)
#define NODE_PRINTLN(...) Serial.println(__VA_ARGS__)
#define NODE_PRINTF(...) Serial.printf(__VA_ARGS__)
#define NODE_SERIAL_BEGIN() Serial.begin(115200)
#define NODE_SERIAL_FLUSH() Serial.flush()
#else
#define NODE_PRINT(...) do {} while (0)
#define NODE_PRINTLN(...) do {} while (0)
#define NODE_PRINTF(...) do {} while (0)
#define NODE_SERIAL_BEGIN() do {} while (0)
#define NODE_SERIAL_FLUSH() do {} while (0)
#endif
static constexpr uint32_t SENSOR_SAMPLE_INTERVAL_MS = 500;
static constexpr uint32_t MIN_REPORT_INTERVAL_MS = 500;
static constexpr uint32_t HEARTBEAT_TRIGGER_MS = 500;
static constexpr uint32_t ADVERTISING_DURATION_MS = 250;
static constexpr uint16_t ADVERTISING_INTERVAL_UNITS = 160;
static constexpr uint32_t RTC_STATE_MAGIC = 0x534E4F44;
struct RetainedState {
uint32_t magic;
uint8_t lastSentPayload[SENSOR_DATA_LENGTH];
bool haveLastSentPayload;
uint8_t nextSequence;
uint32_t elapsedSinceReportMs;
uint32_t previousCycleActiveMs;
uint32_t demonstrationSampleCounter;
};
RTC_DATA_ATTR static RetainedState retained;
static bool readSensorData(uint8_t output[SENSOR_DATA_LENGTH]) {
++retained.demonstrationSampleCounter;
const uint32_t exampleMeasurement = retained.demonstrationSampleCounter;
memcpy(output, &exampleMeasurement, sizeof(exampleMeasurement));
return true;
}
static void initialiseRetainedState() {
if (retained.magic == RTC_STATE_MAGIC) {
return;
}
memset(&retained, 0, sizeof(retained));
retained.magic = RTC_STATE_MAGIC;
retained.nextSequence = static_cast<uint8_t>(esp_random());
retained.haveLastSentPayload = false;
retained.elapsedSinceReportMs = HEARTBEAT_TRIGGER_MS;
}
static void updateElapsedTimeSinceLastReport() {
const uint64_t total = static_cast<uint64_t>(retained.elapsedSinceReportMs) +
retained.previousCycleActiveMs +
SENSOR_SAMPLE_INTERVAL_MS;
retained.elapsedSinceReportMs = (total > UINT32_MAX)
? UINT32_MAX : static_cast<uint32_t>(total);
}
static void sleepUntilNextSample() {
NODE_SERIAL_FLUSH();
esp_sleep_enable_timer_wakeup(
static_cast<uint64_t>(SENSOR_SAMPLE_INTERVAL_MS) * 1000ULL);
esp_deep_sleep_start();
while (true) {
delay(1000);
}
}
static bool advertiseSensorData(const uint8_t payload[SENSOR_DATA_LENGTH],
uint8_t sequence,
uint32_t &advertisingStartMs) {
SensorPacket packet{};
packet.magic = SENSOR_PACKET_MAGIC;
packet.nodeId = SENSOR_NODE_ID;
packet.sequence = sequence;
memcpy(packet.payload, payload, SENSOR_DATA_LENGTH);
uint8_t manufacturerData[MANUFACTURER_DATA_LENGTH];
manufacturerData[0] = static_cast<uint8_t>(COMPANY_ID & 0xFF);
manufacturerData[1] = static_cast<uint8_t>(COMPANY_ID >> 8);
memcpy(manufacturerData + 2, &packet, sizeof(packet));
NimBLEDevice::init("");
NimBLEAdvertising *advertising = NimBLEDevice::getAdvertising();
if (advertising == nullptr) {
NimBLEDevice::deinit(true);
return false;
}
if (!advertising->setConnectableMode(BLE_GAP_CONN_MODE_NON)) {
NimBLEDevice::deinit(true);
return false;
}
advertising->setAdvertisingInterval(ADVERTISING_INTERVAL_UNITS);
advertising->enableScanResponse(false);
NimBLEAdvertisementData advertisementData;
advertisementData.setFlags(0x06);
if (!advertisementData.setManufacturerData(manufacturerData,
sizeof(manufacturerData)) ||
!advertising->setAdvertisementData(advertisementData)) {
NimBLEDevice::deinit(true);
return false;
}
advertisingStartMs = millis();
if (!advertising->start(ADVERTISING_DURATION_MS)) {
NimBLEDevice::deinit(true);
return false;
}
NODE_PRINTF("Broadcast: node=0x%02X sequence=%u data=",
static_cast<unsigned>(packet.nodeId),
static_cast<unsigned>(packet.sequence));
for (size_t i = 0; i < SENSOR_DATA_LENGTH; ++i) {
NODE_PRINTF("%02X", static_cast<unsigned>(packet.payload[i]));
}
NODE_PRINTLN();
while (advertising->isAdvertising()) {
vTaskDelay(pdMS_TO_TICKS(5));
}
NimBLEDevice::deinit(true);
return true;
}
void setup() {
NODE_SERIAL_BEGIN();
#if BATTERY_NODE_DEBUG
delay(30);
#endif
initialiseRetainedState();
updateElapsedTimeSinceLastReport();
uint8_t currentPayload[SENSOR_DATA_LENGTH] = {};
if (!readSensorData(currentPayload)) {
NODE_PRINTLN("Sensor read failed; sleeping until next sample.");
retained.previousCycleActiveMs = millis();
sleepUntilNextSample();
}
const bool valueChanged = !retained.haveLastSentPayload ||
memcmp(currentPayload, retained.lastSentPayload, SENSOR_DATA_LENGTH) != 0;
const bool minIntervalElapsed =
retained.elapsedSinceReportMs >= MIN_REPORT_INTERVAL_MS;
const bool heartbeatDue =
retained.elapsedSinceReportMs >= HEARTBEAT_TRIGGER_MS;
const bool reportDue = minIntervalElapsed && (valueChanged || heartbeatDue);
if (!reportDue) {
retained.previousCycleActiveMs = millis();
sleepUntilNextSample();
}
const uint8_t sequence = retained.nextSequence;
uint32_t advertisingStartMs = 0;
const bool started = advertiseSensorData(currentPayload, sequence,
advertisingStartMs);
if (started) {
memcpy(retained.lastSentPayload, currentPayload, SENSOR_DATA_LENGTH);
retained.haveLastSentPayload = true;
retained.nextSequence = static_cast<uint8_t>(retained.nextSequence + 1);
retained.elapsedSinceReportMs = 0;
retained.previousCycleActiveMs = millis() - advertisingStartMs;
} else {
NODE_PRINTLN("BLE start failed; report remains pending.");
retained.previousCycleActiveMs = millis();
}
sleepUntilNextSample();
}
void loop() {
delay(1000);
}
[PacketFormat.h]
#pragma once
#include <stdint.h>
#include <stddef.h>
static constexpr uint16_t SENSOR_PACKET_MAGIC = 0xB17E;
static constexpr uint8_t SENSOR_NODE_ID = 0x01;
static constexpr uint16_t COMPANY_ID = 0xFFFF;
static constexpr size_t SENSOR_DATA_LENGTH = 4;
struct __attribute__((packed)) SensorPacket {
uint16_t magic;
uint8_t nodeId;
uint8_t sequence;
uint8_t payload[SENSOR_DATA_LENGTH];
};
static_assert(sizeof(SensorPacket) == 8, "SensorPacket must be exactly 8 bytes");
static constexpr size_t MANUFACTURER_DATA_LENGTH = 2 + sizeof(SensorPacket);
static_assert(MANUFACTURER_DATA_LENGTH == 10, "Unexpected manufacturer data size");
[esp32s3-Receiver.ino]
# ESP32-S3 Arduino BLE Advertising (1M PHY) with NimBLE Sketch
# Mains-Powered Receiver Node with Concurrent Wi-Fi
# by Gough Lui with debugging assistance from OpenAI ChatGPT GPT-6 Luna (Nov 2026)
# for My Project is Trash Design Challenge
#include <Arduino.h>
#include <WiFi.h>
#include <WebServer.h>
#include <NimBLEDevice.h>
#include <NimBLEScan.h>
#include <time.h>
#include <string>
#include <string.h>
#include <freertos/FreeRTOS.h>
#include <freertos/queue.h>
#include "PacketFormat.h"
#include "ReceiverConfig.h"
static WebServer webServer(80);
static NimBLEScan *bleScanner = nullptr;
struct ReceivedPacket {
SensorPacket packet;
int8_t rssi;
uint32_t receivedAtMs;
};
static QueueHandle_t receivedPacketQueue = nullptr;
struct ReceiverStatus {
bool havePacket = false;
uint8_t nodeId = 0;
uint8_t sequence = 0;
uint8_t payload[SENSOR_DATA_LENGTH] = {};
int8_t bleRssi = 0;
uint32_t lastReceiveMs = 0;
uint32_t uniquePackets = 0;
uint32_t duplicatePackets = 0;
};
static ReceiverStatus status;
static bool wifiWasConnected = false;
static bool ntpConfigured = false;
static constexpr uint32_t DUPLICATE_WINDOW_MS = 3000;
static constexpr size_t DUPLICATE_CACHE_SIZE = 12;
struct RecentPacket {
bool valid;
uint8_t nodeId;
uint8_t sequence;
uint8_t payload[SENSOR_DATA_LENGTH];
uint32_t receivedAtMs;
};
static RecentPacket recentPackets[DUPLICATE_CACHE_SIZE] = {};
static size_t nextRecentPacket = 0;
static bool clockIsSynchronized() {
return time(nullptr) >= 1704067200;
}
static void formatLocalTime(char *buffer, size_t length) {
if (!clockIsSynchronized()) {
snprintf(buffer, length, "Waiting for NTP synchronization");
return;
}
const time_t now = time(nullptr);
struct tm localInfo;
localtime_r(&now, &localInfo);
strftime(buffer, length, "%Y-%m-%d %H:%M:%S %Z", &localInfo);
}
static void serviceWiFi() {
const bool connected = WiFi.status() == WL_CONNECTED;
if (connected && !wifiWasConnected) {
wifiWasConnected = true;
Serial.println("Wi-Fi connected.");
Serial.print("Receiver webpage: http://");
Serial.println(WiFi.localIP());
if (!ntpConfigured) {
configTzTime(TIME_ZONE, NTP_SERVER_1, NTP_SERVER_2, NTP_SERVER_3);
ntpConfigured = true;
Serial.println("NTP synchronization configured.");
}
} else if (!connected && wifiWasConnected) {
wifiWasConnected = false;
Serial.println("Wi-Fi disconnected; automatic reconnect is enabled.");
}
}
class SensorScanCallbacks : public NimBLEScanCallbacks {
void onResult(const NimBLEAdvertisedDevice *device) override {
if (device == nullptr || !device->haveManufacturerData()) return;
const std::string data = device->getManufacturerData();
if (data.size() != MANUFACTURER_DATA_LENGTH) return;
const uint8_t *bytes = reinterpret_cast<const uint8_t *>(data.data());
const uint16_t companyId = static_cast<uint16_t>(bytes[0]) |
(static_cast<uint16_t>(bytes[1]) << 8);
if (companyId != COMPANY_ID) return;
ReceivedPacket received{};
memcpy(&received.packet, bytes + 2, sizeof(SensorPacket));
received.rssi = static_cast<int8_t>(device->getRSSI());
received.receivedAtMs = millis();
if (received.packet.magic != SENSOR_PACKET_MAGIC ||
received.packet.nodeId != SENSOR_NODE_ID) return;
if (receivedPacketQueue != nullptr) {
xQueueSend(receivedPacketQueue, &received, 0);
}
}
};
static SensorScanCallbacks scanCallbacks;
static bool isRecentDuplicate(const SensorPacket &packet, uint32_t nowMs) {
for (const RecentPacket &recent : recentPackets) {
if (!recent.valid || recent.nodeId != packet.nodeId) continue;
const bool recentEnough =
static_cast<uint32_t>(nowMs - recent.receivedAtMs) <= DUPLICATE_WINDOW_MS;
const bool samePacket = recent.sequence == packet.sequence &&
memcmp(recent.payload, packet.payload, SENSOR_DATA_LENGTH) == 0;
if (recentEnough && samePacket) return true;
}
return false;
}
static void rememberPacket(const SensorPacket &packet, uint32_t nowMs) {
RecentPacket &slot = recentPackets[nextRecentPacket];
slot.valid = true;
slot.nodeId = packet.nodeId;
slot.sequence = packet.sequence;
memcpy(slot.payload, packet.payload, SENSOR_DATA_LENGTH);
slot.receivedAtMs = nowMs;
nextRecentPacket = (nextRecentPacket + 1) % DUPLICATE_CACHE_SIZE;
}
static void printPacket(const ReceivedPacket &received) {
const SensorPacket &packet = received.packet;
Serial.println();
Serial.println("New sensor report:");
Serial.printf(" Node: 0x%02X Sequence: %u RSSI: %d dBm\n",
static_cast<unsigned>(packet.nodeId),
static_cast<unsigned>(packet.sequence),
static_cast<int>(received.rssi));
Serial.print(" Payload: ");
for (size_t i = 0; i < SENSOR_DATA_LENGTH; ++i) {
Serial.printf("%02X", static_cast<unsigned>(packet.payload[i]));
if (i + 1 < SENSOR_DATA_LENGTH) Serial.print(' ');
}
Serial.println();
}
static void processReceivedPackets() {
ReceivedPacket received{};
while (xQueueReceive(receivedPacketQueue, &received, 0) == pdTRUE) {
if (isRecentDuplicate(received.packet, received.receivedAtMs)) {
++status.duplicatePackets;
continue;
}
rememberPacket(received.packet, received.receivedAtMs);
status.havePacket = true;
status.nodeId = received.packet.nodeId;
status.sequence = received.packet.sequence;
memcpy(status.payload, received.packet.payload, SENSOR_DATA_LENGTH);
status.bleRssi = received.rssi;
status.lastReceiveMs = received.receivedAtMs;
++status.uniquePackets;
printPacket(received);
}
}
static const char MAIN_PAGE[] PROGMEM = R"HTML(
<!doctype html><html lang="en"><head>
<meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
<title>BLE Sensor Receiver</title>
<style>
body{font-family:system-ui,sans-serif;max-width:760px;margin:2rem auto;padding:0 1rem;color:#18212b;background:#f5f7fa}
h1{font-size:1.5rem}.panel{background:white;border:1px solid #d9e0e8;border-radius:12px;padding:1rem;margin:1rem 0}
.row{display:flex;justify-content:space-between;gap:1rem;padding:.45rem 0;border-bottom:1px solid #edf0f4}
.row:last-child{border:0}.key{color:#5b6674}code{word-break:break-all}
</style></head><body>
<h1>ESP32-S3 BLE Sensor Receiver</h1>
<div class="panel">
<div class="row"><span class="key">Wi-Fi</span><span id="wifi">Loading</span></div>
<div class="row"><span class="key">IP</span><span id="ip">-</span></div>
<div class="row"><span class="key">Wi-Fi RSSI</span><span id="wifiRssi">-</span></div>
<div class="row"><span class="key">Local time</span><span id="clock">-</span></div>
<div class="row"><span class="key">NTP</span><span id="ntp">-</span></div>
</div><div class="panel">
<div class="row"><span class="key">Unique packets</span><span id="unique">-</span></div>
<div class="row"><span class="key">Duplicates</span><span id="dupes">-</span></div>
<div class="row"><span class="key">Last packet age</span><span id="age">-</span></div>
<div class="row"><span class="key">Node ID</span><span id="node">-</span></div>
<div class="row"><span class="key">Sequence</span><span id="seq">-</span></div>
<div class="row"><span class="key">BLE RSSI</span><span id="bleRssi">-</span></div>
<div class="row"><span class="key">Sensor data</span><code id="payload">-</code></div>
</div><p>JSON: <a href="/api/status">/api/status</a></p>
<script>
async function update(){try{const r=await fetch('/api/status',{cache:'no-store'});const s=await r.json();
document.getElementById('wifi').textContent=s.wifiConnected?'Connected':'Disconnected';
document.getElementById('ip').textContent=s.ip;
document.getElementById('wifiRssi').textContent=s.wifiConnected?`${s.wifiRssi} dBm`:'-';
document.getElementById('clock').textContent=s.localTime;
document.getElementById('ntp').textContent=s.ntpSynchronized?'Synchronized':'Waiting';
document.getElementById('unique').textContent=s.uniquePackets;
document.getElementById('dupes').textContent=s.duplicatePackets;
document.getElementById('age').textContent=s.lastReceiveAgeMs===null?'Never':`${(s.lastReceiveAgeMs/1000).toFixed(1)} s`;
document.getElementById('node').textContent=s.havePacket?`0x${s.nodeId.toString(16).padStart(2,'0')}`:'-';
document.getElementById('seq').textContent=s.havePacket?s.sequence:'-';
document.getElementById('bleRssi').textContent=s.havePacket?`${s.bleRssi} dBm`:'-';
document.getElementById('payload').textContent=s.payload;
}catch(e){document.getElementById('wifi').textContent='Status request failed';}}
update();setInterval(update,5000);
</script></body></html>
)HTML";
static void handleRoot() {
webServer.send_P(200, "text/html; charset=utf-8", MAIN_PAGE);
}
static void handleStatusApi() {
char localTimeText[48];
char payloadHex[SENSOR_DATA_LENGTH * 2 + 1];
char ageText[24];
char json[640];
formatLocalTime(localTimeText, sizeof(localTimeText));
if (status.havePacket) {
for (size_t i = 0; i < SENSOR_DATA_LENGTH; ++i) {
snprintf(payloadHex + i * 2, 3, "%02X", static_cast<unsigned>(status.payload[i]));
}
snprintf(ageText, sizeof(ageText), "%lu",
static_cast<unsigned long>(millis() - status.lastReceiveMs));
} else {
strcpy(payloadHex, "No packet received yet");
strcpy(ageText, "null");
}
const bool wifiConnected = WiFi.status() == WL_CONNECTED;
const String ip = wifiConnected ? WiFi.localIP().toString() : String("-");
const int wifiRssi = wifiConnected ? WiFi.RSSI() : 0;
const time_t epoch = clockIsSynchronized() ? time(nullptr) : 0;
snprintf(json, sizeof(json),
"{\"wifiConnected\":%s,\"ip\":\"%s\",\"wifiRssi\":%d,"
"\"ntpSynchronized\":%s,\"epoch\":%lld,\"localTime\":\"%s\","
"\"uniquePackets\":%lu,\"duplicatePackets\":%lu,"
"\"havePacket\":%s,\"nodeId\":%u,\"sequence\":%u,\"bleRssi\":%d,"
"\"lastReceiveAgeMs\":%s,\"payload\":\"%s\"}",
wifiConnected ? "true" : "false", ip.c_str(), wifiRssi,
clockIsSynchronized() ? "true" : "false", static_cast<long long>(epoch),
localTimeText, static_cast<unsigned long>(status.uniquePackets),
static_cast<unsigned long>(status.duplicatePackets),
status.havePacket ? "true" : "false", static_cast<unsigned>(status.nodeId),
static_cast<unsigned>(status.sequence), static_cast<int>(status.bleRssi),
ageText, payloadHex);
webServer.send(200, "application/json", json);
}
static void startWebServer() {
webServer.on("/", HTTP_GET, handleRoot);
webServer.on("/api/status", HTTP_GET, handleStatusApi);
webServer.onNotFound([]() { webServer.send(404, "text/plain", "Not found"); });
webServer.begin();
Serial.println("HTTP server started on port 80.");
}
void setup() {
Serial.begin(115200);
delay(100);
Serial.println();
Serial.println("Always-powered ESP32-S3 receiver starting.");
receivedPacketQueue = xQueueCreate(24, sizeof(ReceivedPacket));
if (receivedPacketQueue == nullptr) {
Serial.println("Could not create receive queue.");
while (true) delay(1000);
}
WiFi.setHostname(WIFI_HOSTNAME);
WiFi.mode(WIFI_STA);
WiFi.setSleep(true);
WiFi.setAutoReconnect(true);
WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
Serial.printf("Connecting to Wi-Fi '%s'...\n", WIFI_SSID);
startWebServer();
NimBLEDevice::init("");
bleScanner = NimBLEDevice::getScan();
if (bleScanner == nullptr) {
Serial.println("Could not initialise BLE scanner.");
while (true) delay(1000);
}
bleScanner->setActiveScan(false);
bleScanner->setDuplicateFilter(0);
bleScanner->setMaxResults(0);
bleScanner->setScanCallbacks(&scanCallbacks, true);
if (!bleScanner->start(0, false, true)) {
Serial.println("Could not start continuous BLE scan.");
while (true) delay(1000);
}
Serial.println("Scanning for battery-node legacy BLE advertisements.");
}
void loop() {
webServer.handleClient();
serviceWiFi();
processReceivedPackets();
delay(2);
}
[ReceiverConfig.h]
#pragma once static constexpr char WIFI_SSID[] = "YOUR_SSID"; static constexpr char WIFI_PASSWORD[] = "YOUR_PASSWORD"; static constexpr char WIFI_HOSTNAME[] = "esp32-ble-receiver"; static constexpr char TIME_ZONE[] = "AEST-10AEDT,M10.1.0/2,M4.1.0/3"; static constexpr char NTP_SERVER_1[] = "pool.ntp.org"; static constexpr char NTP_SERVER_2[] = "time.google.com"; static constexpr char NTP_SERVER_3[] = "time.cloudflare.com";
It’s been set-up with Sydney, Australia as the time-zone for the NTP client, as that’s where I am, and the Wi-Fi credentials have been substituted with a placeholder. But as a “scaffold” for my future endeavours, it’s a promising start as I had no issues with loading the webpage and it was showing data updates just fine.

Changing the sketch to change the timings of packet sending to about 1/s, updating the Wi-Fi code to refresh once every 0.2s and adding a bit of Bluetooth traffic around (playing audio on my headset), I found that there’s occasional 3-4 seconds of lost data. This isn’t entirely unexpected because of the Wi-Fi coexistence which might take away time from the Bluetooth side just as an advertisement was being sent. Perhaps in my final implementation, I might just use Wi-Fi for a one-time NTP sync and turn it off, relying on a local LCD interface as the primary interface, or allow for Wi-Fi but use a non-auto-refreshing static page instead to minimise losses. But losses are indeed unavoidable, without adding yet another microcontroller/radio to the equation or perhaps without using a connection-oriented mode which would likely cause issues if the connection somehow “hangs” or gets stuck. Perhaps I could send data even more often (in terms of repetitions), at the cost of energy.

But this little raccoon wasn’t happy yet. Because it had to work from outside. I took a walk outside with the receiver attached to my phone running a terminal app, while the transmitter remained inside, for range testing.

At the ordinary location of my bin, I was receiving about -85dBm to -95dBm – right down at the border of what LE 1M can do. At that point, we were getting some burst losses and delivery was hardly assured. This would not do – if my bin got taken down the road even just a little, I’d lose visibility entirely! Or perhaps if enough microwaves came on at the same time, I might get a false alarm that my bin had gone AWOL … it seems I was right to expect that Coded PHY would be necessary. Or if I were to get a sledgehammer, perhaps I could even opt for LoRA, but it’s a bit late to make such major changes.
LE Coded PHY Support - Some Assembly Required
Having resigned myself to needing to rebuild the arduino-esp32 core, I started to prepare the necessary things, including Windows Subsystem for Linux and Ubuntu.

The build itself is orchestrated using esp32-arduino-lib-builder. While I started following its instructions, I quickly ran into issues with things that wouldn’t build together and became quickly lost.

After digging up fragments of instructions, I decided to feed them into ChatGPT and try to iron-out a working procedure to get a workable build. Turns out, the first step was simply to try and recreate the complete build chain for the 3.3.12 so that we can just transfer the built files to overwrite the existing tools.
Ultimately, the chain of commands was as follows (comments prefixed with #):
# Install prerequisites
sudo apt update
sudo apt install -y \
git wget curl build-essential \
flex bison gperf cmake ninja-build ccache jq \
libssl-dev libncurses-dev libffi-dev \
libusb-1.0-0 dfu-util \
python3 python3-pip python3-venv python3-setuptools
# Install the right version of the library builder
mkdir -p ~/src/arduino-esp32-build
cd ~/src/arduino-esp32-build
git clone https://github.com/espressif/esp32-arduino-lib-builder.git
cd esp32-arduino-lib-builder
git checkout 6671d0b
# Install ESP-IDF-5.5.5
export IDF_BRANCH=release/v5.5
export IDF_COMMIT=b774170ff46
if [ -n "${VIRTUAL_ENV:-}" ]; then
deactivate
fi
source ./tools/install-esp-idf.sh
python -m pip install setuptools pyserial click cryptography future pyparsing pyelftools
# Grab TinyUSB with patches
mkdir -p components/arduino_tinyusb
git clone https://github.com/hathach/tinyusb.git \
components/arduino_tinyusb/tinyusb
git -C components/arduino_tinyusb/tinyusb checkout 88c7f0b81
for patch in patches/tinyusb/*.diff; do
[ -e "$patch" ] || continue
git -C components/arduino_tinyusb/tinyusb apply "$PWD/$patch"
done
./tools/install-arduino.sh
git -C components/arduino fetch --all --tags
git -C components/arduino checkout e7c1e8cd4
From there, I needed to edit configs/defconfig.esp32s3 to add the following lines:
# NimBLE BLE 5 feature support CONFIG_BT_NIMBLE_50_FEATURE_SUPPORT=y CONFIG_BT_NIMBLE_LL_CFG_FEAT_LE_CODED_PHY=y # Bluetooth 5 extended advertising and scanning CONFIG_BT_NIMBLE_EXT_ADV=y CONFIG_BT_NIMBLE_EXT_SCAN=y # Wi-Fi / Bluetooth coexistence CONFIG_ESP_COEX_SW_COEXIST_ENABLE=y
Then, it was a case of running the build using the following command:
./build.sh -s -t esp32s3
This was not a quick operation – in all, I spent close to 15GB of bandwidth to download all the necessary files and the compilation took about an hour on my Intel Core i5-1135G7-based laptop.
Once the build succeeds, you’ll need to move /out/tools/esp32-arduino-libs/esp32s3 to C:\Users\[[USER PROFILE NAME]]\AppData\Local\Arduino15\packages\esp32\tools\esp32s3-libs\3.3.12
Of note is that once this updated version is installed, you’ll find that the previous sketch that doesn’t require extended advertising will fail to compile for ESP32-S3! Instead, you’ll have to go with extended advertising, but modify the PHY to be LE 1M instead, so this build isn’t exactly “universal”. If you’re using another chip instead of the ESP32-S3, then you’ll have to change the commands to correspond with your particular branch, noting that the original ESP32 cannot support extended advertising or Bluetooth v5.0 features.
Testing LE Coded PHY (S=8)
The code was revised a bit to match the NimBLE examples that feature Coded PHY extended advertising whilst keeping most of it the same. The new sketches are as follows:
[esp32s3-BatteryNodeCodedPhy.ino]
# ESP32-S3 Arduino BLE Advertising (LE Coded PHY) with NimBLE Sketch
# Battery-Operated Sensor Node
# by Gough Lui with debugging assistance from OpenAI ChatGPT GPT-6 Luna (Nov 2026)
# for My Project is Trash Design Challenge
#include <Arduino.h>
#include <NimBLEDevice.h>
#include <NimBLEExtAdvertising.h>
#include <esp_sleep.h>
#include <esp_attr.h>
#include <esp_system.h>
#include <freertos/FreeRTOS.h>
#include <freertos/task.h>
#include <string.h>
#include "PacketFormat.h"
static constexpr uint32_t SENSOR_SAMPLE_INTERVAL_MS = 1000;
static constexpr uint32_t MIN_REPORT_INTERVAL_MS = 1000;
static constexpr uint32_t HEARTBEAT_TRIGGER_MS = 12000;
static constexpr uint32_t BLE_ADV_INTERVAL_UNITS = 160;
static constexpr uint32_t BLE_ADV_DURATION_MS = 1200;
static constexpr int BLE_ADV_MAX_EVENTS = 3;
static constexpr uint32_t RTC_STATE_MAGIC = 0x534E4F44;
struct RetainedState {
uint32_t magic;
uint8_t lastSentPayload[SENSOR_DATA_LENGTH];
bool haveLastSentPayload;
uint8_t nextSequence;
uint32_t elapsedSinceReportMs;
uint32_t previousCycleActiveMs;
uint32_t demonstrationSampleCounter;
};
RTC_DATA_ATTR static RetainedState retained;
#define CODED_NODE_DEBUG 0
#if CODED_NODE_DEBUG
#define NODE_SERIAL_BEGIN() Serial.begin(115200)
#define NODE_PRINTLN(...) Serial.println(__VA_ARGS__)
#define NODE_PRINTF(...) Serial.printf(__VA_ARGS__)
#define NODE_FLUSH() Serial.flush()
#else
#define NODE_SERIAL_BEGIN() do {} while (0)
#define NODE_PRINTLN(...) do {} while (0)
#define NODE_PRINTF(...) do {} while (0)
#define NODE_FLUSH() do {} while (0)
#endif
static bool readSensorData(uint8_t output[SENSOR_DATA_LENGTH]) {
++retained.demonstrationSampleCounter;
const uint32_t exampleMeasurement = retained.demonstrationSampleCounter;
memcpy(output, &exampleMeasurement, sizeof(exampleMeasurement));
return true;
}
static void initialiseRetainedState() {
if (retained.magic == RTC_STATE_MAGIC) {
return;
}
memset(&retained, 0, sizeof(retained));
retained.magic = RTC_STATE_MAGIC;
retained.nextSequence = static_cast<uint8_t>(esp_random());
retained.haveLastSentPayload = false;
retained.elapsedSinceReportMs = HEARTBEAT_TRIGGER_MS;
}
static void updateElapsedTimeSinceLastReport() {
const uint64_t elapsed =
static_cast<uint64_t>(retained.elapsedSinceReportMs) +
retained.previousCycleActiveMs + SENSOR_SAMPLE_INTERVAL_MS;
retained.elapsedSinceReportMs = elapsed > UINT32_MAX
? UINT32_MAX
: static_cast<uint32_t>(elapsed);
}
static void sleepUntilNextSample() {
NODE_FLUSH();
esp_sleep_enable_timer_wakeup(
static_cast<uint64_t>(SENSOR_SAMPLE_INTERVAL_MS) * 1000ULL);
esp_deep_sleep_start();
while (true) {
delay(1000);
}
}
static bool advertiseSensorData(const uint8_t payload[SENSOR_DATA_LENGTH],
uint8_t sequence,
uint32_t &advertisingStartMs) {
SensorPacket packet{};
packet.magic = SENSOR_PACKET_MAGIC;
packet.nodeId = SENSOR_NODE_ID;
packet.sequence = sequence;
memcpy(packet.payload, payload, SENSOR_DATA_LENGTH);
uint8_t manufacturerData[MANUFACTURER_DATA_LENGTH];
manufacturerData[0] = static_cast<uint8_t>(COMPANY_ID & 0xFF);
manufacturerData[1] = static_cast<uint8_t>(COMPANY_ID >> 8);
memcpy(manufacturerData + 2, &packet, sizeof(packet));
if (!NimBLEDevice::init("")) {
return false;
}
NimBLEExtAdvertising *advertising = NimBLEDevice::getAdvertising();
if (advertising == nullptr) {
NimBLEDevice::deinit(true);
return false;
}
NimBLEExtAdvertisement advertisement(
BLE_HCI_LE_PHY_CODED,
BLE_HCI_LE_PHY_CODED
);
advertisement.setLegacyAdvertising(false);
advertisement.setConnectable(false);
advertisement.setScannable(false);
advertisement.setPrimaryChannels(true, true, true);
advertisement.setMinInterval(BLE_ADV_INTERVAL_UNITS);
advertisement.setMaxInterval(BLE_ADV_INTERVAL_UNITS);
advertisement.setTxPower(20);
if (!advertisement.setManufacturerData(manufacturerData,
sizeof(manufacturerData))) {
NimBLEDevice::deinit(true);
return false;
}
if (!advertising->setInstanceData(0, advertisement)) {
NimBLEDevice::deinit(true);
return false;
}
advertisingStartMs = millis();
if (!advertising->start(0, BLE_ADV_DURATION_MS, BLE_ADV_MAX_EVENTS)) {
NimBLEDevice::deinit(true);
return false;
}
NODE_PRINTF("Coded-PHY report started: node=0x%02X sequence=%u payload=",
static_cast<unsigned>(packet.nodeId),
static_cast<unsigned>(packet.sequence));
for (size_t i = 0; i < SENSOR_DATA_LENGTH; ++i) {
NODE_PRINTF("%02X", static_cast<unsigned>(packet.payload[i]));
}
NODE_PRINTLN();
while (advertising->isActive(0)) {
vTaskDelay(pdMS_TO_TICKS(5));
}
NimBLEDevice::deinit(true);
return true;
}
void setup() {
NODE_SERIAL_BEGIN();
#if CODED_NODE_DEBUG
delay(30);
#endif
initialiseRetainedState();
updateElapsedTimeSinceLastReport();
uint8_t currentPayload[SENSOR_DATA_LENGTH] = {};
if (!readSensorData(currentPayload)) {
NODE_PRINTLN("Sensor read failed; returning to deep sleep.");
retained.previousCycleActiveMs = millis();
sleepUntilNextSample();
}
const bool valueChanged = !retained.haveLastSentPayload ||
memcmp(currentPayload, retained.lastSentPayload,
SENSOR_DATA_LENGTH) != 0;
const bool minimumIntervalElapsed =
retained.elapsedSinceReportMs >= MIN_REPORT_INTERVAL_MS;
const bool heartbeatDue =
retained.elapsedSinceReportMs >= HEARTBEAT_TRIGGER_MS;
const bool reportDue = minimumIntervalElapsed &&
(valueChanged || heartbeatDue);
if (!reportDue) {
retained.previousCycleActiveMs = millis();
sleepUntilNextSample();
}
const uint8_t sequence = retained.nextSequence;
uint32_t advertisingStartMs = 0;
const bool advertised = advertiseSensorData(currentPayload, sequence,
advertisingStartMs);
if (advertised) {
memcpy(retained.lastSentPayload, currentPayload, SENSOR_DATA_LENGTH);
retained.haveLastSentPayload = true;
retained.nextSequence = static_cast<uint8_t>(retained.nextSequence + 1);
retained.elapsedSinceReportMs = 0;
retained.previousCycleActiveMs = millis() - advertisingStartMs;
} else {
NODE_PRINTLN("BLE advertising failed; keeping the report pending.");
retained.previousCycleActiveMs = millis();
}
sleepUntilNextSample();
}
void loop() {
delay(1000);
}
[esp32s3-Receiver.ino]
# ESP32-S3 Arduino BLE Advertising (LE Coded PHY) with NimBLE Sketch
# Mains-Powered Receiver Node with Concurrent Wi-Fi
# by Gough Lui with debugging assistance from OpenAI ChatGPT GPT-6 Luna (Nov 2026)
# for My Project is Trash Design Challenge
#include <Arduino.h>
#include <WiFi.h>
#include <WebServer.h>
#include <NimBLEDevice.h>
#include <NimBLEScan.h>
#include <time.h>
#include <string>
#include <string.h>
#include <freertos/FreeRTOS.h>
#include <freertos/queue.h>
#include "PacketFormat.h"
#include "ReceiverConfig.h"
static WebServer webServer(80);
static NimBLEScan *bleScanner = nullptr;
struct ReceivedPacket {
SensorPacket packet;
int8_t rssi;
uint8_t primaryPhy;
uint8_t secondaryPhy;
uint32_t receivedAtMs;
};
static QueueHandle_t receivedPacketQueue = nullptr;
struct ReceiverStatus {
bool havePacket = false;
uint8_t nodeId = 0;
uint8_t sequence = 0;
uint8_t payload[SENSOR_DATA_LENGTH] = {};
int8_t bleRssi = 0;
uint8_t primaryPhy = 0;
uint8_t secondaryPhy = 0;
uint32_t lastReceiveMs = 0;
uint32_t uniquePackets = 0;
uint32_t duplicatePackets = 0;
};
static ReceiverStatus status;
static bool wifiWasConnected = false;
static bool ntpConfigured = false;
static constexpr uint32_t DUPLICATE_WINDOW_MS = 3000;
static constexpr size_t DUPLICATE_CACHE_SIZE = 12;
struct RecentPacket {
bool valid;
uint8_t nodeId;
uint8_t sequence;
uint8_t payload[SENSOR_DATA_LENGTH];
uint32_t receivedAtMs;
};
static RecentPacket recentPackets[DUPLICATE_CACHE_SIZE] = {};
static size_t nextRecentPacket = 0;
static bool clockIsSynchronized() {
return time(nullptr) >= 1704067200;
}
static void formatLocalTime(char *buffer, size_t length) {
if (!clockIsSynchronized()) {
snprintf(buffer, length, "Waiting for NTP synchronization");
return;
}
const time_t now = time(nullptr);
struct tm localInfo;
localtime_r(&now, &localInfo);
strftime(buffer, length, "%Y-%m-%d %H:%M:%S %Z", &localInfo);
}
static void serviceWiFi() {
const bool connected = WiFi.status() == WL_CONNECTED;
if (connected && !wifiWasConnected) {
wifiWasConnected = true;
Serial.println("Wi-Fi connected.");
Serial.print("Receiver webpage: http://");
Serial.println(WiFi.localIP());
if (!ntpConfigured) {
configTzTime(TIME_ZONE, NTP_SERVER_1, NTP_SERVER_2, NTP_SERVER_3);
ntpConfigured = true;
Serial.println("NTP synchronization configured.");
}
} else if (!connected && wifiWasConnected) {
wifiWasConnected = false;
Serial.println("Wi-Fi disconnected; automatic reconnect remains enabled.");
}
}
class SensorScanCallbacks : public NimBLEScanCallbacks {
void onResult(const NimBLEAdvertisedDevice *device) override {
if (device == nullptr || !device->haveManufacturerData()) {
return;
}
const std::string manufacturerData = device->getManufacturerData();
if (manufacturerData.size() != MANUFACTURER_DATA_LENGTH) {
return;
}
const uint8_t *bytes =
reinterpret_cast<const uint8_t *>(manufacturerData.data());
const uint16_t companyId = static_cast<uint16_t>(bytes[0]) |
(static_cast<uint16_t>(bytes[1]) << 8);
if (companyId != COMPANY_ID) {
return;
}
ReceivedPacket received{};
memcpy(&received.packet, bytes + 2, sizeof(SensorPacket));
received.rssi = static_cast<int8_t>(device->getRSSI());
received.primaryPhy = device->getPrimaryPhy();
received.secondaryPhy = device->getSecondaryPhy();
received.receivedAtMs = millis();
if (received.packet.magic != SENSOR_PACKET_MAGIC ||
received.packet.nodeId != SENSOR_NODE_ID) {
return;
}
if (receivedPacketQueue != nullptr) {
xQueueSend(receivedPacketQueue, &received, 0);
}
}
};
static SensorScanCallbacks scanCallbacks;
static bool isRecentDuplicate(const SensorPacket &packet, uint32_t nowMs) {
for (const RecentPacket &recent : recentPackets) {
if (!recent.valid || recent.nodeId != packet.nodeId) {
continue;
}
const bool recentEnough =
static_cast<uint32_t>(nowMs - recent.receivedAtMs) <= DUPLICATE_WINDOW_MS;
const bool sameContents = recent.sequence == packet.sequence &&
memcmp(recent.payload, packet.payload, SENSOR_DATA_LENGTH) == 0;
if (recentEnough && sameContents) {
return true;
}
}
return false;
}
static void rememberPacket(const SensorPacket &packet, uint32_t nowMs) {
RecentPacket &slot = recentPackets[nextRecentPacket];
slot.valid = true;
slot.nodeId = packet.nodeId;
slot.sequence = packet.sequence;
memcpy(slot.payload, packet.payload, SENSOR_DATA_LENGTH);
slot.receivedAtMs = nowMs;
nextRecentPacket = (nextRecentPacket + 1) % DUPLICATE_CACHE_SIZE;
}
static void printPacket(const ReceivedPacket &received) {
const SensorPacket &packet = received.packet;
Serial.println();
Serial.println("New Coded-PHY sensor report:");
Serial.printf(" Node ID: 0x%02X Sequence: %u RSSI: %d dBm\n",
static_cast<unsigned>(packet.nodeId),
static_cast<unsigned>(packet.sequence),
static_cast<int>(received.rssi));
Serial.printf(" Advertising PHY: primary=%u secondary=%u (3 = LE Coded)\n",
static_cast<unsigned>(received.primaryPhy),
static_cast<unsigned>(received.secondaryPhy));
Serial.print(" Payload: ");
for (size_t i = 0; i < SENSOR_DATA_LENGTH; ++i) {
Serial.printf("%02X", static_cast<unsigned>(packet.payload[i]));
if (i + 1 < SENSOR_DATA_LENGTH) Serial.print(' ');
}
Serial.println();
}
static void processReceivedPackets() {
ReceivedPacket received{};
while (xQueueReceive(receivedPacketQueue, &received, 0) == pdTRUE) {
if (isRecentDuplicate(received.packet, received.receivedAtMs)) {
++status.duplicatePackets;
continue;
}
rememberPacket(received.packet, received.receivedAtMs);
status.havePacket = true;
status.nodeId = received.packet.nodeId;
status.sequence = received.packet.sequence;
memcpy(status.payload, received.packet.payload, SENSOR_DATA_LENGTH);
status.bleRssi = received.rssi;
status.primaryPhy = received.primaryPhy;
status.secondaryPhy = received.secondaryPhy;
status.lastReceiveMs = received.receivedAtMs;
++status.uniquePackets;
printPacket(received);
}
}
static const char MAIN_PAGE[] PROGMEM = R"HTML(
<!doctype html><html lang="en"><head>
<meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
<title>ESP32-S3 Coded-PHY Receiver</title>
<style>
body{font-family:system-ui,sans-serif;max-width:760px;margin:2rem auto;padding:0 1rem;color:#18212b;background:#f5f7fa}
h1{font-size:1.5rem}.panel{background:white;border:1px solid #d9e0e8;border-radius:12px;padding:1rem;margin:1rem 0}
.row{display:flex;justify-content:space-between;gap:1rem;padding:.45rem 0;border-bottom:1px solid #edf0f4}
.row:last-child{border:0}.key{color:#5b6674}code{word-break:break-all}
</style></head><body>
<h1>ESP32-S3 BLE Coded-PHY Receiver</h1>
<div class="panel">
<div class="row"><span class="key">Wi-Fi</span><span id="wifi">Loading</span></div>
<div class="row"><span class="key">IP address</span><span id="ip">-</span></div>
<div class="row"><span class="key">Wi-Fi RSSI</span><span id="wifiRssi">-</span></div>
<div class="row"><span class="key">Local time</span><span id="clock">-</span></div>
<div class="row"><span class="key">NTP</span><span id="ntp">-</span></div>
</div><div class="panel">
<div class="row"><span class="key">Unique reports</span><span id="unique">-</span></div>
<div class="row"><span class="key">Duplicate advertisements</span><span id="dupes">-</span></div>
<div class="row"><span class="key">Last report age</span><span id="age">-</span></div>
<div class="row"><span class="key">Node ID</span><span id="node">-</span></div>
<div class="row"><span class="key">Sequence</span><span id="seq">-</span></div>
<div class="row"><span class="key">BLE RSSI</span><span id="bleRssi">-</span></div>
<div class="row"><span class="key">Sensor data</span><code id="payload">-</code></div>
</div><p>JSON endpoint: <a href="/api/status">/api/status</a></p>
<script>
async function update(){try{const r=await fetch('/api/status',{cache:'no-store'});const s=await r.json();
document.getElementById('wifi').textContent=s.wifiConnected?'Connected':'Disconnected';
document.getElementById('ip').textContent=s.ip;
document.getElementById('wifiRssi').textContent=s.wifiConnected?`${s.wifiRssi} dBm`:'-';
document.getElementById('clock').textContent=s.localTime;
document.getElementById('ntp').textContent=s.ntpSynchronized?'Synchronized':'Waiting';
document.getElementById('unique').textContent=s.uniquePackets;
document.getElementById('dupes').textContent=s.duplicatePackets;
document.getElementById('age').textContent=s.lastReceiveAgeMs===null?'Never':`${(s.lastReceiveAgeMs/1000).toFixed(1)} s`;
document.getElementById('node').textContent=s.havePacket?`0x${s.nodeId.toString(16).padStart(2,'0')}`:'-';
document.getElementById('seq').textContent=s.havePacket?s.sequence:'-';
document.getElementById('bleRssi').textContent=s.havePacket?`${s.bleRssi} dBm`:'-';
document.getElementById('payload').textContent=s.payload;
}catch(e){document.getElementById('wifi').textContent='Status request failed';}}
update();setInterval(update,5000);
</script></body></html>
)HTML";
static void handleRoot() {
webServer.send_P(200, "text/html; charset=utf-8", MAIN_PAGE);
}
static void handleStatusApi() {
char localTimeText[48];
char payloadHex[SENSOR_DATA_LENGTH * 2 + 1];
char ageText[24];
char json[640];
formatLocalTime(localTimeText, sizeof(localTimeText));
if (status.havePacket) {
for (size_t i = 0; i < SENSOR_DATA_LENGTH; ++i) {
snprintf(payloadHex + i * 2, 3, "%02X",
static_cast<unsigned>(status.payload[i]));
}
snprintf(ageText, sizeof(ageText), "%lu",
static_cast<unsigned long>(millis() - status.lastReceiveMs));
} else {
strcpy(payloadHex, "No packet received yet");
strcpy(ageText, "null");
}
const bool wifiConnected = WiFi.status() == WL_CONNECTED;
const String ip = wifiConnected ? WiFi.localIP().toString() : String("-");
const int wifiRssi = wifiConnected ? WiFi.RSSI() : 0;
const time_t epoch = clockIsSynchronized() ? time(nullptr) : 0;
snprintf(json, sizeof(json),
"{\"wifiConnected\":%s,\"ip\":\"%s\",\"wifiRssi\":%d,"
"\"ntpSynchronized\":%s,\"epoch\":%lld,\"localTime\":\"%s\","
"\"uniquePackets\":%lu,\"duplicatePackets\":%lu,"
"\"havePacket\":%s,\"nodeId\":%u,\"sequence\":%u,\"bleRssi\":%d,"
"\"lastReceiveAgeMs\":%s,\"payload\":\"%s\"}",
wifiConnected ? "true" : "false", ip.c_str(), wifiRssi,
clockIsSynchronized() ? "true" : "false", static_cast<long long>(epoch),
localTimeText, static_cast<unsigned long>(status.uniquePackets),
static_cast<unsigned long>(status.duplicatePackets),
status.havePacket ? "true" : "false", static_cast<unsigned>(status.nodeId),
static_cast<unsigned>(status.sequence), static_cast<int>(status.bleRssi),
ageText, payloadHex);
webServer.send(200, "application/json", json);
}
static void startWebServer() {
webServer.on("/", HTTP_GET, handleRoot);
webServer.on("/api/status", HTTP_GET, handleStatusApi);
webServer.onNotFound([]() {
webServer.send(404, "text/plain", "Not found");
});
webServer.begin();
Serial.println("HTTP server started on port 80.");
}
void setup() {
Serial.begin(115200);
delay(100);
Serial.println();
Serial.println("Always-powered ESP32-S3 Coded-PHY receiver starting.");
receivedPacketQueue = xQueueCreate(24, sizeof(ReceivedPacket));
if (receivedPacketQueue == nullptr) {
Serial.println("Could not create BLE receive queue.");
while (true) delay(1000);
}
WiFi.setHostname(WIFI_HOSTNAME);
WiFi.mode(WIFI_STA);
WiFi.setSleep(true);
WiFi.setAutoReconnect(true);
WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
Serial.printf("Connecting to Wi-Fi '%s'...\n", WIFI_SSID);
startWebServer();
if (!NimBLEDevice::init("")) {
Serial.println("Could not initialise NimBLE.");
while (true) delay(1000);
}
bleScanner = NimBLEDevice::getScan();
if (bleScanner == nullptr) {
Serial.println("Could not obtain BLE scanner.");
while (true) delay(1000);
}
bleScanner->setPhy(NimBLEScan::Phy::SCAN_CODED);
bleScanner->setActiveScan(false);
bleScanner->setDuplicateFilter(0);
bleScanner->setMaxResults(0);
bleScanner->setInterval(1000);
bleScanner->setWindow(1000);
bleScanner->setScanCallbacks(&scanCallbacks, true);
if (!bleScanner->start(0, false, true)) {
Serial.println("Could not start continuous Coded-PHY scanning.");
while (true) delay(1000);
}
Serial.println("Scanning continuously on LE Coded PHY (S=8 advertising expected).");
}
void loop() {
webServer.handleClient();
serviceWiFi();
processReceivedPackets();
delay(2);
}
But while I was sure the code was right, NimBLE wasn’t quite playing ball. While compiling it, I was coming to a few compiler errors that were NimBLE-related:
I'm now receiving the following errors instead:
[...]Arduino\libraries\NimBLE-Arduino\src\nimble\nimble\host\src\ble_gap.c: In function 'ble_gap_rx_periodic_adv_sync_transfer':
[...]Arduino\libraries\NimBLE-Arduino\src\nimble\nimble\host\src\ble_gap.c:2357:23: error: 'struct ble_hs_conn' has no member named 'psync'
2357 | if (!conn || !conn->psync) {
| ^~
[...]Arduino\libraries\NimBLE-Arduino\src\nimble\nimble\host\src\ble_gap.c:2369:14: error: 'struct ble_hs_conn' has no member named 'psync'
2369 | cb = conn->psync->cb;
| ^~
[...]Arduino\libraries\NimBLE-Arduino\src\nimble\nimble\host\src\ble_gap.c:2370:18: error: 'struct ble_hs_conn' has no member named 'psync'
2370 | cb_arg = conn->psync->cb_arg;
| ^~
[...]Arduino\libraries\NimBLE-Arduino\src\nimble\nimble\host\src\ble_gap.c:2384:39: error: 'struct ble_hs_conn' has no member named 'psync'
2384 | ble_hs_periodic_sync_free(conn->psync);
| ^~
[...]Arduino\libraries\NimBLE-Arduino\src\nimble\nimble\host\src\ble_gap.c:2388:13: error: 'struct ble_hs_conn' has no member named 'psync'
2388 | conn->psync->sync_handle = sync_handle;
| ^~
[...]Arduino\libraries\NimBLE-Arduino\src\nimble\nimble\host\src\ble_gap.c:2389:13: error: 'struct ble_hs_conn' has no member named 'psync'
2389 | conn->psync->adv_sid = ev->sid;
| ^~
[...]Arduino\libraries\NimBLE-Arduino\src\nimble\nimble\host\src\ble_gap.c:2390:20: error: 'struct ble_hs_conn' has no member named 'psync'
2390 | memcpy(conn->psync->advertiser_addr.val, ev->peer_addr, 6);
| ^~
[...]Arduino\libraries\NimBLE-Arduino\src\nimble\nimble\host\src\ble_gap.c:2391:13: error: 'struct ble_hs_conn' has no member named 'psync'
2391 | conn->psync->advertiser_addr.type = ev->peer_addr_type;
| ^~
[...]Arduino\libraries\NimBLE-Arduino\src\nimble\nimble\host\src\ble_gap.c:2392:41: error: 'struct ble_hs_conn' has no member named 'psync'
2392 | ble_hs_periodic_sync_insert(conn->psync);
| ^~
[...]Arduino\libraries\NimBLE-Arduino\src\nimble\nimble\host\src\ble_gap.c:2395:9: error: 'struct ble_hs_conn' has no member named 'psync'
2395 | conn->psync = NULL;
| ^~
[...]Arduino\libraries\NimBLE-Arduino\src\nimble\nimble\host\src\ble_hs_atomic.c: In function 'ble_hs_atomic_conn_delete':
[...]Arduino\libraries\NimBLE-Arduino\src\nimble\nimble\host\src\ble_hs_atomic.c:32:17: error: 'struct ble_hs_conn' has no member named 'psync'
32 | if (conn->psync) {
| ^~
[...]Arduino\libraries\NimBLE-Arduino\src\nimble\nimble\host\src\ble_hs_atomic.c:33:43: error: 'struct ble_hs_conn' has no member named 'psync'
33 | ble_hs_periodic_sync_free(conn->psync);
| ^~
exit status 1
Compilation error: exit status 1
I certainly was completely out of my depth. Having spent the better part of a day on this problem with over an hour of compile time to rebuild the board support, I wasn’t going to give up. But I did have to give in and ask an AI for help.
Turns out, ChatGPT confirmed it was a problem with NimBLE’s code and suggested workarounds to disable features that weren’t used such that the project could build by avoiding the “broken” code-paths. The fix was to make a change to the first few lines of nimconfig.h in the library folders:
#ifdef ESP_PLATFORM # include <sdkconfig.h> // Project-specific NimBLE configuration overrides. // These must appear AFTER sdkconfig.h is included. #undef CONFIG_BT_NIMBLE_ENABLE_PERIODIC_ADV #define CONFIG_BT_NIMBLE_ENABLE_PERIODIC_ADV 0 #undef CONFIG_BT_NIMBLE_PERIODIC_ADV_SYNC_TRANSFER #define CONFIG_BT_NIMBLE_PERIODIC_ADV_SYNC_TRANSFER 0 # include <esp_idf_version.h>
Having understood what it was trying to do, with a hope and a prayer, the project actually compiled and started working. This tired raccoon went back outside …

This time, I could make it to one or two houses either side of mine … the signal at the point of dropping out was around -99dBm to -104dBm which is pretty much all the gain we were promised from going to Coded PHY.

Checking with nRF Connect on the phone also confirmed that the devices were emitting extended advertising in LE Coded PHY mode – so it’s not simply a case of it building and not fixing the problem. Jackpot! While I did set the power up to +20dBm (according to the datasheet, it should be capable of this), I didn’t see any change in strengths. Other sources suggest that only +13dBm is available, so perhaps I should try that to eke out as much range as I can.
With minor tweaks - advertising six packets in a row instead of three, I'm seeing a no-loss-rate of 97.3%, with the remaining instances involving the loss of just one report over a span of about half-an-hour and that's without tweaking the Wi-Fi settings. That's not half bad, but it is at the bench ... on the road will be a bit more demanding.
Conclusion
When it comes to connectivity, my original hunch that BLE Coded PHY would be needed has proven true. But I was naïve when I chose the ESP32-S3 because it had hardware support for Bluetooth v5.0 including Coded PHY – the software, at least when it comes to Arduino, was not quite ready for out-of-the-box action. This resulted in a painful experience trying to get everything set-up just right – something I would have found exceptionally difficult to overcome without the assistance of AI as the issues often cropped up when building without using exactly the right commit, and even then, NimBLE would also have issues with its own library when some of those extensions were turned on.
That being said, after I completed this journey, I found out that arduino-esp32 has just released a v4.0.0 release that hasn’t hit the board manager URL yet. This major release has some breaking changes which are yet to be fully documented, but apparently, the blog suggests it already has all the changes for extended advertising and Coded PHY support baked in! You can imagine just how frustrated this raccoon was to find that out … after battling with this for the better part of half a week!

But that’s fine. Those dark circles around my eyes only make me more like a raccoon. Look like a raccoon. Think like a raccoon. Be THE raccoon!
AI Disclosure: AI has been used in the generation of a number of images in this post which involve raccoons. AI has not been used to generate or modify any of the text or photographs of products and electronic items. AI has been used to assist with software build errors with third-party libraries, with minor sketch code modifications and debugging.