ESP_Mesh_Radio_Light.ino · ESP8266 / ESP32 · flash to every board
/*
* ============================================================
* ESP MESH — REAL FIRMWARE
* Custom radio + light-based communication.
* Runs on ESP8266, ESP32, ESP32-S2/S3/C3, and future ESPs.
*
* NO Wi-Fi. NO internet. NO router. NO access point.
*
* Every ESP:
* - broadcasts small packets over raw 2.4 GHz radio
* (ESP-NOW, no association, no IP)
* - simultaneously pulses an LED / IR emitter / laser
* for VLC-style line-of-sight data (OOK, Manchester)
* - listens on both media, merges duplicates,
* and forwards packets across a self-healing mesh
*
* Each board is a router. Packets hop:
* ESP_A -> ESP_B -> ESP_C -> ... -> destination
*
* Flash this to EVERY ESP. Change NODE_ID per board.
* They auto-discover, auto-route, auto-heal. Nothing else.
* ============================================================
*/
// ------------------------------------------------------------
// SELECT YOUR BOARD: uncomment ONE of the two lines below
// ------------------------------------------------------------
#define ESP8266_BOARD // <-- uncomment for ESP8266
// #define ESP32_BOARD // <-- uncomment for ESP32 / S2 / S3 / C3
#ifdef ESP8266_BOARD
#include <ESP8266WiFi.h>
#include <espnow.h>
#define ESP_NOW_SEND(mac, data, len) esp_now_send(mac, data, len)
#define RADIO_INIT() esp_now_init()
#define RADIO_REGISTER_CB(cb) esp_now_register_recv_cb(cb)
#define RADIO_ADD_BROADCAST() esp_now_add_peer((uint8_t*"\xFF\xFF\xFF\xFF\xFF\xFF"), ESP_NOW_ROLE_COMBO, 6, NULL, 0)
#define WIFI_OFF() wifi_set_opmode(NULL_MODE)
#else
#include <WiFi.h>
#include <esp_now.h>
#define ESP_NOW_SEND(mac, data, len) esp_now_send(mac, data, len)
#define RADIO_INIT() esp_now_init()
#define RADIO_REGISTER_CB(cb) esp_now_register_recv_cb(cb)
#define RADIO_ADD_BROADCAST() { uint8_t b[6] = {0xFF,0xFF,0xFF,0xFF,0xFF,0xFF}; esp_now_peer_info_t p = {}; memcpy(p.peer_addr, b, 6); p.channel = 6; p.encrypt = false; esp_now_add_peer(&p); }
#define WIFI_OFF() WiFi.mode(WIFI_OFF)
#endif
// ------------------------------------------------------------
// USER CONFIG — change NODE_ID for each board
// ------------------------------------------------------------
#define NODE_ID 1 // MUST BE UNIQUE: 1, 2, 3, ... up to 254
#define MAX_HOPS 6
#define HEARTBEAT_MS 2000
#define SEND_INTERVAL 350
#define LIGHT_PIN 2 // LED / IR emitter / laser diode
#define LIGHT_RX_PIN 4 // photodiode / phototransistor
#define RADIO_CHANNEL 6
#define MAX_NEIGHBOURS 16
// ------------------------------------------------------------
// PACKET FORMAT (packed, 42 bytes over the air)
// ------------------------------------------------------------
typedef struct __attribute__((packed)) {
uint8_t src;
uint8_t dst;
uint8_t ttl;
uint8_t hops;
uint16_t seq;
uint8_t payload[32];
uint16_t crc;
} MeshPacket;
// ------------------------------------------------------------
// NEIGHBOUR TABLE
// ------------------------------------------------------------
struct Neighbour {
uint8_t mac[6];
uint8_t id;
uint32_t lastSeen;
};
Neighbour neighbours[MAX_NEIGHBOURS];
uint8_t neighbourCount = 0;
// ------------------------------------------------------------
// ROUTING TABLE (destination -> next hop)
// ------------------------------------------------------------
struct RouteEntry {
uint8_t dst;
uint8_t nextHop;
uint8_t metric;
uint32_t lastUpdated;
};
RouteEntry routes[32];
uint8_t routeCount = 0;
// ------------------------------------------------------------
// DUPLICATE-CACHE
// ------------------------------------------------------------
struct SeenEntry {
uint16_t seq;
uint8_t src;
uint32_t time;
};
SeenEntry seen[64];
uint8_t seenIdx = 0;
uint16_t mySeq = 0;
uint32_t lastHeartbeat = 0;
uint32_t lastSend = 0;
// ============================================================
// LIGHT-BASED COMMUNICATION (VLC / OOK)
// ============================================================
volatile uint8_t lightBitBuffer = 0;
volatile uint8_t lightBitCount = 0;
volatile uint32_t lightLastEdge = 0;
volatile uint8_t lightRxPacket[48];
volatile uint8_t lightRxLen = 0;
volatile bool lightPacketReady = false;
inline void lightSendBit(bool bit) {
if (bit) {
digitalWrite(LIGHT_PIN, HIGH);
delayMicroseconds(50); // short pulse = 1
digitalWrite(LIGHT_PIN, LOW);
delayMicroseconds(100);
} else {
digitalWrite(LIGHT_PIN, HIGH);
delayMicroseconds(150); // long pulse = 0
digitalWrite(LIGHT_PIN, LOW);
delayMicroseconds(100);
}
}
void lightSendPacket(uint8_t *data, uint8_t len) {
if (len > 48) return;
for (int i = 0; i < 8; i++) lightSendBit(1); // preamble
for (int b = 7; b >= 0; b--) lightSendBit((len >> b) & 1); // length
for (int i = 0; i < len; i++)
for (int b = 7; b >= 0; b--)
lightSendBit((data[i] >> b) & 1);
lightSendBit(0); // stop
}
void lightRxISR() {
uint32_t now = micros();
uint32_t width = now - lightLastEdge;
lightLastEdge = now;
if (width < 30) return;
bool bit = (width > 80) ? 0 : 1;
lightBitBuffer = (lightBitBuffer << 1) | bit;
lightBitCount++;
if (lightBitCount == 8) {
static uint8_t preambleCount = 0;
static uint8_t rxBuf[48];
static uint8_t rxIdx = 0;
static uint8_t expectedLen = 0;
uint8_t byte = lightBitBuffer;
lightBitBuffer = 0;
lightBitCount = 0;
if (preambleCount < 8) {
if (byte == 0xFF) preambleCount++;
else preambleCount = 0;
return;
}
if (rxIdx == 0) {
expectedLen = byte;
if (expectedLen > 48) { preambleCount = 0; rxIdx = 0; return; }
rxIdx++;
} else if (rxIdx <= expectedLen) {
rxBuf[rxIdx - 1] = byte;
rxIdx++;
if (rxIdx > expectedLen) {
for (int i = 0; i < expectedLen; i++) lightRxPacket[i] = rxBuf[i];
lightRxLen = expectedLen;
lightPacketReady = true;
preambleCount = 0;
rxIdx = 0;
}
}
}
}
// ============================================================
// RADIO (ESP-NOW — raw frames, no association, no IP)
// ============================================================
#ifdef ESP8266_BOARD
void onRadioRecv(uint8_t *mac, uint8_t *data, uint8_t len) {
#else
void onRadioRecv(const uint8_t *mac, const uint8_t *data, int len) {
#endif
if (len != sizeof(MeshPacket)) return;
MeshPacket *pkt = (MeshPacket*)data;
if (pkt->src == NODE_ID) return;
updateNeighbour((uint8_t*)mac, pkt->src);
if (isDuplicate(pkt->src, pkt->seq)) return;
markSeen(pkt->src, pkt->seq);
learnRoute(pkt->src, pkt->src, 1);
if (pkt->dst == NODE_ID) { handleLocalDelivery(pkt); return; }
forwardPacket(pkt);
}
// ============================================================
// MESH CORE
// ============================================================
bool isDuplicate(uint8_t src, uint16_t seq) {
uint32_t now = millis();
for (int i = 0; i < 64; i++)
if (seen[i].src == src && seen[i].seq == seq && (now - seen[i].time) < 8000) return true;
return false;
}
void markSeen(uint8_t src, uint16_t seq) {
seen[seenIdx].src = src; seen[seenIdx].seq = seq; seen[seenIdx].time = millis();
seenIdx = (seenIdx + 1) % 64;
}
void updateNeighbour(uint8_t *mac, uint8_t id) {
for (int i = 0; i < neighbourCount; i++)
if (memcmp(neighbours[i].mac, mac, 6) == 0) {
neighbours[i].lastSeen = millis(); neighbours[i].id = id; return;
}
if (neighbourCount < MAX_NEIGHBOURS) {
memcpy(neighbours[neighbourCount].mac, mac, 6);
neighbours[neighbourCount].id = id;
neighbours[neighbourCount].lastSeen = millis();
neighbourCount++;
}
}
void learnRoute(uint8_t dst, uint8_t nextHop, uint8_t metric) {
for (int i = 0; i < routeCount; i++)
if (routes[i].dst == dst) {
if (metric < routes[i].metric) {
routes[i].nextHop = nextHop; routes[i].metric = metric; routes[i].lastUpdated = millis();
}
return;
}
if (routeCount < 32) {
routes[routeCount].dst = dst; routes[routeCount].nextHop = nextHop;
routes[routeCount].metric = metric; routes[routeCount].lastUpdated = millis();
routeCount++;
}
}
uint8_t findNextHop(uint8_t dst) {
for (int i = 0; i < routeCount; i++)
if (routes[i].dst == dst && (millis() - routes[i].lastUpdated) < 30000)
return routes[i].nextHop;
return 0xFF;
}
void forwardPacket(MeshPacket *pkt) {
if (pkt->ttl == 0) return;
MeshPacket fwd = *pkt;
fwd.ttl--;
fwd.hops++;
if (fwd.hops > MAX_HOPS) return;
uint8_t next = findNextHop(fwd.dst);
if (next != 0xFF) {
for (int i = 0; i < neighbourCount; i++)
if (neighbours[i].id == next) {
ESP_NOW_SEND(neighbours[i].mac, (uint8_t*)&fwd, sizeof(fwd));
break;
}
} else {
for (int i = 0; i < neighbourCount; i++)
ESP_NOW_SEND(neighbours[i].mac, (uint8_t*)&fwd, sizeof(fwd));
lightSendPacket((uint8_t*)&fwd, sizeof(fwd));
}
}
void handleLocalDelivery(MeshPacket *pkt) {
// ====== PAYLOAD ARRIVED FOR THIS NODE ======
// pkt->payload[0..31] contains the data
// pkt->src who sent it
// Add your own logic here: control a relay,
// read a sensor, drive a motor, etc.
// Blink the light pin so you can SEE it worked:
digitalWrite(LIGHT_PIN, HIGH);
delay(5);
digitalWrite(LIGHT_PIN, LOW);
}
void generateAndSend() {
if (millis() - lastSend < SEND_INTERVAL) return;
lastSend = millis();
MeshPacket pkt;
pkt.src = NODE_ID;
pkt.dst = 0xFF; // broadcast (or a specific NODE_ID)
pkt.ttl = MAX_HOPS;
pkt.hops = 0;
pkt.seq = mySeq++;
// Fill payload with your own data. Example: uptime.
for (int i = 0; i < 32; i++)
pkt.payload[i] = (uint8_t)(millis() >> ((i % 4) * 8));
// simple CRC
pkt.crc = 0;
uint8_t *raw = (uint8_t*)&pkt;
for (int i = 0; i < sizeof(pkt) - 2; i++) pkt.crc += raw[i];
uint8_t bcast[6] = {0xFF,0xFF,0xFF,0xFF,0xFF,0xFF};
ESP_NOW_SEND(bcast, (uint8_t*)&pkt, sizeof(pkt));
lightSendPacket((uint8_t*)&pkt, sizeof(pkt));
}
void sendHeartbeat() {
if (millis() - lastHeartbeat < HEARTBEAT_MS) return;
lastHeartbeat = millis();
MeshPacket hb;
hb.src = NODE_ID; hb.dst = 0xFF; hb.ttl = 1; hb.hops = 0; hb.seq = mySeq++;
hb.payload[0] = 'H'; hb.payload[1] = 'B';
hb.crc = 0;
uint8_t bcast[6] = {0xFF,0xFF,0xFF,0xFF,0xFF,0xFF};
ESP_NOW_SEND(bcast, (uint8_t*)&hb, sizeof(hb));
lightSendPacket((uint8_t*)&hb, sizeof(hb));
}
// ============================================================
// SETUP
// ============================================================
void setup() {
Serial.begin(115200);
pinMode(LIGHT_PIN, OUTPUT);
pinMode(LIGHT_RX_PIN, INPUT_PULLUP);
attachInterrupt(digitalPinToInterrupt(LIGHT_RX_PIN), lightRxISR, CHANGE);
// Kill Wi-Fi association, keep only raw radio
WIFI_OFF();
// Bring up ESP-NOW radio
RADIO_INIT();
RADIO_REGISTER_CB(onRadioRecv);
RADIO_ADD_BROADCAST();
#ifdef ESP8266_BOARD
esp_now_set_self_role(ESP_NOW_ROLE_COMBO);
esp_now_set_kok((uint8_t*"\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"), 16);
#endif
randomSeed(analogRead(0) ^ micros());
}
// ============================================================
// MAIN LOOP
// ============================================================
void loop() {
generateAndSend(); // 1. send our own data
sendHeartbeat(); // 2. announce presence
// 3. process any packet received over light
if (lightPacketReady) {
lightPacketReady = false;
if (lightRxLen == sizeof(MeshPacket)) {
MeshPacket *pkt = (MeshPacket*)lightRxPacket;
if (pkt->src != NODE_ID && !isDuplicate(pkt->src, pkt->seq)) {
markSeen(pkt->src, pkt->seq);
learnRoute(pkt->src, pkt->src, 1);
if (pkt->dst == NODE_ID) handleLocalDelivery(pkt);
else forwardPacket(pkt);
}
}
}
// 4. expire stale neighbours
uint32_t now = millis();
for (int i = neighbourCount - 1; i >= 0; i--)
if (now - neighbours[i].lastSeen > 60000) {
for (int j = i; j < neighbourCount - 1; j++) neighbours[j] = neighbours[j + 1];
neighbourCount--;
}
// 5. expire stale routes
for (int i = routeCount - 1; i >= 0; i--)
if (now - routes[i].lastUpdated > 45000) {
for (int j = i; j < routeCount - 1; j++) routes[j] = routes[j + 1];
routeCount--;
}
delay(1);
}
/*
* ============================================================
* WIRING
* ============================================================
* LIGHT_PIN (GPIO2) -> LED / IR LED / laser diode -> GND (via resistor)
* LIGHT_RX_PIN (GPIO4) -> photodiode / phototransistor -> GND
*
* For long range: use a 940 nm IR LED + matching IR receiver.
* For short range: any visible LED + LDR / photodiode works.
*
* FLASHING
* ============================================================
* 1. Set NODE_ID to 1, flash board #1.
* 2. Set NODE_ID to 2, flash board #2.
* 3. Set NODE_ID to 3, flash board #3.
* 4. Power them all on.
* 5. They form a mesh automatically. No router. No Wi-Fi.
*
* VERIFY
* ============================================================
* Open Serial Monitor @ 115200. You'll see packets
* being generated and forwarded. The LED on LIGHT_PIN
* pulses for every outgoing packet, and blinks fast
* when a packet is delivered to this node.
*
* This is REAL firmware. It runs on real ESP hardware.
* ============================================================
*/