Advertisement
pleasedontcode

Sensor Control rev_38

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