Advertisement
pleasedontcode

**Sensor Monitor** rev_30

Oct 21st, 2024
103
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Arduino 15.06 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 08:45:58
  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
  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. // Global data to transfer
  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. // Configuration ACS712 da 30A
  87. unsigned int ADC_Offset = 1930;
  88. ACS712  ACS(current_pin, 3.3, 4095, 40); // pin 34 for current sensor acquisition; sensor power is 3.3V
  89.  
  90. X9C10X pot(10000);  //  10KΩ  - digital potentiometer X9C103S from 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
  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.   // Prevent machine from malfunctioning
  146.   for(int i=0; i<10; i++) {
  147.     setCurrentOutput(0);
  148.     delay(20);
  149.     setCurrentOutput(100);
  150.     delay(20);
  151.   }
  152.  
  153.   setCurrentOutput(PWM_output_percentage);
  154.   readMinutesCounterFromEEPROM();
  155.  
  156.   ss.begin(GPSBaud);
  157.   Serial.println("ciao2");
  158.  
  159.   sensor1.begin();
  160.   sensor2.begin();
  161.  
  162.   smartDelay(1000);
  163.  
  164.   ACS.setMidPoint(ADC_Offset);
  165.  
  166.   Serial.println(F("Access Point Web Server"));
  167.  
  168.   // Initialize SPIFFS
  169.   initSPIFFS();
  170.  
  171.   WiFi.mode(WIFI_AP); // Set the ESP32 to access point mode
  172.   if (!WiFi.softAP(ssid, pass)) {
  173.     Serial.println("Soft AP creation failed.");
  174.     while(1);
  175.   }
  176.  
  177.   // Print the IP address of the access point
  178.   IPAddress IP = WiFi.softAPIP();
  179.   Serial.print("Access Point IP Address: ");
  180.   Serial.println(IP);
  181.  
  182.   // Serve the JPEG image
  183.   server.on("/background.jpg", HTTP_GET, [](AsyncWebServerRequest *request){
  184.     Serial.println("0");
  185.     request->send(SPIFFS, "/background.jpg", "image/jpeg");
  186.   });
  187.  
  188.   // Serve the HTML page
  189.   server.on("/", HTTP_GET, [](AsyncWebServerRequest *request){
  190.     Serial.println("1");
  191.     request->send(SPIFFS, "/index.html", "text/html");
  192.   });
  193.  
  194.   server.on("/UPDATEDATA", HTTP_POST, [](AsyncWebServerRequest *request) {
  195.     // Allocate a temporary JsonDocument
  196.     StaticJsonDocument<512> doc;
  197.  
  198.     // Gather data and populate JSON
  199.     updateData(doc);
  200.  
  201.     // Convert the JSON document to string and send it in response
  202.     String response;
  203.     serializeJsonPretty(doc, response);
  204.  
  205.     request->send(200, "application/json", response);
  206.   });
  207.  
  208.   // Start the server
  209.   server.begin();
  210. }
  211.  
  212. void loop() {
  213.   // No logic in the loop; the server works asynchronously
  214.   readGPSAndCheckSpeed();
  215.   readCurrent();
  216.   readVoltage();
  217.   readWaterTank();
  218.   readTemp1();
  219.   readTemp2();
  220.   updateMinutesCounter();
  221.   checkRegeneration();
  222. }
  223.  
  224. // The updateData function to generate the JSON payload
  225. void updateData(JsonDocument &doc) {
  226.   if (velocita > 0.0) {
  227.     doc["speed"] = String(velocita) + String(F(" km/h"));
  228.   } else {
  229.     doc["speed"] = String(F("ERROR"));
  230.   }
  231.   doc["voltageCommandOut"] = String(F("Tensione uscita comando: ")) + String(voltage_output_value) + String(F("/3.3 [V]"));
  232.   doc["percentageCommandOut"] = String(F("Uscita comando PWM: ")) + String(PWM_output_percentage) + String(F(" [%]"));
  233.   doc["waterTankLevel"] = waterLevelEmpty ? String(F("VUOTO")) : String(F("PIENO"));
  234.   doc["powerOnTime"] = String(powerOnTime) + String(F(" min"));
  235.   doc["current"] = String(current) + String(F(" A"));
  236.   doc["voltage"] = String(voltage) + String(F(" V"));
  237.   doc["temperature1"] = String(temperature1) + String(F(" °C"));
  238.   doc["temperature2"] = String(temperature2) + String(F(" °C"));
  239.   doc["set_timer"] = String(F("Timer : ")) + String(set_timer) + String(F(" min"));
  240. }
  241.  
  242. void checkRegeneration() {
  243.   if(set_timer == 0) {
  244.     startRegeneration = false;
  245.   }
  246. }
  247.  
  248. void readMinutesCounterFromEEPROM() {
  249.   // Read the counter value from EEPROM
  250.   unsigned long max_minutesCounter = 0UL - 1UL;
  251.  
  252.   EEPROM.begin(sizeof(powerOnTime));
  253.   EEPROM.get(0, powerOnTime);
  254.  
  255.   if(powerOnTime == max_minutesCounter) {
  256.     powerOnTime = 0;
  257.     Serial.println("Minutes Counter reinitialized");
  258.     saveMinutesCounterInEEPROM();
  259.   }
  260.  
  261.   Serial.print("powerOnTime: ");
  262.   Serial.println(powerOnTime);
  263. }
  264.  
  265. void updateMinutesCounter() {
  266.   currentMillis = millis();
  267.   if((currentMillis - previousMillis) > 1000) {
  268.     previousMillis = currentMillis;
  269.     secondsCounter++;
  270.     if(secondsCounter % 60 == 0) {
  271.       secondsCounter = 0;
  272.       minutesCounter++;
  273.       powerOnTime++;
  274.       if(minutesCounter % 10 == 0) { // Save counter in EEPROM every 10 minutes
  275.         saveMinutesCounterInEEPROM();
  276.       }
  277.       Serial.print("cumulatedMinutesCounter:");
  278.       Serial.println(powerOnTime);
  279.       if(set_timer > 0) {
  280.         set_timer--;
  281.       }
  282.     }
  283.   }    
  284. }
  285.  
  286. void saveMinutesCounterInEEPROM()  {
  287.   EEPROM.put(0, powerOnTime);
  288.   EEPROM.commit();
  289. }
  290.  
  291. void readGPSAndCheckSpeed() {
  292.   if(startRegeneration == false) {
  293.     while (ss.available() > 0) {
  294.       if (gps.encode(ss.read())) {
  295.         checkSpeed();
  296.       }
  297.     }
  298.  
  299.     if (millis() > 5000 && gps.charsProcessed() < 10) {
  300.       velocita = -1.0;
  301.       PWM_output_percentage = PWM_output_percentage_0A;
  302.       setCurrentOutput(PWM_output_percentage);
  303.     }
  304.   } else {
  305.     PWM_output_percentage = lookup_phyData_from_voltage(set_current, SEGMENT_POINTS_voltage_Temperature, &(voltage_Temperature_lookup[0][0]));
  306.     setCurrentOutput(PWM_output_percentage);
  307.   }
  308. }
  309.  
  310. void setCurrentOutput(float PWM_outputPercentage) {
  311.   pot.setPosition(PWM_outputPercentage);   //  position
  312.   voltage_output_value = PWM_outputPercentage * 5.0 / 100.0;  
  313. }
  314.  
  315. void readCurrent() {
  316.   int mA = ACS.mA_DC(30); // 30 acquisitions average
  317.   float tempCurrent = float(mA) / 1000;
  318.   current = current * 0.7 + tempCurrent * 0.3;
  319. }
  320.  
  321. void readVoltage() {
  322.   float adc_voltage = 0.0;
  323.   float R1 = 30000.0;
  324.   float R2 = 7500.0;
  325.   float ref_voltage = 3.3;
  326.  
  327.   float adc_value = analogRead(voltage_pin);
  328.   adc_voltage  = (adc_value * ref_voltage) / 4096.0;
  329.   voltage = adc_voltage * (R1 + R2) / R2;
  330. }
  331.  
  332. void readWaterTank() {
  333.   waterLevelEmpty = digitalRead(water_level_pin);
  334. }
  335.  
  336. void checkSpeed() {
  337.   if (gps.location.isValid()) {
  338.     velocita = gps.speed.kmph();
  339.     if(millis() - SpeedShowTimer > TEMPO_ATTESA_VISUALIZZAZIONE_VELOCITA) {
  340.       if(velocita > VELOCITA_SOGLIA_HIGH) {
  341.         PWM_output_percentage = PWM_output_percentage_9A;
  342.         setCurrentOutput(PWM_output_percentage);
  343.       } else if(velocita > VELOCITA_SOGLIA_0A_HIGH && velocita < VELOCITA_SOGLIA_LOW) {
  344.         PWM_output_percentage = PWM_output_percentage_5A;
  345.         setCurrentOutput(PWM_output_percentage);
  346.       } else if(velocita < VELOCITA_SOGLIA_0A_LOW) {
  347.         PWM_output_percentage = PWM_output_percentage_0A;
  348.         setCurrentOutput(PWM_output_percentage);
  349.       }
  350.       SpeedShowTimer = millis();
  351.     }
  352.   } else {
  353.     Serial.println(F("NO GPS FIX!"));
  354.     velocita = -1.0;
  355.     PWM_output_percentage = PWM_output_percentage_0A;
  356.     setCurrentOutput(PWM_output_percentage);
  357.   }
  358. }
  359.  
  360. void displayInfo() {
  361.   Serial.print(F("Location: "));
  362.   printInt(gps.satellites.value(), gps.satellites.isValid(), 5);
  363.   printFloat(gps.hdop.hdop(), gps.hdop.isValid(), 6, 1);
  364.   printFloat(gps.location.lat(), gps.location.isValid(), 11, 6);
  365.   printFloat(gps.location.lng(), gps.location.isValid(), 12, 6);
  366.   if (gps.location.isValid()) {
  367.     Serial.print(gps.location.lat(), 6);
  368.     Serial.print(F(","));
  369.     Serial.print(gps.location.lng(), 6);
  370.   } else {
  371.     Serial.print(F("INVALID"));
  372.   }
  373.   Serial.print(F("  Date/Time: "));
  374.   if (gps.date.isValid()) {
  375.     Serial.print(gps.date.month());
  376.     Serial.print(F("/"));
  377.     Serial.print(gps.date.day());
  378.     Serial.print(F("/"));
  379.     Serial.print(gps.date.year());
  380.   } else {
  381.     Serial.print(F("INVALID"));
  382.   }
  383.   Serial.print(F(" "));
  384.   if (gps.time.isValid()) {
  385.     if (gps.time.hour() < 10) Serial.print(F("0"));
  386.     Serial.print(gps.time.hour());
  387.     Serial.print(F(":"));
  388.     if (gps.time.minute() < 10) Serial.print(F("0"));
  389.     Serial.print(gps.time.minute());
  390.     Serial.print(F(":"));
  391.     if (gps.time.second() < 10) Serial.print(F("0"));
  392.     Serial.print(gps.time.second());
  393.     Serial.print(F("."));
  394.     if (gps.time.centisecond() < 10) Serial.print(F("0"));
  395.     Serial.print(gps.time.centisecond());
  396.   } else {
  397.     Serial.print(F("INVALID"));
  398.   }
  399.   Serial.println();
  400. }
  401.  
  402. static void printFloat(float val, bool valid, int len, int prec) {
  403.   if (!valid) {
  404.     while (len-- > 1)
  405.       Serial.print('*');
  406.     Serial.print(' ');
  407.   } else {
  408.     Serial.print(val, prec);
  409.     int vi = abs((int)val);
  410.     int flen = prec + (val < 0.0 ? 2 : 1);
  411.     flen += vi >= 1000 ? 4 : vi >= 100 ? 3 : vi >= 10 ? 2 : 1;
  412.     for (int i = flen; i < len; ++i)
  413.       Serial.print(' ');
  414.   }
  415.   smartDelay(0);
  416. }
  417.  
  418. static void printInt(unsigned long val, bool valid, int len) {
  419.   char sz[32] = "*****************";
  420.   if (valid)
  421.     sprintf(sz, "%ld", val);
  422.   sz[len] = 0;
  423.   for (int i = strlen(sz); i < len; ++i)
  424.     sz[i] = ' ';
  425.   if (len > 0)
  426.     sz[len - 1] = ' ';
  427.   Serial.print(sz);
  428.   smartDelay(0);
  429. }
  430.  
  431. // This custom version of delay() ensures that the gps object
  432. // is being "fed".
  433. static void smartDelay(unsigned long ms) {
  434.   unsigned long start = millis();
  435.   do {
  436.     while (ss.available())
  437.       gps.encode(ss.read());
  438.   } while (millis() - start < ms);
  439. }
  440.  
  441. void resetDataRegeneration() {
  442.   PWM_output_percentage = PWM_output_percentage_0A;
  443.   setCurrentOutput(PWM_output_percentage);
  444.   startRegeneration = false;
  445.   set_current = 0;
  446.   set_timer = 0;
  447. }
  448.  
  449. void extractSubstring(String str, char delimiter)  {
  450.   int startIndex = 0;
  451.   int endIndex = str.indexOf(delimiter);
  452.   int counter = 0;
  453.  
  454.   while(endIndex != -1) {
  455.     String part = str.substring(startIndex, endIndex);
  456.     Serial.println(part);
  457.     if(counter == 0) {
  458.       counter++; // here is 'POST'
  459.     } else if (counter == 1) {
  460.       set_current = part.toInt();
  461.       counter++;
  462.     } else if (counter == 2) {
  463.       set_timer = part.toInt();
  464.       counter++;
  465.     }
  466.     startIndex = endIndex + 1;
  467.     endIndex = str.indexOf(delimiter, startIndex);
  468.   }
  469. }
  470.  
  471. float lookup_phyData_from_voltage(float voltage, int segment_points, const float* voltage_phyData_lookup) {
  472.     uint8_t index = 0;
  473.     const float *voltagePointer = &voltage_phyData_lookup[0];
  474.     const float *phyDataPointer = &voltage_phyData_lookup[segment_points];
  475.  
  476.     voltage = min(voltage, voltagePointer[segment_points - 1]);
  477.     voltage = max(voltage, voltagePointer[0]);
  478.  
  479.     while (voltagePointer[index] <= voltage && index < segment_points)
  480.         index++;
  481.  
  482.     if (index == 0) {
  483.         return map_f(voltage,
  484.             voltagePointer[0],
  485.             voltagePointer[1],
  486.             phyDataPointer[0],
  487.             phyDataPointer[1]);
  488.     } else if (index == segment_points) {
  489.         return map_f(voltage,
  490.             voltagePointer[segment_points - 2],
  491.             voltagePointer[segment_points - 1],
  492.             phyDataPointer[segment_points - 2],
  493.             phyDataPointer[segment_points - 1]);
  494.     } else {
  495.         return map_f(voltage,
  496.             voltagePointer[index - 1],
  497.             voltagePointer[index],
  498.             phyDataPointer[index - 1],
  499.             phyDataPointer[index]);
  500.     }
  501. }
  502.  
  503. float map_f(float x, float in_min, float in_max, float out_min, float out_max) {
  504.     return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
  505. }
  506.  
  507. static float voltage_average_temp1 = 0.0;
  508. static float voltage_average_temp2 = 0.0;
  509.  
  510. void readTemp1() {
  511.     sensor1.requestTemperatures(); // Send the command to get temperatures
  512.     temperature1 = sensor1.getTempCByIndex(0);
  513.     if (temperature1 == DEVICE_DISCONNECTED_C) {
  514.         temperature1 = -100;
  515.     }  
  516. }
  517.  
  518. void readTemp2() {
  519.     sensor2.requestTemperatures(); // Send the command to get temperatures
  520.     temperature2 = sensor2.getTempCByIndex(0);
  521.     if (temperature2 == DEVICE_DISCONNECTED_C) {
  522.         temperature2 = -100;
  523.     }  
  524. }
  525.  
  526. /* END CODE */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement