Advertisement
pleasedontcode

**Sensor Monitor** rev_36

Oct 21st, 2024
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Arduino 12.95 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: **Sensor Monitor**
  13.     - Source Code NOT compiled for: ESP32 DevKit V1
  14.     - Source Code created on: 2024-10-21 11:24:26
  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. #define ss Serial2
  102.  
  103. unsigned long TEMPO_ATTESA_VISUALIZZAZIONE_VELOCITA = 300;
  104. unsigned long SpeedShowTimer = 0;
  105.  
  106. // Counter to track seconds
  107. unsigned long secondsCounter            = 0;
  108. unsigned long previousMillis            = millis(); // Variable to store the previous millis value
  109. unsigned long currentMillis             = millis();
  110. unsigned long minutesCounter            = 0;
  111.  
  112. // Setup a oneWire instance to communicate with any OneWire devices (not just Maxim/Dallas temperature ICs)
  113. OneWire oneWire1(ONE_WIRE_BUS_Temp1);
  114. OneWire oneWire2(ONE_WIRE_BUS_Temp2);
  115.  
  116. // Pass our oneWire reference to Dallas Temperature.
  117. DallasTemperature sensor1(&oneWire1);
  118. DallasTemperature sensor2(&oneWire2);
  119.  
  120. /****** DEFINITION OF ANALOG INPUTS CHARACTERISTIC CURVES *****/
  121. const uint8_t SEGMENT_POINTS_voltage_Temperature = 10;
  122. const float voltage_Temperature_lookup[2][SEGMENT_POINTS_voltage_Temperature] =
  123. {
  124.     {0.0, 1.2, 1.9, 5.0, 10.0, 14.5, 17.0, 20.0, 30.0, 35.0}, // corrente [V]
  125.     {0.0, 5.0, 7.0, 13.0, 22.0, 29.0, 33.0, 37.0, 56.0, 65.0} // percentuale [°C]
  126. };
  127.  
  128. // Initialize SPIFFS for file storage
  129. void initSPIFFS() {
  130.   if (!SPIFFS.begin(true)) {
  131.     Serial.println("An error occurred while mounting SPIFFS");
  132.     return;
  133.   }
  134.   Serial.println("SPIFFS mounted successfully");
  135. }
  136.  
  137. void setup() {
  138.   // Start Serial for debugging
  139.   Serial.begin(115200);
  140.   delay(1000);
  141.   Serial.println("ciao");
  142.  
  143.   pot.begin(DIGPOT_INC, DIGPOT_UD, DIGPOT_CS);  //  pulse, direction, select // INC = 4, UD = 5, CS = 15
  144.  
  145.   //NON TOGLIERE - SERVE PER NON FAR SBARELLARE LA MACCHINA
  146.   for(int i=0; i<10;i++)
  147.   {
  148.     setCurrentOutput(0);
  149.     delay(20);
  150.     setCurrentOutput(100);
  151.     delay(20);
  152.   }
  153.  
  154.   setCurrentOutput(PWM_output_percentage);
  155.   readMinutesCounterFromEEPROM();
  156.  
  157.   ss.begin(GPSBaud);
  158.   Serial.println("ciao2");
  159.  
  160.   sensor1.begin();
  161.   sensor2.begin();
  162.  
  163.   smartDelay(1000);
  164.  
  165.   ACS.setMidPoint(ADC_Offset);
  166.  
  167.   Serial.println(F("Access Point Web Server"));
  168.  
  169.   // Initialize SPIFFS
  170.   initSPIFFS();
  171.  
  172.   WiFi.mode(WIFI_AP); // Set the ESP32 to access point mode
  173.   if (!WiFi.softAP(ssid, pass)) {
  174.     Serial.println("Soft AP creation failed.");
  175.     while(1);
  176.   }
  177.  
  178.   // Print the IP address of the access point
  179.   IPAddress IP = WiFi.softAPIP();
  180.   Serial.print("Access Point IP Address: ");
  181.   Serial.println(IP);
  182.  
  183.   // Serve the JPEG image
  184.   server.on("/background.jpg", HTTP_GET, [](AsyncWebServerRequest *request){
  185.     Serial.println("0");
  186.     request->send(SPIFFS, "/background.jpg", "image/jpeg");
  187.   });
  188.  
  189.   // Serve the HTML page
  190.   server.on("/", HTTP_GET, [](AsyncWebServerRequest *request){
  191.     Serial.println("1");
  192.     request->send(SPIFFS, "/index.html", "text/html");
  193.   });
  194.  
  195.   server.on("/UPDATEDATA", HTTP_POST, [](AsyncWebServerRequest *request) {
  196.     // Log post request handling
  197.     //Serial.println("postUpdateData");
  198.  
  199.     // Allocate a temporary JsonDocument
  200.     StaticJsonDocument<512> doc;
  201.  
  202.     // Gather data and populate JSON
  203.     updateData(doc);
  204.  
  205.     // Convert the JSON document to string and send it in response
  206.     String response;
  207.     serializeJsonPretty(doc, response);
  208.  
  209.     request->send(200, "application/json", response);
  210.   });
  211.  
  212.   // Start the server
  213.   server.begin();
  214. }
  215.  
  216. void loop() {
  217.   // No logic in the loop; the server works asynchronously
  218.   readGPSAndCheckSpeed();
  219.   readCurrent();
  220.   readVoltage();
  221.   readWaterTank();
  222.   readTemp1();
  223.   readTemp2();
  224.   updateMinutesCounter();
  225.   checkRegeneration();
  226. }
  227.  
  228. // The updateData function to generate the JSON payload
  229. void updateData(JsonDocument &doc) {
  230.   if (velocita > 0.0) {
  231.     doc["speed"] = String(velocita) + String(F(" km/h"));
  232.   } else {
  233.     doc["speed"] = String(F("ERROR"));
  234.   }
  235.   doc["voltageCommandOut"] = String(F("Tensione uscita comando: ")) + String(voltage_output_value) + String(F("/3.3 [V]"));
  236.   doc["percentageCommandOut"] = String(F("Uscita comando PWM: ")) + String(PWM_output_percentage) + String(F(" [%]"));
  237.   doc["waterTankLevel"] = waterLevelEmpty ? String(F("VUOTO")) : String(F("PIENO"));
  238.   doc["powerOnTime"] = String(powerOnTime) + String(F(" min"));
  239.   doc["current"] = String(current) + String(F(" A"));
  240.   doc["voltage"] = String(voltage) + String(F(" V"));
  241.   doc["temperature1"] = String(temperature1) + String(F(" °C"));
  242.   doc["temperature2"] = String(temperature2) + String(F(" °C"));
  243.   doc["set_timer"] = String(F("Timer : ")) + String(set_timer) + String(F(" min"));
  244. }
  245.  
  246. void checkRegeneration() {
  247.   if(set_timer == 0) {
  248.     startRegeneration = false;
  249.   }
  250. }
  251.  
  252. void readMinutesCounterFromEEPROM() {
  253.   // Read the counter value from EEPROM
  254.   unsigned long max_minutesCounter = 0UL - 1UL;
  255.  
  256.   EEPROM.begin(sizeof(powerOnTime));
  257.   EEPROM.get(0, powerOnTime);
  258.  
  259.   if(powerOnTime == max_minutesCounter) {
  260.     powerOnTime = 0;
  261.     Serial.println("Minutes Counter reinitialized");
  262.     saveMinutesCounterInEEPROM();
  263.   }
  264.  
  265.   Serial.print("powerOnTime: ");
  266.   Serial.println(powerOnTime);
  267. }
  268.  
  269. void updateMinutesCounter() {
  270.   currentMillis = millis();
  271.   if((currentMillis - previousMillis) > 1000) {
  272.     previousMillis = currentMillis;
  273.     secondsCounter++;
  274.     if(secondsCounter % 60 == 0) {
  275.       secondsCounter = 0;
  276.       minutesCounter++;
  277.       powerOnTime++;
  278.       if(minutesCounter % 10 == 0) { //salva contatore in EEPROM ogni 10 minuti
  279.         saveMinutesCounterInEEPROM();
  280.       }
  281.       Serial.print("cumulatedMinutesCounter:");
  282.       Serial.println(powerOnTime);
  283.       if(set_timer > 0) {
  284.         set_timer--;
  285.       }
  286.     }
  287.   }    
  288. }
  289.  
  290. void saveMinutesCounterInEEPROM()  {
  291.   EEPROM.put(0, powerOnTime);
  292.   EEPROM.commit();
  293. }
  294.  
  295. void readGPSAndCheckSpeed() {
  296.   if(startRegeneration == false) {
  297.     while (ss.available() > 0) {
  298.       if (gps.encode(ss.read())) {
  299.         checkSpeed();
  300.       }
  301.     }
  302.  
  303.     if (millis() > 5000 && gps.charsProcessed() < 10) {
  304.       velocita = -1.0;
  305.       PWM_output_percentage = PWM_output_percentage_0A;
  306.       setCurrentOutput(PWM_output_percentage);
  307.     }
  308.   } else {
  309.     PWM_output_percentage = lookup_phyData_from_voltage(set_current, SEGMENT_POINTS_voltage_Temperature, &(voltage_Temperature_lookup[0][0]));
  310.     setCurrentOutput(PWM_output_percentage);
  311.   }
  312. }
  313.  
  314. void setCurrentOutput(float PWM_outputPercentage) {
  315.   pot.setPosition(PWM_outputPercentage);   //  position
  316.   voltage_output_value = PWM_outputPercentage * 5.0 / 100.0;  
  317. }
  318.  
  319. void readCurrent() {
  320.   int mA = ACS.mA_DC(30); //30 acquisizioni di media
  321.   float tempCurrent = float(mA) / 1000;
  322.   current = current * 0.7 + tempCurrent * 0.3;
  323. }
  324.  
  325. void readVoltage() {
  326.   float adc_voltage = 0.0;
  327.   float R1 = 30000.0;
  328.   float R2 = 7500.0;
  329.   float ref_voltage = 3.3;
  330.  
  331.   float adc_value = analogRead(voltage_pin);
  332.   adc_voltage  = (adc_value * ref_voltage) / 4096.0;
  333.   voltage = adc_voltage * (R1 + R2) / R2;
  334. }
  335.  
  336. void readWaterTank() {
  337.   waterLevelEmpty = digitalRead(water_level_pin);
  338. }
  339.  
  340. void checkSpeed() {
  341.   if (gps.location.isValid()) {
  342.     velocita = gps.speed.kmph();
  343.     if(millis() - SpeedShowTimer > TEMPO_ATTESA_VISUALIZZAZIONE_VELOCITA) {
  344.       if(velocita > VELOCITA_SOGLIA_HIGH) {
  345.         PWM_output_percentage = PWM_output_percentage_9A;
  346.         setCurrentOutput(PWM_output_percentage);
  347.       } else if(velocita > VELOCITA_SOGLIA_0A_HIGH && velocita < VELOCITA_SOGLIA_LOW) {
  348.         PWM_output_percentage = PWM_output_percentage_5A;
  349.         setCurrentOutput(PWM_output_percentage);
  350.       } else if(velocita < VELOCITA_SOGLIA_0A_LOW) {
  351.         PWM_output_percentage = PWM_output_percentage_0A;
  352.         setCurrentOutput(PWM_output_percentage);
  353.       }
  354.       SpeedShowTimer = millis();
  355.     }
  356.   } else {
  357.     Serial.println(F("NO GPS FIX!"));
  358.     velocita = -1.0;
  359.     PWM_output_percentage = PWM_output_percentage_0A;
  360.     setCurrentOutput(PWM_output_percentage);
  361.   }
  362. }
  363.  
  364. void readTemp1() {
  365.     sensor1.requestTemperatures(); // Send the command to get temperatures
  366.     temperature1 = sensor1.getTempCByIndex(0);
  367.     if(temperature1 == DEVICE_DISCONNECTED_C) {
  368.       temperature1 = -100;
  369.     }  
  370. }
  371.  
  372. void readTemp2() {
  373.     sensor2.requestTemperatures(); // Send the command to get temperatures
  374.     temperature2 = sensor2.getTempCByIndex(0);
  375.     if(temperature2 == DEVICE_DISCONNECTED_C) {
  376.       temperature2 = -100;
  377.     }  
  378. }
  379.  
  380. float lookup_phyData_from_voltage(float voltage, int segment_points, const float* voltage_phyData_lookup) {
  381.     uint8_t index = 0;
  382.     const float *voltagePointer = &voltage_phyData_lookup[0];
  383.     const float *phyDataPointer = &voltage_phyData_lookup[segment_points];
  384.  
  385.     voltage = min(voltage, voltagePointer[segment_points-1]);
  386.     voltage = max(voltage, voltagePointer[0]);
  387.  
  388.     while(voltagePointer[index] <= voltage && index < segment_points) {
  389.         index++;
  390.     }
  391.  
  392.     if(index == 0) {
  393.         return map_f(voltage, voltagePointer[0], voltagePointer[1], phyDataPointer[0], phyDataPointer[1]);
  394.     } else if(index == segment_points) {
  395.         return map_f(voltage, voltagePointer[segment_points-2], voltagePointer[segment_points-1], phyDataPointer[segment_points-2], phyDataPointer[segment_points-1]);
  396.     } else {
  397.         return map_f(voltage, voltagePointer[index-1], voltagePointer[index], phyDataPointer[index-1], phyDataPointer[index]);
  398.     }
  399. }
  400.  
  401. float map_f(float x, float in_min, float in_max, float out_min, float out_max) {
  402.     return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
  403. }
  404.  
  405. static void smartDelay(unsigned long ms) {
  406.   unsigned long start = millis();
  407.   do {
  408.     while (ss.available())
  409.       gps.encode(ss.read());
  410.   } while (millis() - start < ms);
  411. }
  412.  
  413. void resetDataRegeneration() {
  414.   PWM_output_percentage = PWM_output_percentage_0A;
  415.   setCurrentOutput(PWM_output_percentage);
  416.   startRegeneration = false;
  417.   set_current = 0;
  418.   set_timer = 0;
  419. }
  420.  
  421. void extractSubstring(String str, char delimiter)  {
  422.   int startIndex = 0;
  423.   int endIndex = str.indexOf(delimiter);
  424.   int counter = 0;
  425.  
  426.   while(endIndex != -1) {
  427.     String part = str.substring(startIndex, endIndex);
  428.     Serial.println(part);
  429.     if(counter == 0) {
  430.       counter++; // qui c'è 'POST'
  431.     } else if (counter == 1) {
  432.       set_current = part.toInt();
  433.       counter++;
  434.     } else if (counter == 2) {
  435.       set_timer = part.toInt();
  436.       counter++;
  437.     }
  438.     startIndex = endIndex + 1;
  439.     endIndex = str.indexOf(delimiter, startIndex);
  440.   }
  441. }
  442.  
  443. /* END CODE */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement