Got interested in how to solve the problem of determining which Student remote pressed the button first and decided to test my solution of having a local time beacon... sort of like WWV where all the remotes could synchronize their local time bases to a standard.
The setup is a Seeed XIAO ESP32-C6 programmed to transmit over ESPNOW channel 6 a #of_microseconds and sequence# every second. The Student remotes continually receive this signal and use it to synchronize a local timestamp. When a Student presses a button, the event is time-stamped and a Teacher unit can poll all the students to determine which one actually pressed their button first.
You can see that network Beacon Time is backed into by adding Elapsed since beacon + Network button time.
My reason for doing this was threefold. I hadn't used AI to write a sketch before and wanted to see how practical it is to have a design chat with AI to develop a workable solution. Second, I have just started using the Seeed XIAO modules and wanted to have an actual project rather than just running the examples. Third I was curious how easy it was going to be to determine when an event happened with only a wireless connection as opposed to using hardwired switches.
Time Beacon
/*
ESP-NOW time beacon for a Seeed Studio XIAO ESP32-C6.
Once per second this sketch broadcasts:
- a beacon sequence number
- the master's esp_timer_get_time() value in microseconds
Use with ESPNow_Time_Client.ino. Both boards must use the same
ESPNOW_CHANNEL value.
Target: Arduino-ESP32 core 3.x, board "XIAO_ESP32C6".
*/
#include <Arduino.h>
#include <WiFi.h>
#include <esp_now.h>
#include <esp_timer.h>
#include <esp_wifi.h>
#include <inttypes.h>
namespace {
constexpr uint8_t ESPNOW_CHANNEL = 6;
constexpr int64_t BEACON_PERIOD_US = 1000000LL;
constexpr uint32_t PACKET_MAGIC = 0x54494D45UL; // ASCII "TIME"
constexpr uint8_t PROTOCOL_VERSION = 1;
constexpr uint8_t PACKET_TYPE_BEACON = 1;
const uint8_t BROADCAST_ADDRESS[ESP_NOW_ETH_ALEN] = {
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF};
struct __attribute__((packed)) TimeBeacon {
uint32_t magic;
uint8_t version;
uint8_t packetType;
uint16_t packetSize;
uint32_t sequence;
int64_t masterTimeUs;
};
static_assert(sizeof(TimeBeacon) == 20, "Unexpected TimeBeacon size");
uint32_t beaconSequence = 0;
int64_t nextBeaconUs = 0;
void stopWithError(const char *message, esp_err_t error) {
Serial.printf("%s: %s (%d)\n", message, esp_err_to_name(error), error);
while (true) {
delay(1000);
}
}
void initializeEspNow() {
WiFi.mode(WIFI_STA);
WiFi.disconnect();
delay(100);
esp_err_t error =
esp_wifi_set_channel(ESPNOW_CHANNEL, WIFI_SECOND_CHAN_NONE);
if (error != ESP_OK) {
stopWithError("Could not set the Wi-Fi channel", error);
}
error = esp_now_init();
if (error != ESP_OK) {
stopWithError("Could not initialize ESP-NOW", error);
}
esp_now_peer_info_t broadcastPeer = {};
memcpy(broadcastPeer.peer_addr, BROADCAST_ADDRESS, ESP_NOW_ETH_ALEN);
broadcastPeer.channel = ESPNOW_CHANNEL;
broadcastPeer.ifidx = WIFI_IF_STA;
broadcastPeer.encrypt = false;
error = esp_now_add_peer(&broadcastPeer);
if (error != ESP_OK && error != ESP_ERR_ESPNOW_EXIST) {
stopWithError("Could not add the broadcast peer", error);
}
}
void sendTimeBeacon() {
TimeBeacon beacon = {};
beacon.magic = PACKET_MAGIC;
beacon.version = PROTOCOL_VERSION;
beacon.packetType = PACKET_TYPE_BEACON;
beacon.packetSize = sizeof(beacon);
beacon.sequence = ++beaconSequence;
// Take this timestamp as close as possible to esp_now_send(). The delay
// between this statement and actual RF transmission is approximately
// common to every client that receives this particular beacon.
beacon.masterTimeUs = esp_timer_get_time();
const esp_err_t error = esp_now_send(
BROADCAST_ADDRESS, reinterpret_cast<const uint8_t *>(&beacon),
sizeof(beacon));
if (error == ESP_OK) {
Serial.printf("Beacon %" PRIu32 ", master time %" PRId64 " us\n",
beacon.sequence, beacon.masterTimeUs);
} else {
Serial.printf("Beacon send failed: %s (%d)\n", esp_err_to_name(error),
error);
}
}
} // namespace
void setup() {
Serial.begin(115200);
const uint32_t serialWaitStarted = millis();
while (!Serial && millis() - serialWaitStarted < 3000) {
delay(10);
} // seems like a hack but AI swears blind all the cool kids are doing it
Serial.println();
Serial.println("ESP-NOW time beacon");
initializeEspNow();
Serial.printf("Station MAC: %s\n", WiFi.macAddress().c_str());
Serial.printf("ESP-NOW channel: %u\n", ESPNOW_CHANNEL);
// Send the first beacon promptly. Subsequent deadlines remain exactly one
// second apart rather than accumulating loop timing error.
nextBeaconUs = esp_timer_get_time() + 100000LL;
}
void loop() {
const int64_t nowUs = esp_timer_get_time();
if (nowUs >= nextBeaconUs) {
sendTimeBeacon();
do {
nextBeaconUs += BEACON_PERIOD_US;
} while (nextBeaconUs <= nowUs);
}
delay(1);
}
Time Client
/*
ESP-NOW time-beacon client for a Seeed Studio XIAO ESP32-C6.
Connect a normally-open pushbutton between XIAO pin D1 (GPIO1) and GND.
The internal pull-up is enabled. The first falling edge is timestamped;
switch debounce is performed afterward without changing that timestamp.
The Serial Monitor prints the button time expressed in the master's time
domain. This first experiment does not transmit the result back to the
master; polling can be added after synchronization has been characterized.
Target: Arduino-ESP32 core 3.x, board "XIAO_ESP32C6".
*/
#include <Arduino.h>
#include <WiFi.h>
#include <esp_now.h>
#include <esp_timer.h>
#include <esp_wifi.h>
#include <inttypes.h>
namespace {
constexpr uint8_t ESPNOW_CHANNEL = 6;
constexpr uint8_t BUTTON_PIN = D1; // XIAO ESP32-C6 D1 is GPIO1.
constexpr uint32_t RELEASE_DEBOUNCE_MS = 30;
constexpr uint32_t PACKET_MAGIC = 0x54494D45UL; // ASCII "TIME"
constexpr uint8_t PROTOCOL_VERSION = 1;
constexpr uint8_t PACKET_TYPE_BEACON = 1;
struct __attribute__((packed)) TimeBeacon {
uint32_t magic;
uint8_t version;
uint8_t packetType;
uint16_t packetSize;
uint32_t sequence;
int64_t masterTimeUs;
};
static_assert(sizeof(TimeBeacon) == 20, "Unexpected TimeBeacon size");
portMUX_TYPE timeMux = portMUX_INITIALIZER_UNLOCKED;
// Latest synchronization anchor. All 64-bit values are protected by timeMux
// because a 64-bit read/write need not be atomic on this processor.
volatile bool beaconValid = false;
volatile bool beaconPrintPending = false;
volatile uint32_t beaconSequence = 0;
volatile int64_t beaconMasterUs = 0;
volatile int64_t beaconLocalUs = 0;
// A button event includes a copy of the synchronization anchor that was valid
// at the instant of the press. A later beacon therefore cannot alter the event.
volatile bool pressLatched = false;
volatile bool pressPrintPending = false;
volatile uint32_t pressBeaconSequence = 0;
volatile int64_t pressLocalUs = 0;
volatile int64_t pressAnchorMasterUs = 0;
volatile int64_t pressAnchorLocalUs = 0;
void stopWithError(const char *message, esp_err_t error) {
Serial.printf("%s: %s (%d)\n", message, esp_err_to_name(error), error);
while (true) {
delay(1000);
}
}
// Arduino-ESP32 core 3.x receive callback. Record local reception time before
// validating or copying the packet so software work does not add to the anchor.
void onEspNowReceive(const esp_now_recv_info_t *info, const uint8_t *data,
int length) {
const int64_t localReceiveUs = esp_timer_get_time();
(void)info;
if (length != static_cast<int>(sizeof(TimeBeacon))) {
return;
}
TimeBeacon beacon;
memcpy(&beacon, data, sizeof(beacon));
if (beacon.magic != PACKET_MAGIC ||
beacon.version != PROTOCOL_VERSION ||
beacon.packetType != PACKET_TYPE_BEACON ||
beacon.packetSize != sizeof(TimeBeacon)) {
return;
}
portENTER_CRITICAL(&timeMux);
beaconSequence = beacon.sequence;
beaconMasterUs = beacon.masterTimeUs;
beaconLocalUs = localReceiveUs;
beaconValid = true;
beaconPrintPending = true;
portEXIT_CRITICAL(&timeMux);
}
void ARDUINO_ISR_ATTR onButtonFalling() {
const int64_t localPressUs = esp_timer_get_time();
portENTER_CRITICAL_ISR(&timeMux);
if (beaconValid && !pressLatched) {
pressLocalUs = localPressUs;
pressBeaconSequence = beaconSequence;
pressAnchorMasterUs = beaconMasterUs;
pressAnchorLocalUs = beaconLocalUs;
pressLatched = true;
pressPrintPending = true;
}
portEXIT_CRITICAL_ISR(&timeMux);
}
void initializeEspNow() {
WiFi.mode(WIFI_STA);
WiFi.disconnect();
delay(100);
esp_err_t error =
esp_wifi_set_channel(ESPNOW_CHANNEL, WIFI_SECOND_CHAN_NONE);
if (error != ESP_OK) {
stopWithError("Could not set the Wi-Fi channel", error);
}
error = esp_now_init();
if (error != ESP_OK) {
stopWithError("Could not initialize ESP-NOW", error);
}
error = esp_now_register_recv_cb(onEspNowReceive);
if (error != ESP_OK) {
stopWithError("Could not register the ESP-NOW receive callback", error);
}
}
void printPendingBeacon() {
bool shouldPrint = false;
uint32_t sequence = 0;
int64_t masterUs = 0;
int64_t localUs = 0;
portENTER_CRITICAL(&timeMux);
if (beaconPrintPending) {
shouldPrint = true;
sequence = beaconSequence;
masterUs = beaconMasterUs;
localUs = beaconLocalUs;
beaconPrintPending = false;
}
portEXIT_CRITICAL(&timeMux);
if (shouldPrint) {
Serial.printf("Beacon %" PRIu32 ": master=%" PRId64
" us, localRx=%" PRId64 ", offset=%" PRId64 " us\n",
sequence, masterUs, localUs, masterUs - localUs);
}
}
void printPendingPress() {
bool shouldPrint = false;
uint32_t sequence = 0;
int64_t localUs = 0;
int64_t anchorMasterUs = 0;
int64_t anchorLocalUs = 0;
portENTER_CRITICAL(&timeMux);
if (pressPrintPending) {
shouldPrint = true;
sequence = pressBeaconSequence;
localUs = pressLocalUs;
anchorMasterUs = pressAnchorMasterUs;
anchorLocalUs = pressAnchorLocalUs;
pressPrintPending = false;
}
portEXIT_CRITICAL(&timeMux);
if (shouldPrint) {
const int64_t elapsedSinceBeaconUs = localUs - anchorLocalUs;
const int64_t networkButtonTimeUs =
anchorMasterUs + elapsedSinceBeaconUs;
Serial.println();
Serial.println("BUTTON PRESSED");
Serial.printf(" Beacon sequence: %" PRIu32 "\n", sequence);
Serial.printf(" Elapsed since beacon: %" PRId64 " us\n",
elapsedSinceBeaconUs);
Serial.printf(" Network button time: %" PRId64 " us\n",
networkButtonTimeUs);
}
}
void rearmButtonAfterRelease() {
static uint32_t releaseStartedMs = 0;
bool isLatched;
portENTER_CRITICAL(&timeMux);
isLatched = pressLatched;
portEXIT_CRITICAL(&timeMux);
if (!isLatched) {
releaseStartedMs = 0;
return;
}
if (digitalRead(BUTTON_PIN) == LOW) {
releaseStartedMs = 0;
return;
}
if (releaseStartedMs == 0) {
releaseStartedMs = millis();
return;
}
if (millis() - releaseStartedMs >= RELEASE_DEBOUNCE_MS) {
portENTER_CRITICAL(&timeMux);
pressLatched = false;
portEXIT_CRITICAL(&timeMux);
releaseStartedMs = 0;
Serial.println("Button released and rearmed.");
}
}
} // namespace
void setup() {
Serial.begin(115200);
const uint32_t serialWaitStarted = millis();
while (!Serial && millis() - serialWaitStarted < 3000) {
delay(10);
}
Serial.println();
Serial.println("ESP-NOW time client");
pinMode(BUTTON_PIN, INPUT_PULLUP);
attachInterrupt(digitalPinToInterrupt(BUTTON_PIN), onButtonFalling, FALLING);
initializeEspNow();
Serial.printf("Station MAC: %s\n", WiFi.macAddress().c_str());
Serial.printf("ESP-NOW channel: %u\n", ESPNOW_CHANNEL);
Serial.printf("Button: XIAO D1 / GPIO%u to GND\n", BUTTON_PIN);
Serial.println("Waiting for time beacons...");
}
void loop() {
printPendingBeacon();
printPendingPress();
rearmButtonAfterRelease();
delay(1);
}