ESP8266_ESPNOW_receive.ino 2.02 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
/**
 * This originally was the ESP-NOW to Serial sketch from Anthony Elder
 * but that was rather incomplete for my goal so I adapted it
 *  
 * Author: Anthony Elder (original author)
 * License: Apache License v2
 * 
 * Altered by DIY_bloke
 */
#include <ESP8266WiFi.h>
extern "C" {
  #include <espnow.h>
  #include "user_interface.h"
}

/* Set a private Mac Address
 *  http://serverfault.com/questions/40712/what-range-of-mac-addresses-can-i-safely-use-for-my-virtual-machines
 * Note: the point of setting a specific MAC is so you can replace this Gateway ESP8266 device with a new one
 * and the new gateway will still pick up the remote sensors which are still sending to the old MAC 
 */
uint8_t mac[] = {0xEC, 0xFA, 0xBC, 0x9B, 0xF5, 0x6D};
void initVariant() {
  WiFi.mode(WIFI_AP);
  wifi_set_macaddr(SOFTAP_IF, &mac[0]);
}


// keep in sync with ESP_NOW sensor struct
struct __attribute__((packed)) SENSOR_DATA {
    float temp;
    float humidity;
    float pressure;
} sensorData;
volatile boolean haveReading = false;
int heartBeat;

void setup() {
  Serial.begin(115200); Serial.println();

  Serial.print("This node AP mac: "); Serial.println(WiFi.softAPmacAddress());
  Serial.print("This node STA mac: "); Serial.println(WiFi.macAddress());

  initEspNow();
}


void loop() {
    if (millis()-heartBeat > 30000) {
    Serial.println("Waiting for ESP-NOW messages...");
    heartBeat = millis();
  }
  if (haveReading) {
    haveReading = false;
   Serial.println(sensorData.temp);
   Serial.println(sensorData.humidity);
   Serial.println(sensorData.pressure);
   ESP.restart(); // <----- Reboots to re-enable ESP-NOW
  }
}

void initEspNow() {
  if (esp_now_init()!=0) {
    Serial.println("*** ESP_Now init failed");
    ESP.restart();
  }

  esp_now_set_self_role(ESP_NOW_ROLE_COMBO);

  esp_now_register_recv_cb([](uint8_t *mac, uint8_t *data, uint8_t len) {
    memcpy(&sensorData, data, sizeof(sensorData));
    Serial.printf(" Temp=%0.1f, Hum=%0.0f%%, pressure=%0.0fmb\n", sensorData.temp, sensorData.humidity, sensorData.pressure);  
    
  });
}