#define DATA_POINTS 10
float voltageArray[DATA_POINTS];
#define SAMPLE_INTERVAL 1000
int offset = 0;
// Define the analog input pin based on your ESP32 NodeMCU board
#define ANALOG_PIN 34 // Replace with the GPIO pin number corresponding to "VP"
#include <WiFi.h>
#include <HTTPClient.h>
#include <Ticker.h>
// Your Wi-Fi credentials
const char *ssid = "YourWiFiSSID";
const char *password = "YourWiFiPassword";
// Server details
const char *serverAddress = "http://YourServerAddress"; // Replace with your server address
const int serverPort = 80; // Replace with your server port
Ticker timer;
void voltMeter() {
int volt = analogRead(ANALOG_PIN); // read the input
Serial.print("Analog Input: ");
Serial.println(volt);
// Calculate the gradient
float gradient = calculateGradient();
Serial.print("Gradient: ");
Serial.println(gradient);
// Send the values to the server
sendToServer(volt, gradient);
}
float calculateGradient() {
// Use numerical differentiation to estimate the gradient
// Assuming a simple backward difference method
float voltageNow = analogRead(ANALOG_PIN) * (5.0 / 4095.0); // Current voltage reading for ESP32
float voltagePrevious = voltageArray[DATA_POINTS - 1]; // Previous voltage reading
// Shift the array to make room for the new value
for (int i = 0; i < DATA_POINTS - 1; i++) {
voltageArray[i] = voltageArray[i + 1];
}
// Store the current value in the array
voltageArray[DATA_POINTS - 1] = voltageNow;
// Calculate the gradient using backward difference
float gradient = (voltageNow - voltagePrevious) / (DATA_POINTS * SAMPLE_INTERVAL / 1000.0);
return gradient;
}
void sendToServer(int analogInput, float gradient) {
// Create an HTTP client object
HTTPClient http;
// Construct the server endpoint URL
String url = String(serverAddress) + ":" + String(serverPort) + "/updateData";
// Add parameters to the URL
url += "?analogInput=" + String(analogInput);
url += "&gradient=" + String(gradient);
// Start the HTTP request
http.begin(url);
// Send the request and check for errors
int httpCode = http.GET();
if (httpCode > 0) {
Serial.printf("HTTP request successful, response code: %d\n", httpCode);
} else {
Serial.printf("HTTP request failed, error: %s\n", http.errorToString(httpCode).c_str());
}
// End the HTTP request
http.end();
}
void setup() {
// Debug console
Serial.begin(115200);
// Connect to Wi-Fi
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting to WiFi...");
}
Serial.println("Connected to WiFi");
// Set up the timer for data reporting
timer.attach(SAMPLE_INTERVAL, voltMeter);
}
void loop() {
// No need for additional loop logic, as the Ticker handles the interval
}