Advertisement
LeventeDaradici

esp8266-web-server-gauges

Jan 18th, 2022 (edited)
198
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 3.30 KB | None | 0 0
  1. /*********
  2.   Rui Santos
  3.   Complete instructions at https://RandomNerdTutorials.com/esp8266-web-server-gauges/
  4.  
  5.   Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files.
  6.   The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
  7. *********/
  8.  
  9. #include <Arduino.h>
  10. #include <ESP8266WiFi.h>
  11. #include <ESPAsyncTCP.h>
  12. #include <ESPAsyncWebServer.h>
  13. #include "LittleFS.h"
  14. #include <Arduino_JSON.h>
  15. #include <Adafruit_BMP280.h>
  16. #include <Adafruit_Sensor.h>
  17.  
  18. // define device I2C address: 0x76 or 0x77 (0x77 is library default address)
  19. #define BMP280_I2C_ADDRESS  0x76
  20. Adafruit_BMP280 bmp280;
  21.  
  22. // Replace with your network credentials
  23. const char* ssid = "YOUR WIFI SSID";
  24. const char* password = "*YOUR WIFI PASSWORD";
  25.  
  26. // Create AsyncWebServer object on port 80
  27. AsyncWebServer server(80);
  28.  
  29. // Create an Event Source on /events
  30. AsyncEventSource events("/events");
  31.  
  32. // Json Variable to Hold Sensor Readings
  33. JSONVar readings;
  34.  
  35. // Timer variables
  36. unsigned long lastTime = 0;  
  37. unsigned long timerDelay = 30000;
  38.  
  39. // Create a sensor object
  40.  
  41.  
  42.  
  43.  
  44. // Get Sensor Readings and return JSON object
  45. String getSensorReadings(){
  46.   readings["temperature"] = String(bmp280.readTemperature());
  47.   readings["humidity"] =  String(bmp280.readPressure());
  48.   String jsonString = JSON.stringify(readings);
  49.   return jsonString;
  50. }
  51.  
  52. // Initialize LittleFS
  53. void initFS() {
  54.   if (!LittleFS.begin()) {
  55.     Serial.println("An error has occurred while mounting LittleFS");
  56.   }
  57.   Serial.println("LittleFS mounted successfully");
  58. }
  59.  
  60. // Initialize WiFi
  61. void initWiFi() {
  62.   WiFi.mode(WIFI_STA);
  63.   WiFi.begin(ssid, password);
  64.   Serial.print("Connecting to WiFi ..");
  65.   while (WiFi.status() != WL_CONNECTED) {
  66.     Serial.print('.');
  67.     delay(1000);
  68.   }
  69.   Serial.println(WiFi.localIP());
  70. }
  71.  
  72. void setup() {
  73.   Serial.begin(115200);
  74.   if (!bmp280.begin(BMP280_I2C_ADDRESS))
  75.   {  
  76.     Serial.println("Could not find a valid BMP280 sensor, check wiring!");
  77.     while (1);
  78.   }
  79.   Serial.println("BMP sensor init succesfully !");
  80.   initWiFi();
  81.   initFS();
  82.  
  83.   // Web Server Root URL
  84.   server.on("/", HTTP_GET, [](AsyncWebServerRequest *request){
  85.     request->send(LittleFS, "/index.html", "text/html");
  86.   });
  87.  
  88.   server.serveStatic("/", LittleFS, "/");
  89.  
  90.   // Request for the latest sensor readings
  91.   server.on("/readings", HTTP_GET, [](AsyncWebServerRequest *request){
  92.     String json = getSensorReadings();
  93.     request->send(200, "application/json", json);
  94.     json = String();
  95.   });
  96.  
  97.   events.onConnect([](AsyncEventSourceClient *client){
  98.     if(client->lastId()){
  99.       Serial.printf("Client reconnected! Last message ID that it got is: %u\n", client->lastId());
  100.     }
  101.     // send event with message "hello!", id current millis
  102.     // and set reconnect delay to 1 second
  103.     client->send("hello!", NULL, millis(), 10000);
  104.   });
  105.   server.addHandler(&events);
  106.  
  107.   // Start server
  108.   server.begin();
  109. }
  110.  
  111. void loop() {
  112.   if ((millis() - lastTime) > timerDelay) {
  113.     // Send Events to the client with the Sensor Readings Every 30 seconds
  114.     events.send("ping",NULL,millis());
  115.     events.send(getSensorReadings().c_str(),"new_readings" ,millis());
  116.     lastTime = millis();
  117.   }
  118. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement