/*
Rui Santos
Complete project details at https://RandomNerdTutorials.com/esp8266-
client-server-wi-fi/
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 <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#include <WiFiClient.h>
#include <ESP8266WiFiMulti.h>
ESP8266WiFiMulti WiFiMulti;
const char* ssid = "ESP8266-Access-Point";
const char* password = "123456789";
//Your IP address or domain name with URL path
const char* serverNameTemp = "http://192.168.4.1/temperature";
const char* serverNameHumi = "http://192.168.4.1/humidity";
const char* serverNamePres = "http://192.168.4.1/pressure";
String temperature;
String humidity;
String pressure;
String data;
unsigned long previousMillis = 0;
const long interval = 5000;
void setup() {
Serial.begin(115200);
Serial.println();
WiFi.mode(WIFI_STA);
WiFiMulti.addAP(ssid, password);
while((WiFiMulti.run() == WL_CONNECTED)) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("Connected to WiFi");
}
void loop(){
getWeatherData();
sendHumidityToNextion();
sendTemperatureToNextion();
delay(10000);
}
void getWeatherData(){
{
unsigned long currentMillis = millis();
if(currentMillis - previousMillis >= interval) {
// Check WiFi connection status
if ((WiFiMulti.run() == WL_CONNECTED)) {
temperature = httpGETRequest(serverNameTemp);
humidity = httpGETRequest(serverNameHumi);
pressure = httpGETRequest(serverNamePres);
Serial.println("Temperature: " + temperature + " *C - Humidity: " +
humidity + " % - Pressure: " + pressure + " hPa");
// save the last HTTP GET Request
previousMillis = currentMillis;
}
else {
Serial.println("WiFi Disconnected");
}
}
}
}
void sendHumidityToNextion()
{
String command = "humidity.txt=\""+String(humidity)+"\"";
Serial.print(command);
endNextionCommand();
}
void sendTemperatureToNextion()
{
String command = "temperature.txt=\""+String(temperature)+"\"";
Serial.print(command);
endNextionCommand();
}
void endNextionCommand()
{
Serial.write(0xff);
Serial.write(0xff);
Serial.write(0xff);
}
String httpGETRequest(const char* serverName) {
WiFiClient client;
HTTPClient http;
// Your IP address with path or Domain name with URL path
http.begin(client, serverName);
// Send HTTP POST request
int httpResponseCode = http.GET();
String payload = "--";
if (httpResponseCode>0) {
Serial.print("HTTP Response code: ");
Serial.println(httpResponseCode);
payload = http.getString();
}
else {
Serial.print("Error code: ");
Serial.println(httpResponseCode);
}
// Free resources
http.end();
return payload;
}