/* Session 6 — ESP-NOW sensor node (star topology, no router needed in the field) Sends a struct to the gateway every 60 s; retries 3 times if the delivery callback reports failure. Set GATEWAY_MAC to the MAC printed by s06_espnow_gateway. Use the SAME Wi-Fi channel as the gateway. Compatible with ESP32 Arduino core 3.x (esp_now_send_cb_t uses wifi_tx_info_t). For core 2.x change the callback signature to: void onSent(const uint8_t *mac, esp_now_send_status_t status) */ #include #include #include #include uint8_t GATEWAY_MAC[] = {0x24, 0x6F, 0x28, 0xAA, 0xBB, 0xCC}; // <-- edit const uint8_t CHANNEL = 6; const uint8_t NODE_NUM = 2; // 1..20, unique per node typedef struct __attribute__((packed)) { uint8_t node; uint32_t seq; float temp; float hum; uint16_t soilRaw; float battery; } Reading; DHT dht(4, DHT22); Reading msg; volatile bool lastOk = false; void onSent(const wifi_tx_info_t *info, esp_now_send_status_t status) { lastOk = (status == ESP_NOW_SEND_SUCCESS); } void setup() { Serial.begin(115200); dht.begin(); WiFi.mode(WIFI_STA); esp_wifi_set_channel(CHANNEL, WIFI_SECOND_CHAN_NONE); if (esp_now_init() != ESP_OK) { Serial.println("ESP-NOW init failed"); ESP.restart(); } esp_now_register_send_cb(onSent); esp_now_peer_info_t peer = {}; memcpy(peer.peer_addr, GATEWAY_MAC, 6); peer.channel = CHANNEL; esp_now_add_peer(&peer); Serial.print("node MAC: "); Serial.println(WiFi.macAddress()); } void loop() { msg.node = NODE_NUM; msg.seq++; msg.temp = dht.readTemperature(); msg.hum = dht.readHumidity(); msg.soilRaw = analogRead(34); msg.battery = analogReadMilliVolts(33) * 2 / 1000.0; for (int attempt = 1; attempt <= 3; attempt++) { // handle temporary loss lastOk = false; esp_now_send(GATEWAY_MAC, (uint8_t *)&msg, sizeof(msg)); delay(60); if (lastOk) break; Serial.printf("seq %lu attempt %d failed\n", msg.seq, attempt); delay(200 * attempt); // back-off } Serial.printf("seq %lu sent=%s\n", msg.seq, lastOk ? "OK" : "LOST"); delay(60000); }