Advertisement
pleasedontcode

**Sensor Monitor** rev_33

Oct 21st, 2024
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Arduino 11.35 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 10:50:48
  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";        // at least 8 characters - 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 - threshold below 15 km/h turns off current supply
  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; // temperature probe 1
  62. const int ONE_WIRE_BUS_Temp2 = 21; // temperature probe 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. // ACS712 configuration
  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
  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}, // current [V]
  125.     {0.0, 5.0, 7.0, 13.0, 22.0, 29.0, 33.0, 37.0, 56.0, 65.0} // percentage [°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.  
  141.   delay(1000);
  142.  
  143.   Serial.println("ciao");
  144.  
  145.   pot.begin(DIGPOT_INC, DIGPOT_UD, DIGPOT_CS);  //  pulse, direction, select // INC = 4, UD = 5, CS = 15
  146.  
  147.   // NON TOGLIERE - SERVE PER NON FAR SBARELLARE LA MACCHINA
  148.   for(int i=0; i<10;i++)
  149.   {
  150.     setCurrentOutput(0);
  151.     delay(20);
  152.     setCurrentOutput(100);
  153.     delay(20);
  154.   }
  155.  
  156.   setCurrentOutput(PWM_output_percentage);
  157.   readMinutesCounterFromEEPROM();
  158.  
  159.   ss.begin(GPSBaud);
  160.   Serial.println("ciao2");
  161.  
  162.   sensor1.begin();
  163.   sensor2.begin();
  164.  
  165.   smartDelay(1000);
  166.  
  167.   ACS.setMidPoint(ADC_Offset);
  168.  
  169.   Serial.println(F("Access Point Web Server"));
  170.  
  171.   // Initialize SPIFFS
  172.   initSPIFFS();
  173.  
  174.   WiFi.mode(WIFI_AP); // Set the ESP32 to access point mode
  175.   if (!WiFi.softAP(ssid, pass)) {
  176.     Serial.println("Soft AP creation failed.");
  177.     while(1);
  178.   }
  179.  
  180.   // Print the IP address of the access point
  181.   IPAddress IP = WiFi.softAPIP();
  182.   Serial.print("Access Point IP Address: ");
  183.   Serial.println(IP);
  184.  
  185.   // Serve the JPEG image
  186.   server.on("/background.jpg", HTTP_GET, [](AsyncWebServerRequest *request){
  187.     Serial.println("0");
  188.     request->send(SPIFFS, "/background.jpg", "image/jpeg");
  189.   });
  190.  
  191.   // Serve the HTML page
  192.   server.on("/", HTTP_GET, [](AsyncWebServerRequest *request){
  193.     Serial.println("1");
  194.     request->send(SPIFFS, "/index.html", "text/html");
  195.   });
  196.  
  197.   server.on("/UPDATEDATA", HTTP_POST, [](AsyncWebServerRequest *request) {
  198.     // Log post request handling
  199.     //Serial.println("postUpdateData");
  200.  
  201.     // Allocate a temporary JsonDocument
  202.     StaticJsonDocument<512> doc;
  203.  
  204.     // Gather data and populate JSON
  205.     updateData(doc);
  206.  
  207.     // Convert the JSON document to string and send it in response
  208.     String response;
  209.     serializeJsonPretty(doc, response);
  210.  
  211.     request->send(200, "application/json", response);
  212.   });
  213.  
  214.   // Start the server
  215.   server.begin();
  216. }
  217.  
  218. void loop() {
  219.   // No logic in the loop; the server works asynchronously
  220.  
  221.   readGPSAndCheckSpeed();
  222.   readCurrent();
  223.   readVoltage();
  224.   readWaterTank();
  225.   readTemp1();
  226.   readTemp2();
  227.   updateMinutesCounter();
  228.   checkRegeneration();
  229. }
  230.  
  231. // The updateData function to generate the JSON payload
  232. void updateData(JsonDocument &doc) {
  233.   if (velocita > 0.0) {
  234.     doc["speed"] = String(velocita) + String(F(" km/h"));
  235.   } else {
  236.     doc["speed"] = String(F("ERROR"));
  237.   }
  238.   doc["voltageCommandOut"] = String(F("Tensione uscita comando: ")) + String(voltage_output_value) + String(F("/3.3 [V]"));
  239.   doc["percentageCommandOut"] = String(F("Uscita comando PWM: ")) + String(PWM_output_percentage) + String(F(" [%]"));
  240.  
  241.   doc["waterTankLevel"] = waterLevelEmpty ? String(F("VUOTO")) : String(F("PIENO"));
  242.   doc["powerOnTime"] = String(powerOnTime) + String(F(" min"));
  243.   doc["current"] = String(current) + String(F(" A"));
  244.   doc["voltage"] = String(voltage) + String(F(" V"));
  245.   doc["temperature1"] = String(temperature1) + String(F(" °C"));
  246.   doc["temperature2"] = String(temperature2) + String(F(" °C"));
  247.   doc["set_timer"] = String(F("Timer : ")) + String(set_timer) + String(F(" min"));
  248. }
  249.  
  250. void checkRegeneration() {
  251.   if(set_timer == 0)
  252.   {
  253.     startRegeneration = false;
  254.   }
  255. }
  256.  
  257. void readMinutesCounterFromEEPROM() {
  258.   // Read the counter value from EEPROM
  259.   unsigned long max_minutesCounter = 0UL - 1UL;
  260.  
  261.   EEPROM.begin(sizeof(powerOnTime));
  262.   EEPROM.get(0, powerOnTime);
  263.  
  264.   if(powerOnTime == max_minutesCounter) {
  265.     powerOnTime = 0;
  266.     Serial.println("Minutes Counter reinitialized");
  267.     saveMinutesCounterInEEPROM();
  268.   }
  269.  
  270.   Serial.print("powerOnTime: ");
  271.   Serial.println(powerOnTime);
  272. }
  273.  
  274. void updateMinutesCounter() {
  275.   currentMillis = millis();
  276.   if( (currentMillis - previousMillis) > 1000) {
  277.     previousMillis = currentMillis;
  278.     secondsCounter++;
  279.     if(secondsCounter % 60 == 0) {
  280.       secondsCounter = 0;
  281.       minutesCounter++;
  282.       powerOnTime++;
  283.       if(minutesCounter % 10 == 0) { // save counter in EEPROM every 10 minutes
  284.         saveMinutesCounterInEEPROM();
  285.       }
  286.       Serial.print("cumulatedMinutesCounter:");
  287.       Serial.println(powerOnTime);
  288.       if(set_timer > 0) {
  289.         set_timer--;
  290.       }
  291.     }
  292.   }    
  293. }
  294.  
  295. void saveMinutesCounterInEEPROM()  {
  296.   EEPROM.put(0, powerOnTime);
  297.   EEPROM.commit();
  298. }
  299.  
  300. void readGPSAndCheckSpeed() {
  301.   if(startRegeneration == false) {
  302.     while (ss.available() > 0) {
  303.       if (gps.encode(ss.read())) {
  304.         checkSpeed();
  305.       }
  306.     }
  307.  
  308.     if (millis() > 5000 && gps.charsProcessed() < 10)
  309.     {
  310.       velocita = -1.0;
  311.       PWM_output_percentage = PWM_output_percentage_0A;
  312.       setCurrentOutput(PWM_output_percentage);
  313.     }
  314.   } else {
  315.     PWM_output_percentage = lookup_phyData_from_voltage(set_current, SEGMENT_POINTS_voltage_Temperature, &(voltage_Temperature_lookup[0][0]));
  316.     setCurrentOutput(PWM_output_percentage);
  317.   }
  318. }
  319.  
  320. void setCurrentOutput(float PWM_outputPercentage) {
  321.   pot.setPosition(PWM_outputPercentage);   //  position
  322.   voltage_output_value = PWM_outputPercentage * 5.0 / 100.0;  
  323. }
  324.  
  325. void readCurrent() {
  326.   int mA = ACS.mA_DC(30); // 30 acquisitions for averaging
  327.   float tempCurrent = float(mA) / 1000;
  328.   current = current * 0.7 + tempCurrent * 0.3;
  329. }
  330.  
  331. void readVoltage() {
  332.   // Floats for ADC voltage & Input voltage
  333.   float adc_voltage = 0.0;
  334.  
  335.   // Floats for resistor values in divider (in ohms)
  336.   float R1 = 30000.0;
  337.   float R2 = 7500.0;
  338.  
  339.   // Float for Reference Voltage
  340.   float ref_voltage = 3.3;
  341.  
  342.   // Read the Analog Input
  343.   float adc_value = analogRead(voltage_pin);
  344.  
  345.   // Determine voltage at ADC input
  346.   adc_voltage  = (adc_value * ref_voltage) / 4096.0;
  347.  
  348.   // Calculate voltage at divider input
  349.   voltage = adc_voltage * (R1 + R2) / R2;
  350. }
  351.  
  352. void readWaterTank() {
  353.   waterLevelEmpty = digitalRead(water_level_pin);
  354. }
  355.  
  356. void checkSpeed() {
  357.     if (gps.location.isValid()) {
  358.         velocita = gps.speed.kmph();
  359.         if(millis() - SpeedShowTimer > TEMPO_ATTESA_VISUALIZZAZIONE_VELOCITA)
  360.         {
  361.           if(velocita > VELOCITA_SOGLIA_HIGH)
  362.           {
  363.             PWM_output_percentage = PWM_output_percentage_9A;
  364.             setCurrentOutput(PWM_output_percentage);
  365.           }
  366.           else if(velocita > VELOCITA_SOGLIA_0A_HIGH && velocita < VELOCITA_SOGLIA_LOW)
  367.           {
  368.             PWM_output_percentage = PWM_output_percentage_5A;
  369.             setCurrentOutput(PWM_output_percentage);
  370.           }
  371.           else if(velocita < VELOCITA_SOGLIA_0A_LOW)
  372.           {
  373.             PWM_output_percentage = PWM_output_percentage_0A;
  374.             setCurrentOutput(PWM_output_percentage);
  375.           }
  376.           SpeedShowTimer = millis();
  377.         }
  378.     }
  379.     else
  380.     {
  381.       Serial.println(F("NO GPS FIX!"));
  382.       velocita = -1.0;
  383.       PWM_output_percentage = PWM_output_percentage_0A;
  384.       setCurrentOutput(PWM_output_percentage);
  385.     }
  386. }
  387.  
  388. void readTemp1() {
  389.     sensor1.requestTemperatures(); // Send the command to get temperatures
  390.     temperature1 = sensor1.getTempCByIndex(0);
  391.     if(temperature1 == DEVICE_DISCONNECTED_C) {
  392.       temperature1 = -100;
  393.     }  
  394. }
  395.  
  396. void readTemp2() {
  397.     sensor2.requestTemperatures(); // Send the command to get temperatures
  398.     temperature2 = sensor2.getTempCByIndex(0);
  399.     if(temperature2 == DEVICE_DISCONNECTED_C) {
  400.       temperature2 = -100;
  401.     }  
  402. }
  403.  
  404. /* END CODE */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement