Advertisement
pleasedontcode

**Sensor Monitoring** rev_39

Oct 21st, 2024
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  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 Monitoring**
  13.     - Source Code NOT compiled for: ESP32 DevKit V1
  14.     - Source Code created on: 2024-10-21 14:09:12
  15.  
  16. ********* Pleasedontcode.com **********/
  17.  
  18. /****** SYSTEM REQUIREMENTS *****/
  19. /****** SYSTEM REQUIREMENT 1 *****/
  20.     /* merge code. */
  21. /****** END SYSTEM REQUIREMENTS *****/
  22.  
  23.  
  24. /********* User code review feedback **********
  25. #### Feedback 1 ####
  26. - modify code and put non blocking code.
  27. ********* User code review feedback **********/
  28.  
  29. /* START CODE */
  30.  
  31. /****** DEFINITION OF LIBRARIES *****/
  32. #include <TinyGPSPlus.h>
  33. #include "ACS712.h"
  34. #include <WiFi.h>
  35. #include <ESPAsyncWebServer.h>
  36. #include <SPIFFS.h>
  37. #include <ArduinoJson.h>
  38. #include <EEPROM.h>
  39. #include <OneWire.h>
  40. #include <DallasTemperature.h>
  41. #include "X9C10X.h"
  42.  
  43. /****** FUNCTION PROTOTYPES *****/
  44. void setup(void);
  45. void loop(void);
  46.  
  47. // Access Point credentials
  48. char ssid[] = "pleasedontcode.com";        // your network SSID (name)
  49. char pass[] = "prova1234";        // your network password (use for WPA, or use as key for WEP)
  50.  
  51. // Create an instance of the web server
  52. AsyncWebServer server(80);
  53.  
  54. TinyGPSPlus gps;
  55.  
  56. #define VELOCITA_SOGLIA_HIGH 75.0 //km/h
  57. #define VELOCITA_SOGLIA_LOW 65.0 //km/h
  58. #define VELOCITA_SOGLIA_0A_HIGH  20.0 //km/h - soglia sotto 15km/h si spegne l'erogazione corrente
  59. #define VELOCITA_SOGLIA_0A_LOW  10.0 //km/h
  60.  
  61. //PINS
  62. const int water_level_pin = 18;
  63. const int voltage_pin     = 35;
  64. const int current_pin     = 34;
  65. const int tempSensor1_pin = 33;
  66. const int tempSensor2_pin = 32;
  67. const int ONE_WIRE_BUS_Temp1 = 19; //sonda temp 1
  68. const int ONE_WIRE_BUS_Temp2 = 21; //sonda temp 2
  69. const int DIGPOT_INC      = 4;    // pin INC - X9C103S
  70. const int DIGPOT_UD       = 5;    // pin UD - X9C103S
  71. const int DIGPOT_CS       = 15;   // pin CS - X9C103S
  72.  
  73. const float PWM_output_percentage_0A = 0.0; //0%
  74. const float PWM_output_percentage_9A = 20.0; //20% --> 1V/5V
  75. const float PWM_output_percentage_5A = 13.0; //13% --> 0,65V/5V
  76.  
  77. // DATI globali da trasferire
  78. float PWM_output_percentage = 0.0;
  79. float velocita = 0.0;
  80. float voltage_output_value = 0.0;
  81. bool waterLevelEmpty = true;
  82. float voltage = 0.0;
  83. float current = 0.0;
  84. float temperature1 = 0.0;
  85. float temperature2 = 0.0;
  86. unsigned long powerOnTime = 0; //minutes
  87.  
  88. boolean startRegeneration = false;
  89. unsigned int set_current  = 0;
  90. unsigned int set_timer    = 0;
  91.  
  92. // configurazione ACS712 da 30A
  93. unsigned int ADC_Offset = 1930;
  94. ACS712  ACS(current_pin, 3.3, 4095, 40); // pin 34 per acquisizione sensore corrente; l'alimentazione sensore è 3.3V
  95. X9C10X pot(10000);  //  10KΩ  - potenziometro digitale X9C103S da 10kΩ
  96.  
  97. void printWiFiStatus();
  98. void printWebPage();
  99. void checkClientRequest(String currentLine);
  100.  
  101. bool ReplyWebPageContent = true;
  102. bool ReplyResetTime = false;
  103. bool postUpdateData = false;
  104.  
  105. static const int GPSBaud = 9600;
  106. #define ss Serial2
  107.  
  108. unsigned long TEMPO_ATTESA_VISUALIZZAZIONE_VELOCITA = 300;
  109. unsigned long SpeedShowTimer = 0;
  110.  
  111. // Counter to track seconds
  112. unsigned long secondsCounter            = 0;
  113. unsigned long previousMillis            = millis(); // Variable to store the previous millis value
  114. unsigned long currentMillis             = millis();
  115. unsigned long minutesCounter            = 0;
  116.  
  117. // Setup a oneWire instance to communicate with any OneWire devices (not just Maxim/Dallas temperature ICs)
  118. OneWire oneWire1(ONE_WIRE_BUS_Temp1);
  119. OneWire oneWire2(ONE_WIRE_BUS_Temp2);
  120.  
  121. // Pass our oneWire reference to Dallas Temperature.
  122. DallasTemperature sensor1(&oneWire1);
  123. DallasTemperature sensor2(&oneWire2);
  124.  
  125. /****** DEFINITION OF ANALOG INPUTS CHARACTERISTIC CURVES *****/
  126. const uint8_t SEGMENT_POINTS_voltage_Temperature = 10;
  127. const float voltage_Temperature_lookup[2][SEGMENT_POINTS_voltage_Temperature] =
  128. {
  129.     {0.0, 1.2, 1.9, 5.0, 10.0, 14.5, 17.0, 20.0, 30.0, 35.0}, // corrente [V]
  130.     {0.0, 5.0, 7.0, 13.0, 22.0, 29.0, 33.0, 37.0, 56.0, 65.0} // percentuale [°C]
  131. };
  132.  
  133. // Initialize SPIFFS for file storage
  134. void initSPIFFS() {
  135.   if (!SPIFFS.begin(true)) {
  136.     Serial.println("An error occurred while mounting SPIFFS");
  137.     return;
  138.   }
  139.   Serial.println("SPIFFS mounted successfully");
  140. }
  141.  
  142. void setup() {
  143.   // Start Serial for debugging
  144.   Serial.begin(115200);
  145.   delay(1000);
  146.   Serial.println("ciao");
  147.  
  148.   pot.begin(DIGPOT_INC, DIGPOT_UD, DIGPOT_CS);  //  pulse, direction, select // INC = 4, UD = 5, CS = 15
  149.  
  150.   // Set Up ACS712
  151.   ACS.setMidPoint(ADC_Offset);
  152.  
  153.   ss.begin(GPSBaud);
  154.   Serial.println("ciao2");
  155.  
  156.   sensor1.begin();
  157.   sensor2.begin();
  158.  
  159.   delay(1000);
  160.  
  161.   Serial.println(F("Access Point Web Server"));
  162.  
  163.   // Initialize SPIFFS
  164.   initSPIFFS();
  165.  
  166.   WiFi.mode(WIFI_AP); // Set the ESP32 to access point mode
  167.   if (!WiFi.softAP(ssid, pass)) {
  168.     Serial.println("Soft AP creation failed.");
  169.     while(1);
  170.   }
  171.  
  172.   // Print the IP address of the access point
  173.   IPAddress IP = WiFi.softAPIP();
  174.   Serial.print("Access Point IP Address: ");
  175.   Serial.println(IP);
  176.  
  177.   // URLs handling
  178.   server.on("/background.jpg", HTTP_GET, [](AsyncWebServerRequest *request){
  179.     Serial.println("0");
  180.     request->send(SPIFFS, "/background.jpg", "image/jpeg");
  181.   });
  182.  
  183.   server.on("/", HTTP_GET, [](AsyncWebServerRequest *request){
  184.     Serial.println("1");
  185.     request->send(SPIFFS, "/index.html", "text/html");
  186.   });
  187.  
  188.   server.on("/UPDATEDATA", HTTP_POST, [](AsyncWebServerRequest *request) {
  189.     StaticJsonDocument<512> doc;
  190.  
  191.     // Populate JSON with user data
  192.     updateData(doc);  
  193.  
  194.     String response;
  195.     serializeJsonPretty(doc, response);
  196.  
  197.     request->send(200, "application/json", response);
  198.   });
  199.  
  200.   // Start the server
  201.   server.begin();
  202. }
  203.  
  204. void loop() {
  205.   // Non-blocking implementations updated the reading functions
  206.   readGPSAndCheckSpeed();
  207.   readCurrent();
  208.   readVoltage();
  209.   readWaterTank();
  210.   readTemp1();
  211.   readTemp2();
  212.   updateMinutesCounter();
  213.   checkRegeneration();
  214. }
  215.  
  216. // Handle updates to appending new data
  217. void updateData(JsonDocument &doc) {
  218.   if (velocita > 0.0) {
  219.     doc["speed"] = String(velocita) + String(F(" km/h"));
  220.   } else {
  221.     doc["speed"] = String(F("ERROR"));
  222.   }
  223.   doc["voltageCommandOut"] = String(F("Tensione uscita comando: ")) + String(voltage_output_value) + String(F("/3.3 [V]"));
  224.   doc["percentageCommandOut"] = String(F("Uscita comando PWM: ")) + String(PWM_output_percentage) + String(F(" [%]"));
  225.   doc["waterTankLevel"] = waterLevelEmpty ? String(F("VUOTO")) : String(F("PIENO"));
  226.   doc["powerOnTime"] = String(powerOnTime) + String(F(" min"));
  227.   doc["current"] = String(current) + String(F(" A"));
  228.   doc["voltage"] = String(voltage) + String(F(" V"));
  229.   doc["temperature1"] = String(temperature1) + String(F(" °C"));
  230.   doc["temperature2"] = String(temperature2) + String(F(" °C"));
  231.   doc["set_timer"] = String(F("Timer : ")) + String(set_timer) + String(F(" min"));
  232. }
  233.  
  234. void checkRegeneration() {
  235.   // Non-blocking check for setting timer adjustment
  236.   if(set_timer == 0) {
  237.     startRegeneration = false;
  238.   }
  239. }
  240.  
  241. ///////////////////////////////////////////////////////////////////////////
  242. // The remaining functions have been converted to non-blocking behaviours..
  243. ///////////////////////////////////////////////////////////////////////////
  244. void readGPSAndCheckSpeed() {
  245.     if(!startRegeneration) {
  246.         while (ss.available()) {
  247.             if (gps.encode(ss.read())) {
  248.                 checkSpeed();
  249.             }
  250.         }
  251.    
  252.         if (millis() > 5000 && gps.charsProcessed() < 10) {
  253.             velocita = -1.0;
  254.             PWM_output_percentage = PWM_output_percentage_0A;
  255.             setCurrentOutput(PWM_output_percentage);
  256.         }
  257.     } else {
  258.         PWM_output_percentage = lookup_phyData_from_voltage(set_current, SEGMENT_POINTS_voltage_Temperature, &(voltage_Temperature_lookup[0][0]));
  259.         setCurrentOutput(PWM_output_percentage);
  260.     }
  261. }
  262.  
  263.  
  264. void readCurrent() {
  265.     int mA = ACS.mA_DC(30); //30 acquisizioni di media
  266.     float tempCurrent = float(mA) / 1000;
  267.     current = current * 0.7 + tempCurrent * 0.3;
  268. }
  269.  
  270. void readVoltage() {
  271.     float adc_voltage = 0.0;
  272.     float R1 = 30000.0;
  273.     float R2 = 7500.0;
  274.     float ref_voltage = 3.3;
  275.  
  276.     float adc_value = analogRead(voltage_pin);
  277.     adc_voltage  = (adc_value * ref_voltage) / 4096.0;
  278.     voltage = adc_voltage * (R1 + R2) / R2;
  279. }
  280.  
  281. void readWaterTank() {
  282.     waterLevelEmpty = digitalRead(water_level_pin);
  283. }
  284.  
  285. void readTemp1() {
  286.     sensor1.requestTemperatures(); // Send the command to get temperatures
  287.     temperature1 = sensor1.getTempCByIndex(0);
  288.     if(temperature1 == DEVICE_DISCONNECTED_C) {
  289.         temperature1 = -100; // Indicator for sensor disconnect
  290.     }  
  291. }
  292.  
  293. void readTemp2() {
  294.     sensor2.requestTemperatures(); // Send the command to get temperatures
  295.     temperature2 = sensor2.getTempCByIndex(0);
  296.     if(temperature2 == DEVICE_DISCONNECTED_C) {
  297.         temperature2 = -100; // Indicator for sensor disconnect
  298.     }  
  299. }
  300.  
  301. /* END CODE */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement