Advertisement
pleasedontcode

"Web Server" rev_44

Oct 22nd, 2024
68
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Arduino 16.47 KB | None | 0 0
  1. /********* Pleasedontcode.com **********
  2.  
  3.     Pleasedontcode thanks you for automatic code generation! Enjoy your code!
  4.  
  5.     - Terms and Conditions:
  6.     You have a non-exclusive, revocable, worldwide, royalty-free license
  7.     for personal and commercial use. Attribution is optional; modifications
  8.     are allowed, but you're responsible for code maintenance. We're not
  9.     liable for any loss or damage. For full terms,
  10.     please visit pleasedontcode.com/termsandconditions.
  11.  
  12.     - Project: "Web Server"
  13.     - Source Code NOT compiled for: ESP32 DevKit V1
  14.     - Source Code created on: 2024-10-22 10:02:09
  15.  
  16. ********* Pleasedontcode.com **********/
  17.  
  18. /****** SYSTEM REQUIREMENTS *****/
  19. /****** SYSTEM REQUIREMENT 1 *****/
  20.     /* merge code. */
  21. /****** END SYSTEM REQUIREMENTS *****/
  22.  
  23. /* START CODE */
  24.  
  25. /****** DEFINITION OF LIBRARIES *****/
  26. #include <TinyGPSPlus.h>
  27. #include "ACS712.h"
  28. #include <WiFi.h>
  29. #include <ESPAsyncWebServer.h>
  30. #include <SPIFFS.h>
  31. #include <ArduinoJson.h>
  32. #include <EEPROM.h>
  33. #include <OneWire.h>
  34. #include <DallasTemperature.h>
  35. #include "X9C10X.h"
  36.  
  37. /****** FUNCTION PROTOTYPES *****/
  38. void setup(void);
  39. void loop(void);
  40.  
  41. // Access Point credentials
  42. char ssid[] = "pleasedontcode.com";        // your network SSID (name)
  43. char pass[] = "prova1234";        // your network password (use for WPA, or use as key for WEP)
  44.  
  45. // Create an instance of the web server
  46. AsyncWebServer server(80);
  47.  
  48. TinyGPSPlus gps;
  49.  
  50. #define VELOCITA_SOGLIA_HIGH 75.0 //km/h
  51. #define VELOCITA_SOGLIA_LOW 65.0 //km/h
  52. #define VELOCITA_SOGLIA_0A_HIGH  20.0 //km/h - soglia sotto 15km/h si spegne l'erogazione corrente
  53. #define VELOCITA_SOGLIA_0A_LOW  10.0 //km/h
  54.  
  55. //PINS
  56. const int water_level_pin = 18;
  57. const int voltage_pin     = 35;
  58. const int current_pin     = 34;
  59. const int tempSensor1_pin = 33;
  60. const int tempSensor2_pin = 32;
  61. const int ONE_WIRE_BUS_Temp1 = 19; //sonda temp 1
  62. const int ONE_WIRE_BUS_Temp2 = 21; //sonda temp 2
  63. const int DIGPOT_INC      = 4;    // pin INC - X9C103S
  64. const int DIGPOT_UD       = 5;    // pin UD - X9C103S
  65. const int DIGPOT_CS       = 15;   // pin CS - X9C103S
  66.  
  67. const float PWM_output_percentage_0A = 0.0; //0%
  68. const float PWM_output_percentage_9A = 20.0; //20% --> 1V/5V
  69. const float PWM_output_percentage_5A = 13.0; //13% --> 0,65V/5V
  70.  
  71. // DATI globali da trasferire
  72. float PWM_output_percentage = 0.0;
  73. float velocita = 0.0;
  74. float voltage_output_value = 0.0;
  75. bool waterLevelEmpty = true;
  76. float voltage = 0.0;
  77. float current = 0.0;
  78. float temperature1 = 0.0;
  79. float temperature2 = 0.0;
  80. unsigned long powerOnTime = 0; //minutes
  81.  
  82. boolean startRegeneration = false;
  83. unsigned int set_current  = 0;
  84. unsigned int set_timer    = 0;
  85.  
  86. //configurazione ACS712 da 30A
  87. unsigned int ADC_Offset = 1930;
  88. ACS712  ACS(current_pin, 3.3, 4095, 40); //pin 34 per acquisizione sensore corrente; l'alimentazione sensore è 3.3V
  89.  
  90. X9C10X pot(10000);  //  10KΩ  - potenziometro digitale X9C103S da 10kΩ
  91.  
  92. void printWiFiStatus();
  93. void printWebPage();
  94. void checkClientRequest(String currentLine);
  95.  
  96. bool ReplyWebPageContent = true;
  97. bool ReplyResetTime = false;
  98. bool postUpdateData = false;
  99.  
  100. static const int GPSBaud = 9600;
  101.  
  102. // The serial connection to the GPS device
  103. #define ss Serial2
  104.  
  105. unsigned long TEMPO_ATTESA_VISUALIZZAZIONE_VELOCITA = 300;
  106. unsigned long SpeedShowTimer = 0;
  107.  
  108. // Counter to track seconds
  109. unsigned long secondsCounter            = 0;
  110. unsigned long previousMillis            = millis(); // Variable to store the previous millis value
  111. unsigned long currentMillis             = millis();
  112. unsigned long minutesCounter            = 0;
  113.  
  114. // Setup a oneWire instance to communicate with any OneWire devices (not just Maxim/Dallas temperature ICs)
  115. OneWire oneWire1(ONE_WIRE_BUS_Temp1);
  116. OneWire oneWire2(ONE_WIRE_BUS_Temp2);
  117.  
  118. // Pass our oneWire reference to Dallas Temperature.
  119. DallasTemperature sensor1(&oneWire1);
  120. DallasTemperature sensor2(&oneWire2);
  121.  
  122. /****** DEFINITION OF ANALOG INPUTS CHARACTERISTIC CURVES *****/
  123. const uint8_t SEGMENT_POINTS_voltage_Temperature = 10;
  124. const float voltage_Temperature_lookup[2][SEGMENT_POINTS_voltage_Temperature] =
  125. {
  126.     {0.0, 1.2, 1.9, 5.0, 10.0, 14.5, 17.0, 20.0, 30.0, 35.0}, // corrente [V]
  127.     {0.0, 5.0, 7.0, 13.0, 22.0, 29.0, 33.0, 37.0, 56.0, 65.0} // percentuale [°C]
  128. };
  129.  
  130. // Initialize SPIFFS for file storage
  131. void initSPIFFS() {
  132.   if (!SPIFFS.begin(true)) {
  133.     Serial.println("An error occurred while mounting SPIFFS");
  134.     return;
  135.   }
  136.   Serial.println("SPIFFS mounted successfully");
  137. }
  138.  
  139. void setup() {
  140.   // Start Serial for debugging
  141.   Serial.begin(115200);
  142.  
  143.   delay(1000);
  144.  
  145.   Serial.println("ciao");
  146.  
  147.   pot.begin(DIGPOT_INC, DIGPOT_UD, DIGPOT_CS);  //  pulse, direction, select // INC = 4, UD = 5, CS = 15
  148.  
  149.   //NON TOGLIERE - SERVE PER NON FAR SBARELLARE LA MACCHINA
  150.   for(int i=0; i<10;i++)
  151.   {
  152.     setCurrentOutput(0);
  153.     delay(20);
  154.     setCurrentOutput(100);
  155.     delay(20);
  156.   }
  157.  
  158.   setCurrentOutput(PWM_output_percentage);
  159.   readMinutesCounterFromEEPROM();
  160.  
  161.   ss.begin(GPSBaud);
  162.   Serial.println("ciao2");
  163.  
  164.   sensor1.begin();
  165.   sensor2.begin();
  166.  
  167.   smartDelay(1000);
  168.  
  169.   ACS.setMidPoint(ADC_Offset);
  170.  
  171.   Serial.println(F("Access Point Web Server"));
  172.  
  173.   // Initialize SPIFFS
  174.   initSPIFFS();
  175.  
  176.   WiFi.mode(WIFI_AP); // Set the ESP32 to access point mode
  177.   if (!WiFi.softAP(ssid, pass)) {
  178.     Serial.println("Soft AP creation failed.");
  179.     while(1);
  180.   }
  181.  
  182.   // Print the IP address of the access point
  183.   IPAddress IP = WiFi.softAPIP();
  184.   Serial.print("Access Point IP Address: ");
  185.   Serial.println(IP);
  186.  
  187.   // Serve the JPEG image
  188.   server.on("/background.jpg", HTTP_GET, [](AsyncWebServerRequest *request){
  189.     Serial.println("0");
  190.     request->send(SPIFFS, "/background.jpg", "image/jpeg");
  191.   });
  192.  
  193.   // Serve the HTML page
  194.   server.on("/", HTTP_GET, [](AsyncWebServerRequest *request){
  195.     Serial.println("1");
  196.     request->send(SPIFFS, "/index.html", "text/html");
  197.   });
  198.  
  199.   server.on("/UPDATEDATA", HTTP_POST, [](AsyncWebServerRequest *request) {
  200.     // Log post request handling
  201.     //Serial.println("postUpdateData");
  202.  
  203.     // Allocate a temporary JsonDocument
  204.     StaticJsonDocument<512> doc;
  205.  
  206.     // Gather data and populate JSON
  207.     updateData(doc);
  208.  
  209.     // Convert the JSON document to string and send it in response
  210.     String response;
  211.     serializeJsonPretty(doc, response);
  212.  
  213.     request->send(200, "application/json", response);
  214.   });
  215.  
  216.   // Start the server
  217.   server.begin();
  218. }
  219.  
  220. void loop() {
  221.   // No logic in the loop; the server works asynchronously
  222.  
  223.   readGPSAndCheckSpeed();
  224.   readCurrent();
  225.   readVoltage();
  226.   readWaterTank();
  227.   readTemp1();
  228.   readTemp2();
  229.   updateMinutesCounter();
  230.   checkRegeneration();
  231. }
  232.  
  233. // The updateData function to generate the JSON payload
  234. void updateData(JsonDocument &doc) {
  235.   if (velocita > 0.0) {
  236.     doc["speed"] = String(velocita) + String(F(" km/h"));
  237.   } else {
  238.     doc["speed"] = String(F("ERROR"));
  239.   }
  240.   doc["voltageCommandOut"] = String(F("Tensione uscita comando: ")) + String(voltage_output_value) + String(F("/3.3 [V]"));
  241.   doc["percentageCommandOut"] = String(F("Uscita comando PWM: ")) + String(PWM_output_percentage) + String(F(" [%]"));
  242.  
  243.   doc["waterTankLevel"] = waterLevelEmpty ? String(F("VUOTO")) : String(F("PIENO"));
  244.   doc["powerOnTime"] = String(powerOnTime) + String(F(" min"));
  245.   doc["current"] = String(current) + String(F(" A"));
  246.   doc["voltage"] = String(voltage) + String(F(" V"));
  247.   doc["temperature1"] = String(temperature1) + String(F(" °C"));
  248.   doc["temperature2"] = String(temperature2) + String(F(" °C"));
  249.   doc["set_timer"] = String(F("Timer : ")) + String(set_timer) + String(F(" min"));
  250. }
  251.  
  252. void checkRegeneration() {
  253.   if(set_timer == 0)
  254.   {
  255.     startRegeneration = false;
  256.   }
  257. }
  258.  
  259. void readMinutesCounterFromEEPROM() {
  260.   // Read the counter value from EEPROM
  261.   unsigned long max_minutesCounter = 0UL - 1UL;
  262.  
  263.   EEPROM.begin(sizeof(powerOnTime));
  264.   EEPROM.get( 0, powerOnTime );
  265.  
  266.   if(powerOnTime == max_minutesCounter) {
  267.     powerOnTime = 0;
  268.     Serial.println("Minutes Counter reinitialized");
  269.     saveMinutesCounterInEEPROM();
  270.   }
  271.  
  272.   Serial.print("powerOnTime: ");
  273.   Serial.println(powerOnTime);
  274. }
  275.  
  276. void updateMinutesCounter() {
  277.   currentMillis = millis();
  278.   if( (currentMillis - previousMillis) > 1000) {
  279.     previousMillis = currentMillis;
  280.     secondsCounter++;
  281.     if(secondsCounter % 60 == 0) {
  282.       secondsCounter = 0;
  283.       minutesCounter++;
  284.       powerOnTime++;
  285.       if(minutesCounter % 10 == 0) { //salva contatore in EEPROM ogni 10 minuti
  286.         saveMinutesCounterInEEPROM();
  287.       }
  288.       Serial.print("cumulatedMinutesCounter:");
  289.       Serial.println(powerOnTime);
  290.       if(set_timer > 0) {
  291.         set_timer--;
  292.       }
  293.     }
  294.   }    
  295. }
  296.  
  297. void saveMinutesCounterInEEPROM()  {
  298.   EEPROM.put(0, powerOnTime);
  299.   EEPROM.commit();
  300. }
  301.  
  302. void readGPSAndCheckSpeed() {
  303.   if(startRegeneration == false) {
  304.     while (ss.available() > 0) {
  305.       if (gps.encode(ss.read())) {
  306.         checkSpeed();
  307.       }
  308.     }
  309.  
  310.     if (millis() > 5000 && gps.charsProcessed() < 10)
  311.     {
  312.       velocita = -1.0;
  313.       PWM_output_percentage = PWM_output_percentage_0A;
  314.       setCurrentOutput(PWM_output_percentage);
  315.     }
  316.   } else {
  317.     PWM_output_percentage = lookup_phyData_from_voltage(set_current, SEGMENT_POINTS_voltage_Temperature, &(voltage_Temperature_lookup[0][0]));
  318.     setCurrentOutput(PWM_output_percentage);
  319.   }
  320. }
  321.  
  322. void setCurrentOutput(float PWM_outputPercentage)
  323. {
  324.   pot.setPosition(PWM_outputPercentage);   //  position
  325.   voltage_output_value = PWM_outputPercentage*5.0/100.0;  
  326. }
  327.  
  328. void readCurrent(){
  329.   int mA = ACS.mA_DC(30); //30 acquisizioni di media
  330.   float tempCurrent = float(mA)/1000;
  331.   current = current*0.7 + tempCurrent*0.3;
  332. }
  333.  
  334. void readVoltage() {
  335.   // Floats for ADC voltage & Input voltage
  336.   float adc_voltage = 0.0;
  337.  
  338.   // Floats for resistor values in divider (in ohms)
  339.   float R1 = 30000.0;
  340.   float R2 = 7500.0;
  341.  
  342.   // Float for Reference Voltage
  343.   float ref_voltage = 3.3;
  344.  
  345.   // Read the Analog Input
  346.   float adc_value = analogRead(voltage_pin);
  347.  
  348.   // Determine voltage at ADC input
  349.   adc_voltage  = (adc_value * ref_voltage) / 4096.0;
  350.  
  351.   // Calculate voltage at divider input
  352.   voltage = adc_voltage*(R1+R2)/R2;
  353. }
  354.  
  355. void readWaterTank() {
  356.   waterLevelEmpty = digitalRead(water_level_pin);
  357. }
  358.  
  359. void checkSpeed() {
  360.     if (gps.location.isValid())
  361.     {
  362.         velocita = gps.speed.kmph();
  363.         if(millis() - SpeedShowTimer > TEMPO_ATTESA_VISUALIZZAZIONE_VELOCITA)
  364.         {
  365.           if(velocita > VELOCITA_SOGLIA_HIGH)
  366.           {
  367.             PWM_output_percentage = PWM_output_percentage_9A;
  368.             setCurrentOutput(PWM_output_percentage);
  369.           }
  370.           else if(velocita > VELOCITA_SOGLIA_0A_HIGH && velocita < VELOCITA_SOGLIA_LOW)
  371.           {
  372.             PWM_output_percentage = PWM_output_percentage_5A;
  373.             setCurrentOutput(PWM_output_percentage);
  374.           }
  375.           else if(velocita < VELOCITA_SOGLIA_0A_LOW)
  376.           {
  377.             PWM_output_percentage = PWM_output_percentage_0A;
  378.             setCurrentOutput(PWM_output_percentage);
  379.           }
  380.          
  381.           SpeedShowTimer = millis();
  382.         }
  383.     }
  384.     else
  385.     {
  386.       Serial.println(F("NO GPS FIX!"));
  387.       velocita = -1.0;
  388.       PWM_output_percentage = PWM_output_percentage_0A;
  389.       setCurrentOutput(PWM_output_percentage);
  390.     }
  391. }
  392.  
  393. void displayInfo()
  394. {
  395.   Serial.print(F("Location: "));
  396.    printInt(gps.satellites.value(), gps.satellites.isValid(), 5);
  397.   printFloat(gps.hdop.hdop(), gps.hdop.isValid(), 6, 1);
  398.   printFloat(gps.location.lat(), gps.location.isValid(), 11, 6);
  399.  
  400.    printFloat(gps.location.lat(), gps.location.isValid(), 11, 6);
  401.   printFloat(gps.location.lng(), gps.location.isValid(), 12, 6);
  402.   while(1);
  403.   Serial.print(gps.location.lat(), 6);
  404.     Serial.print(F(","));
  405.     Serial.print(gps.location.lng(), 6);
  406.  
  407.      Serial.print(gps.date.month());
  408.     Serial.print(F("/"));
  409.     Serial.print(gps.date.day());
  410.     Serial.print(F("/"));
  411.     Serial.print(gps.date.year());
  412.  
  413.  
  414.   if (gps.location.isValid())
  415.   {
  416.     Serial.print(gps.location.lat(), 6);
  417.     Serial.print(F(","));
  418.     Serial.print(gps.location.lng(), 6);
  419.   }
  420.   else
  421.   {
  422.     Serial.print(F("INVALID"));
  423.   }
  424.  
  425.   Serial.print(F("  Date/Time: "));
  426.   if (gps.date.isValid())
  427.   {
  428.     Serial.print(gps.date.month());
  429.     Serial.print(F("/"));
  430.     Serial.print(gps.date.day());
  431.     Serial.print(F("/"));
  432.     Serial.print(gps.date.year());
  433.   }
  434.   else
  435.   {
  436.     Serial.print(F("INVALID"));
  437.   }
  438.  
  439.   Serial.print(F(" "));
  440.   if (gps.time.isValid())
  441.   {
  442.     if (gps.time.hour() < 10) Serial.print(F("0"));
  443.     Serial.print(gps.time.hour());
  444.     Serial.print(F(":"));
  445.     if (gps.time.minute() < 10) Serial.print(F("0"));
  446.     Serial.print(gps.time.minute());
  447.     Serial.print(F(":"));
  448.     if (gps.time.second() < 10) Serial.print(F("0"));
  449.     Serial.print(gps.time.second());
  450.     Serial.print(F("."));
  451.     if (gps.time.centisecond() < 10) Serial.print(F("0"));
  452.     Serial.print(gps.time.centisecond());
  453.   }
  454.   else
  455.   {
  456.     Serial.print(F("INVALID"));
  457.   }
  458.  
  459.   Serial.println();
  460. }
  461.  
  462. static void printFloat(float val, bool valid, int len, int prec)
  463. {
  464.   if (!valid)
  465.   {
  466.     while (len-- > 1)
  467.       Serial.print('*');
  468.     Serial.print(' ');
  469.   }
  470.   else
  471.   {
  472.     Serial.print(val, prec);
  473.     int vi = abs((int)val);
  474.     int flen = prec + (val < 0.0 ? 2 : 1); // . and -
  475.     flen += vi >= 1000 ? 4 : vi >= 100 ? 3 : vi >= 10 ? 2 : 1;
  476.     for (int i=flen; i<len; ++i)
  477.       Serial.print(' ');
  478.   }
  479.   smartDelay(0);
  480. }
  481.  
  482. static void printInt(unsigned long val, bool valid, int len)
  483. {
  484.   char sz[32] = "*****************";
  485.   if (valid)
  486.     sprintf(sz, "%ld", val);
  487.   sz[len] = 0;
  488.   for (int i=strlen(sz); i<len; ++i)
  489.     sz[i] = ' ';
  490.   if (len > 0)
  491.     sz[len-1] = ' ';
  492.   Serial.print(sz);
  493.   smartDelay(0);
  494. }
  495.  
  496. // This custom version of delay() ensures that the gps object
  497. // is being "fed".
  498. static void smartDelay(unsigned long ms)
  499. {
  500.   unsigned long start = millis();
  501.   do
  502.   {
  503.     while (ss.available())
  504.       gps.encode(ss.read());
  505.   } while (millis() - start < ms);
  506. }
  507.  
  508. void resetDataRegeneration() {
  509.   PWM_output_percentage = PWM_output_percentage_0A;
  510.   setCurrentOutput(PWM_output_percentage);
  511.   startRegeneration = false;
  512.   set_current = 0;
  513.   set_timer = 0;
  514. }
  515.  
  516. void extractSubstring(String str, char delimiter)  {
  517.   int startIndex = 0;
  518.   int endIndex = str.indexOf(delimiter);
  519.  
  520.   int counter = 0;
  521.  
  522.   while(endIndex != -1) {
  523.     String part = str.substring(startIndex, endIndex);
  524.     Serial.println(part);
  525.     if(counter == 0) {
  526.       counter++; // qui c'è 'POST'
  527.     } else if (counter == 1) {
  528.       set_current = part.toInt();
  529.       counter++;
  530.     } else if (counter == 2) {
  531.       set_timer = part.toInt();
  532.       counter++;
  533.     }
  534.     startIndex = endIndex + 1;
  535.     endIndex = str.indexOf(delimiter, startIndex);
  536.   }
  537. }
  538.  
  539. float lookup_phyData_from_voltage(float voltage, int segment_points, const float* voltage_phyData_lookup)
  540. {
  541.     // Search table for appropriate value.
  542.     uint8_t index = 0;
  543.  
  544.     const float *voltagePointer = &voltage_phyData_lookup[0];
  545.     const float *phyDataPointer = &voltage_phyData_lookup[segment_points];
  546.  
  547.     // Perform minimum and maximum voltage saturation based on characteristic curve
  548.     voltage = min(voltage, voltagePointer[segment_points-1]);
  549.     voltage = max(voltage, voltagePointer[0]);
  550.  
  551.     while( voltagePointer[index] <= voltage && index < segment_points )
  552.         index++;
  553.  
  554.     // If index is zero, physical value is smaller than our table range
  555.     if( index==0 )
  556.     {
  557.         return map_f( voltage,
  558.             voltagePointer[0],   // X1
  559.             voltagePointer[1],   // X2
  560.             phyDataPointer[0],   // Y1
  561.             phyDataPointer[1] ); // Y2
  562.     }
  563.     // If index is maxed out, phyisical value is larger than our range.
  564.     else if( index==segment_points )
  565.     {
  566.         return map_f( voltage,
  567.             voltagePointer[segment_points-2],   // X1
  568.             voltagePointer[segment_points-1],   // X2
  569.             phyDataPointer[segment_points-2],   // Y1
  570.             phyDataPointer[segment_points-1] ); // Y2
  571.     }
  572.     // index is between 0 and max, just right
  573.     else
  574.     {
  575.         return map_f( voltage,
  576.             voltagePointer[index-1], // X1
  577.             voltagePointer[index],    // X2
  578.             phyDataPointer[index-1], // Y1
  579.             phyDataPointer[index] );  // Y2
  580.     }
  581. }
  582.  
  583. float map_f(float x, float in_min, float in_max, float out_min, float out_max)
  584. {
  585.     return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
  586. }
  587.  
  588. static float voltage_average_temp1 = 0.0;
  589. static float voltage_average_temp2 = 0.0;
  590.  
  591. void readTemp1()
  592. {
  593.     sensor1.requestTemperatures(); // Send the command to get temperatures
  594.     temperature1  =sensor1.getTempCByIndex(0);
  595.     if(temperature1 == DEVICE_DISCONNECTED_C)
  596.     {
  597.       temperature1  = -100;
  598.     }  
  599. }
  600.  
  601. void readTemp2()
  602. {
  603.     sensor2.requestTemperatures(); // Send the command to get temperatures
  604.     temperature2  =sensor2.getTempCByIndex(0);
  605.     if(temperature2 == DEVICE_DISCONNECTED_C)
  606.     {
  607.       temperature2  = -100;
  608.     }  
  609. }
  610.  
  611. /* END CODE */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement