Hi everyone
I am bulding some sort of weather station but Ihave problems with sending the data from my reciever (I am using esp-now network) to the server and I cant open my server in my web brower.
I am using
- esp 32 as a server
- esp8266 as a sender
- dht11 as the sensors
- arduino 2.3.4
Here is my code for the esp 8266 (Its big mix of codes I found online so its may be bit weird)
#include <ESP8266WiFi.h>
#include <espnow.h>
#include "DHT.h"
#define DHTPIN 2
#define DHTTYPE DHT11
DHT dht(DHTPIN, DHTTYPE);
#define CHANNEL 4
float tempe;
float humi;
int reading;
uint8_t remoteMac[] = {0xfc, 0xb4, 0x67, 0xf1, 0x47, 0x58};
struct __attribute__((packed)) DataStruct {
//char text[32];
float hum;
float temp;
int read;
};
DataStruct myData;
unsigned long lastSentMillis;
unsigned long sendIntervalMillis = 1000;
void InitESPNow() {
WiFi.disconnect();
if (esp_now_init()==0) {
Serial.println("ESPNow Init Success");
}
else {
Serial.println("ESPNow Init Failed");
ESP.restart();
}
}
void sendData() {
if (millis() - lastSentMillis >= sendIntervalMillis) {
lastSentMillis += sendIntervalMillis;
reading = reading + 1;
myData.read = reading;
esp_now_send(NULL, (uint8_t *)&myData, sizeof(myData));
Serial.println("sent data");
Serial.println(myData.hum);
Serial.println(myData.temp);
}
}
void setup() {
Serial.begin(74880); Serial.println();
dht.begin();
reading = 0;
Serial.println("Starting dht");
WiFi.mode(WIFI_STA);
WiFi.disconnect();
Serial.printf("This mac: %s, ", WiFi.macAddress().c_str());
Serial.printf("slave mac: %02x%02x%02x%02x%02x%02x", remoteMac[0], remoteMac[1], remoteMac[2], remoteMac[3], remoteMac[4], remoteMac[5]);
Serial.printf(", channel: %i\n",CHANNEL);
InitESPNow();
esp_now_set_self_role(ESP_NOW_ROLE_CONTROLLER);
esp_now_add_peer(remoteMac, ESP_NOW_ROLE_SLAVE, CHANNEL, NULL, 0);
}
void loop() {
humi = dht.readHumidity();
tempe = dht.readTemperature();
if (isnan(humi) || isnan(tempe)) {
Serial.print("failed to read ");
} else {
if (myData.hum != humi) {
myData.hum = humi;
myData.temp = tempe;
sendData();
} else if (myData.temp != tempe) {
myData.hum = humi;
myData.temp = tempe;
sendData();
}
}
delay(1000);
}
here is the output
13:35:01.820 -> Packet received from: ea:c2:fb:3f:e4:c2
13:35:01.820 -> 44.00
13:35:01.820 -> 20.50
13:35:01.820 -> 135
13:35:01.820 -> event send :{"id":1,"temperature":0,"humidity":0,"readingId":0}
here is the code for the esp32
/*********
Rui Santos & Sara Santos - Random Nerd Tutorials
Complete project details at https://RandomNerdTutorials.com/esp-now-many-to-one-esp32/
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files.
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*********/
#include <esp_now.h>
#include <WiFi.h>
#include "ESPAsyncWebServer.h"
#include "AsyncTCP.h"
#include <ArduinoJson.h>
//my structure
struct __attribute__((packed)) DataStruct {
//char text[32];
float hum;
float temp;
int read;
};
DataStruct myData;
const char* ssid = "Popo";
const char* password = "81popelakova";
int chan;
//setings fo webserver
AsyncWebServer server(80);
AsyncEventSource events("/events");
//web server
const char index_html[] PROGMEM = R"rawliteral(
<!DOCTYPE HTML><html>
<head>
<title>ESP-NOW DASHBOARD</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.2/css/all.css" integrity="sha384-fnmOCqbTlWIlj8LyTjo7mOUStjsKC4pOpQbqyi7RrhN7udi9RwhKkMHpvLbHG9Sr" crossorigin="anonymous">
<link rel="icon" href="data:,">
<style>
html {font-family: Arial; display: inline-block; text-align: center;}
p { font-size: 1.2rem;}
body { margin: 0;}
.topnav { overflow: hidden; background-color: #2f4468; color: white; font-size: 1.7rem; }
.content { padding: 20px; }
.card { background-color: white; box-shadow: 2px 2px 12px 1px rgba(140,140,140,.5); }
.cards { max-width: 700px; margin: 0 auto; display: grid; grid-gap: 2rem; grid-template-columns: repeat(auto-fit, minmax(300px, 1fr)); }
.reading { font-size: 2.8rem; }
.packet { color: #bebebe; }
.card.temperature { color: #fd7e14; }
.card.humidity { color: #1b78e2; }
</style>
</head>
<body>
<div class="topnav">
<h3>ESP-NOW DASHBOARD</h3>
</div>
<div class="content">
<div class="cards">
<div class="card temperature">
<h4><i class="fas fa-thermometer-half"></i> BOARD #1 - TEMPERATURE</h4><p><span class="reading"><span id="t1"></span> °C</span></p><p class="packet">Reading ID: <span id="rt1"></span></p>
</div>
<div class="card humidity">
<h4><i class="fas fa-tint"></i> BOARD #1 - HUMIDITY</h4><p><span class="reading"><span id="h1"></span> %</span></p><p class="packet">Reading ID: <span id="rh1"></span></p>
</div>
<div class="card temperature">
<h4><i class="fas fa-thermometer-half"></i> BOARD #2 - TEMPERATURE</h4><p><span class="reading"><span id="t2"></span> °C</span></p><p class="packet">Reading ID: <span id="rt2"></span></p>
</div>
<div class="card humidity">
<h4><i class="fas fa-tint"></i> BOARD #2 - HUMIDITY</h4><p><span class="reading"><span id="h2"></span> %</span></p><p class="packet">Reading ID: <span id="rh2"></span></p>
</div>
</div>
</div>
<script>
if (!!window.EventSource) {
var source = new EventSource('/events');
source.addEventListener('open', function(e) {
console.log("Events Connected");
}, false);
source.addEventListener('error', function(e) {
if (e.target.readyState != EventSource.OPEN) {
console.log("Events Disconnected");
}
}, false);
source.addEventListener('message', function(e) {
console.log("message", e.data);
}, false);
source.addEventListener('new_readings', function(e) {
console.log("new_readings", e.data);
var obj = JSON.parse(e.data);
document.getElementById("t"+obj.id).innerHTML = obj.temperature.toFixed(2);
document.getElementById("h"+obj.id).innerHTML = obj.humidity.toFixed(2);
document.getElementById("rt"+obj.id).innerHTML = obj.readingId;
document.getElementById("rh"+obj.id).innerHTML = obj.readingId;
}, false);
}
</script>
</body>
</html>)rawliteral";
//when recieved
void OnDataRecv(const uint8_t * mac_addr, const uint8_t *incomingData, int len) {
char macStr[18];
Serial.print("Packet received from: ");
snprintf(macStr, sizeof(macStr), "%02x:%02x:%02x:%02x:%02x:%02x",
mac_addr[0], mac_addr[1], mac_addr[2], mac_addr[3], mac_addr[4], mac_addr[5]);
Serial.println(macStr);
memcpy(&myData, incomingData, sizeof(myData));
Serial.println(myData.hum);
Serial.println(myData.temp);
Serial.println(myData.read);
StaticJsonDocument<1000> root;
String payload;
root["id"] = 1;
root["temperature"] = float(incomingData.temp);
root["humidity"] = float(incomingData.hum);
root["readingId"] = float(incomingData.read);
serializeJson(root, payload);
Serial.print("event send :");
serializeJson(root, Serial);
events.send(payload.c_str(), "new_readings", millis());
Serial.println();
}
void setup() {
Serial.begin(115200);
WiFi.mode(WIFI_STA);
if (esp_now_init() != ESP_OK) {
Serial.println("Error initializing ESP-NOW");
return;
}
esp_now_register_recv_cb(esp_now_recv_cb_t(OnDataRecv));
chan = WiFi.channel();
Serial.print("Station IP Address: ");
Serial.println(WiFi.localIP());
Serial.print("Wi-Fi Channel: ");
Serial.println(WiFi.channel());
//Start Web server
server.on("/", HTTP_GET, [](AsyncWebServerRequest *request){
request->send_P(200, "text/html", index_html);
});
events.onConnect([](AsyncEventSourceClient *client){
if(client->lastId()){
Serial.printf("Client reconnected! Last message ID that it got is: %u\n", client->lastId());
}
client->send("hello!", NULL, millis(), 10000);
});
server.addHandler(&events);
// start server
server.begin();
}
void loop() {
static unsigned long lastEventTime = millis();
static const unsigned long EVENT_INTERVAL_MS = 5000;
if ((millis() - lastEventTime) > EVENT_INTERVAL_MS) {
events.send("ping", NULL, millis());
lastEventTime = millis();
}
}
here is the output from esp8266
13:32:31.926 -> sent data
13:32:31.926 -> 44.00
13:32:31.926 -> 20.50
13:32:46.110 -> sent data
13:32:46.110 -> 45.00
13:32:46.110 -> 20.50
13:33:10.423 -> sent data
13:33:10.423 -> 44.00
13:33:10.423 -> 20.50
13:33:12.457 -> sent data
13:33:12.457 -> 45.00
13:33:12.457 -> 20.50