Rusty_Gunn

Code for ESP32-DEV, W5500 Wired Ethernet Module, and BME-280 Web Server with Favicon!

May 11th, 2024
1,745
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 15.07 KB | Source Code | 0 0
  1. //////////////////////////////////////////////////////////////////////////////////////////
  2. //ESP32 Environmental Sensor Web Server                                                 //
  3. //                                                                                      //
  4. //Set board to ESP32-Dev Module                                                         //
  5. //I am using a ESP-WROOM-32 module with 30 pins                                         //
  6. //connected to a Wiz W5500 ethernet module                                              //
  7. //and a BME280 (3.3v) environmental sesnor                                              //
  8. //                                                                                      //
  9. //Code is based on the webserver example that comes with the W5500 library              //
  10. //                                                                                      //
  11. //Compiled by Reiley McKerracher                                                        //
  12. //April 2, 2023                                                                         //
  13. //////////////////////////////////////////////////////////////////////////////////////////
  14.  
  15.  
  16. //////////////////////////////////////////////////////////////////////////////////////////
  17. // Initialize                                                                           //
  18. //////////////////////////////////////////////////////////////////////////////////////////
  19.  
  20. //rename serial, helpful when using multiple serial connections
  21. #define MySerial Serial
  22.  
  23. //wifi library, only used to turn it off since we are using an ethernet adapter
  24. //library is included esp32 board manager package by Expressif Systems
  25. #include <WiFi.h>
  26.  
  27. //Ethernet Variable Setup
  28. //install ethernet library from library manager within the arduino IDE
  29. //within the library, copy the Ethernet.h file (within the same directory) to a new name of EthernetESP32.h
  30. //Edit EthernetESP32.h and on line 254 replace "class EthernetServer : public Server" with "class EthernetServer : public Print"
  31. //without the edit, you will have compiling errors for the class
  32. //ethernet code based on web server example that comes with the library
  33. #include <SPI.h>
  34. #include <EthernetESP32.h>  //ethernet library for w5500 chip modified for the esp32
  35. //esp library ETH does not work with the w5500
  36. byte mac[] = { 0x74, 0x69, 0x69, 0x2D, 0x32, 0x33 };  // ethernet mac address - must be unique on your network
  37. IPAddress ip(192, 168, 0, 48);                        // assign an IP address for the server - must be unique on your network and ideally outside your router's dhcp range
  38. IPAddress gateway(192, 168, 0, 1);
  39. IPAddress subnet(255, 255, 255, 0);
  40.  
  41. EthernetServer server(80);  //set HTTP server port
  42. String readString;          //var for url requested, this allows us to serve different pages based on the url
  43.  
  44. //To create a favicon, first create a 16x16 png file, then convert to base64 then to 8 bit signed hex
  45. //http://www.xiconeditor.com/   -> create and or edit ico file
  46. //https://www.aconvert.com/image/ico-to-png/  -> convert ico to png
  47. //https://www.base64-image.de/    -> png to base64
  48. //https://cryptii.com/pipes/base32-to-hex   -> hex encode
  49. //      text -> decode 64 -> encode 8 bit hexidecimal signed -> text    -> signed 8 bit for ethercard library
  50. //http://tomeko.net/online_tools/base64.php?lang=en    -> base64 to unsigned hex with 0x prefix for ethernet2 library
  51. //for this example I have created a arduino green house/home icon
  52. //code was originally inspired by this forum post: https://jeelabs.org/forum/node/1042.html which unforntatly no longer exists.
  53. const char favicon[] = {
  54.   -0x77, 0x50, 0x4e, 0x47, 0x0d, 0xa, 0x1a, 0xa, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x48, 0x44, 0x52,
  55.   0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x10, 0x2, 0x3, 0x00, 0x00, 0x00, 0x62, -0x63, 0x17,
  56.   -0x0e, 0x00, 0x00, 0x00, 0x04, 0x67, 0x41, 0x4d, 0x41, 0x00, 0x00, -0x4f, -0x71, 0x0b, -0x04, 0x61,
  57.   0x05, 0x00, 0x00, 0x00, 0x20, 0x63, 0x48, 0x52, 0x4d, 0x00, 0x00, 0x7a, 0x26, 0x00, 0x00, -0x80,
  58.   -0x7c, 0x00, 0x00, -0x06, 0x00, 0x00, 0x00, -0x80, -0x18, 0x00, 0x00, 0x75, 0x30, 0x00, 0x00, -0x16,
  59.   0x60, 0x00, 0x00, 0x3a, -0x68, 0x00, 0x00, 0x17, 0x70, -0x64, -0x46, 0x51, 0x3c, 0x00, 0x00, 0x00,
  60.   0x09, 0x50, 0x4c, 0x54, 0x45, 0x00, 0x00, 0x00, 0x00, -0x6a, -0x64, -0x01, -0x01, -0x01, 0x2a, 0x0d,
  61.   0x43, 0x7e, 0x00, 0x00, 0x00, 0x01, 0x74, 0x52, 0x4e, 0x53, 0x00, 0x40, -0x1a, -0x28, 0x66, 0x00,
  62.   0x00, 0x00, 0x01, 0x62, 0x4b, 0x47, 0x44, 0x02, 0x66, 0x0b, 0x7c, 0x64, 0x00, 0x00, 0x00, 0x07,
  63.   0x74, 0x49, 0x4d, 0x45, 0x07, -0x1e, 0x06, 0x10, 0x09, 0x13, 0x0d, 0x58, -0x72, -0x4c, -0x4a, 0x00,
  64.   0x00, 0x00, 0x34, 0x49, 0x44, 0x41, 0x54, 0x08, -0x29, 0x63, 0x60, 0x0c, 0x0d, 0x75, 0x60, 0x10,
  65.   0x0d, 0x0d, 0x0d, -0x7f, 0x10, -0x5f, 0x61, 0x53, -0x7f, 0x44, -0x2c, -0x2e, 0x50, -0x7a, -0x30, -0x54,
  66.   -0x6b, 0x40, 0x62, -0x2b, -0x56, 0x50, -0x7a, -0x50, 0x55, -0x55, -0x5a, 0x42, 0x58, 0x50, 0x22, 0x0a,
  67.   -0x67, 0x40, -0x18, 0x05, 0x19, 0x05, 0x00, -0x35, -0x6e, 0x18, 0x60, 0x40, 0x44, 0x39, -0x49, 0x00,
  68.   0x00, 0x00, 0x25, 0x74, 0x45, 0x58, 0x74, 0x64, 0x61, 0x74, 0x65, 0x3a, 0x63, 0x72, 0x65, 0x61,
  69.   0x74, 0x65, 0x00, 0x32, 0x30, 0x31, 0x38, 0x2d, 0x30, 0x36, 0x2d, 0x31, 0x36, 0x54, 0x30, 0x39,
  70.   0x3a, 0x31, 0x39, 0x3a, 0x31, 0x33, 0x2d, 0x30, 0x37, 0x3a, 0x30, 0x30, -0x7a, 0x13, -0x11, 0x3e,
  71.   0x00, 0x00, 0x00, 0x25, 0x74, 0x45, 0x58, 0x74, 0x64, 0x61, 0x74, 0x65, 0x3a, 0x6d, 0x6f, 0x64,
  72.   0x69, 0x66, 0x79, 0x00, 0x32, 0x30, 0x31, 0x38, 0x2d, 0x30, 0x36, 0x2d, 0x31, 0x36, 0x54, 0x30,
  73.   0x39, 0x3a, 0x31, 0x39, 0x3a, 0x31, 0x33, 0x2d, 0x30, 0x37, 0x3a, 0x30, 0x30, -0x9, 0x4e, 0x57,
  74.   -0x7e, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4e, 0x44, -0x52, 0x42, 0x60, -0x7e
  75. };
  76.  
  77. //BME280 Variable Setup
  78. //Adafruit BME280 Library
  79. //https://github.com/adafruit/Adafruit_BME280_Library/tree/master
  80. #include <Wire.h>
  81. #include <SPI.h>
  82. #include <Adafruit_BME280.h>
  83.  
  84. Adafruit_BME280 bme;  // use I2C interface
  85. float bme_temp = 0;
  86. float bme_pressure = 0;
  87. float bme_humidity = 0;
  88.  
  89. //Global Variables for time stracking reading of sensors
  90. unsigned long lastSensorTime = millis();
  91.  
  92. //////////////////////////////////////////////////////////////////////////////////////////
  93. // Start Functions                                                                      //
  94. //////////////////////////////////////////////////////////////////////////////////////////
  95.  
  96. void readSensors() {
  97.   MySerial.print(F("Uptime: "));
  98.   MySerial.print(uptime(millis()));
  99.   MySerial.println(F(" - Reading Sensors"));
  100.  
  101.   //read bme280 sensor
  102.   bme_temp = bme.readTemperature();
  103.   bme_pressure = (bme.readPressure() / 100.0F);
  104.   bme_humidity = bme.readHumidity();
  105.  
  106.   lastSensorTime = millis();
  107. }
  108.  
  109. //return how long the arduino/server has been running
  110. //original code from Arduino forum
  111. //https://forum.arduino.cc/t/function-uptime/70600
  112. char *uptime(unsigned long milli) {
  113.   static char _return[25];
  114.   unsigned long secs = milli / 1000, mins = secs / 60;
  115.   unsigned int hours = mins / 60, days = hours / 24;
  116.   milli -= secs * 1000;
  117.   secs -= mins * 60;
  118.   mins -= hours * 60;
  119.   hours -= days * 24;
  120.   sprintf(_return, "%d days %2.2d:%2.2d:%2.2d.%3.3d", (byte)days, (byte)hours, (byte)mins, (byte)secs, (int)milli);
  121.   return _return;
  122. }
  123.  
  124. //convert int status to descriptive string for WiFi Status
  125. char *WiFi_Status(int status_int) {
  126.   static char _return[25];
  127.   switch (status_int) {
  128.     case 255:
  129.       sprintf(_return, "WL_NO_SHIELD");
  130.       break;
  131.     case 0:
  132.       sprintf(_return, "WL_IDLE_STATUS");
  133.       break;
  134.     case 1:
  135.       sprintf(_return, "WL_NO_SSID_AVAIL");
  136.       break;
  137.     case 2:
  138.       sprintf(_return, "WL_SCAN_COMPLETED");
  139.       break;
  140.     case 3:
  141.       sprintf(_return, "WL_CONNECTED");
  142.       break;
  143.     case 4:
  144.       sprintf(_return, "WL_CONNECT_FAILED");
  145.       break;
  146.     case 5:
  147.       sprintf(_return, "WL_CONNECTION_LOST");
  148.       break;
  149.     case 6:
  150.       sprintf(_return, "WL_DISCONNECTED");
  151.       break;
  152.     default:
  153.       sprintf(_return, "ERROR");
  154.       break;
  155.   }
  156.   return _return;
  157. }
  158.  
  159. //////////////////////////////////////////////////////////////////////////////////////////
  160. // Start Setup                                                                          //
  161. //////////////////////////////////////////////////////////////////////////////////////////
  162.  
  163. void setup() {
  164.   delay(1000);  //pause before starting serial, wihtout this, the esp32 will need the reset button pressed after flashing to get the serial monitor working
  165.   MySerial.begin(9600);
  166.   //while (!MySerial && (millis() < 5000)) delay(10); //does not work on esp32
  167.   MySerial.println("Begin Setup...");
  168.  
  169.  
  170.   //start the Ethernet connection and the server:
  171.   Ethernet.init(5);  //set the CS pin, required for ESP32 as the arduino default is different
  172.   Ethernet.begin(mac, ip);
  173.  
  174.   // Check for Ethernet hardware present
  175.   if (Ethernet.hardwareStatus() == EthernetNoHardware) {
  176.     MySerial.println("Ethernet shield was not found.  Sorry, can't run without hardware. :(");
  177.     while (true) {
  178.       delay(1);  // do nothing, no point running without Ethernet hardware
  179.     }
  180.   }
  181.   if (Ethernet.linkStatus() == LinkOFF) {
  182.     MySerial.println("Ethernet cable is not connected.");
  183.   }
  184.  
  185.   // start the server
  186.   server.begin();
  187.   MySerial.print(F("Server is at "));
  188.   MySerial.println(Ethernet.localIP());
  189.  
  190.   //don't need wifi since we are using an ethernet adapter, turn it off
  191.   WiFi.disconnect();
  192.   WiFi.mode(WIFI_OFF);
  193.   MySerial.print("WiFi Status: ");
  194.   //MySerial.println(WiFi.status());  //should output 255 indicating no shield (meaning it is disabled)
  195.   MySerial.println(WiFi_Status(WiFi.status()));  //this will return a descriptive string instead of a int but because of the assoicated function, uses more memory than the line above
  196.   // WL_NO_SHIELD        = 255,
  197.   // WL_IDLE_STATUS      = 0,
  198.   // WL_NO_SSID_AVAIL    = 1,
  199.   // WL_SCAN_COMPLETED   = 2,
  200.   // WL_CONNECTED        = 3,
  201.   // WL_CONNECT_FAILED   = 4,
  202.   // WL_CONNECTION_LOST  = 5,
  203.   // WL_DISCONNECTED     = 6,
  204.  
  205.   //BME280 sensor setup
  206.   MySerial.println("Initalize BME280 sensor.");
  207.   if (!bme.begin(0x76)) {  //insure you are on the right address, 0x76 and 0x77 are the common addresses
  208.     MySerial.println("Could not find a valid BME280 sensor, check wiring!");
  209.     while (1) delay(10);
  210.   }
  211.  
  212.   //inital reading of sensors, populate global variables
  213.   readSensors();
  214.  
  215.   MySerial.println("Setup Complete.");
  216.   MySerial.println("");
  217. }
  218.  
  219. //////////////////////////////////////////////////////////////////////////////////////////
  220. // Start Main Loop                                                                      //
  221. //////////////////////////////////////////////////////////////////////////////////////////
  222.  
  223. void loop() {
  224.  
  225.   // listen for incoming clients
  226.   EthernetClient client = server.available();
  227.   if (client) {
  228.     MySerial.println("");
  229.     MySerial.println("new client");
  230.     boolean currentLineIsBlank = true;
  231.     boolean endofFirstLine = false;
  232.     readString = "";
  233.     while (client.connected()) {
  234.       if (client.available()) {
  235.         char c = client.read();
  236.  
  237.         //first time encounter a line return say true
  238.         if (c == '\n' && endofFirstLine == false) endofFirstLine = true;
  239.  
  240.         //MySerial.print(c); //print what server receives to serial monitor
  241.  
  242.         //read char by char HTTP request, limit to checking the first 30 and stop after first line
  243.         if ((readString.length() < 30) && (endofFirstLine == false)) {
  244.           //store characters to string
  245.           readString += c;
  246.         }
  247.  
  248.         // if you've gotten to the end of the line (received a newline
  249.         // character) and the line is blank, the http request has ended
  250.         // so you can send a reply
  251.         if (c == '\n' && currentLineIsBlank) {
  252.  
  253.           //if readString starts with /s serve sensor data
  254.           if (readString.indexOf("/s") > 0) {
  255.             MySerial.println(F("Enviromental Data Served"));
  256.  
  257.             //only read sensors if values are more than 20 seconds old, helps with webpage hammering
  258.             if ((millis() > (lastSensorTime + (20UL * 1000))) || (millis() < lastSensorTime)) readSensors();
  259.  
  260.             // send a standard http response header
  261.             client.println("HTTP/1.1 200 OK");
  262.             client.println("Content-Type: text/plain");
  263.             client.println("Pragma: no-cache");
  264.             client.println("Connection: close");  // the connection will be closed after completion of the response
  265.             client.println();
  266.             client.println("Environmental Sensor Web Server");
  267.             client.print("Temperature: ");
  268.             client.print(bme_temp, 1);
  269.             client.println(" C");
  270.             client.print("Relative Humidity: ");
  271.             client.print(bme_humidity, 1);
  272.             client.println(" %rh");
  273.             client.print("Pressure: ");
  274.             client.print(bme_pressure);  //note 1hPa = 1mbar
  275.             client.println(" mbar");
  276.             client.print("Uptime: ");
  277.             client.print(uptime(millis()));
  278.             break;
  279.           }
  280.  
  281.           //if readString containt favicon, serve the favicon
  282.           if (readString.indexOf("favicon") > 0) {
  283.             MySerial.println(F("favicon Served"));
  284.             client.println("HTTP/1.1 200 OK");
  285.             client.println("Content-Type: image/png");
  286.             client.println("Pragma: no-cache");
  287.             client.println("Connection: close");  // the connection will be closed after completion of the response
  288.             client.println();
  289.             //client.println("HTTP/1.1 200 OK\r\nPragma: public\r\nCache-Control: max-age=1\r\nExpires: Thu, 26 Dec 2016 23:59:59 GMT\r\nContent-Type: image/");
  290.             //client.print("png\r\n\r\n");
  291.             for (int i = 0; i < sizeof(favicon); i++) {
  292.               client.write(favicon[i]);
  293.             }
  294.             break;
  295.           }
  296.  
  297.           //for all other queries serve a 404
  298.           else {
  299.             MySerial.println(F("404 Served"));
  300.             client.println("HTTP/1.1 200 OK");
  301.             client.println("Content-Type: text/plain");
  302.             client.println("Pragma: no-cache");
  303.             client.println("Connection: close");  // the connection will be closed after completion of the response
  304.             client.println();
  305.             client.println("404 Error");
  306.             break;
  307.           }
  308.         }
  309.         if (c == '\n') {
  310.           // you're starting a new line
  311.           currentLineIsBlank = true;
  312.         } else if (c != '\r') {
  313.           // you've gotten a character on the current line
  314.           currentLineIsBlank = false;
  315.         }
  316.       }
  317.     }
  318.     // give the web browser time to receive the data
  319.     delay(1);
  320.     // close the connection:
  321.     client.stop();
  322.     MySerial.println("client disconnected");
  323.     MySerial.print(F("Uptime: "));
  324.     MySerial.print(uptime(millis()));
  325.     MySerial.print(F(" readString: "));
  326.     MySerial.println(readString);
  327.   }
  328.  
  329.   //update sensors if there has been no reading for 20 min
  330.   if ((millis() > (lastSensorTime + (20UL * 60 * 1000))) || (millis() < lastSensorTime)) {
  331.     MySerial.println("");
  332.     readSensors();
  333.   }
  334.  
  335.   delay(100);
  336. }
  337.  
Add Comment
Please, Sign In to add comment