Advertisement
pleasedontcode

GPS Monitoring rev_32

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