#include <ArduinoJson.h>
#include <WiFi.h>
#include <HTTPClient.h>
#include <string.h>
struct Module{
const int relayPin;
const int echoPin;
const int trigPin;
};
Module modules[] = {
{16, 27, 12},
{17, 26, 14},
{18, 25, 33}
};
size_t n = sizeof(modules) / sizeof(modules[0]);
long* distances = new long[n];
const int maxHeight = 20;
long minHeight;
const char* ssid = "Wokwi-GUEST";
const char* password = "";
// Local server details
const char* serverURL = "http://192.168.1.6:3000"; // Replace with your backend server's IP and port
void calcDistances(long* dist){
minHeight = 20;
Serial.println("Distances: ");
for(int i = 0; i < n; i++){
digitalWrite(modules[i].trigPin, LOW);
delayMicroseconds(2);
digitalWrite(modules[i].trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(modules[i].trigPin, LOW);
long value = pulseIn(modules[i].echoPin, HIGH);
dist[i] = (value * 0.034) / 2;
minHeight = min(minHeight, dist[i]);
Serial.println(dist[i]);
}
Serial.print("Minimum: ");
Serial.println(minHeight);
}
void makeGetRequest() {
if (WiFi.status() == WL_CONNECTED) {
HTTPClient http;
String url = String(serverURL) + "/places";
http.begin(url);
int httpResponseCode = http.GET();
if (httpResponseCode > 0) {
String response = http.getString();
Serial.println("GET Response:");
Serial.println(response);
} else {
Serial.print("Error in GET request: ");
Serial.println(httpResponseCode);
}
http.end();
} else {
Serial.println("WiFi disconnected!");
}
}
void makePutRequest() {
if (WiFi.status() == WL_CONNECTED) {
HTTPClient http;
String url = String(serverURL) + "/user-tank-data";
http.begin(url);
http.addHeader("Content-Type", "application/json");
String jsonPayload = "{\"key\":\"value\"}";
int httpResponseCode = http.PUT(jsonPayload);
if (httpResponseCode > 0) {
String response = http.getString();
Serial.println("PUT Response:");
Serial.println(response);
} else {
Serial.print("Error in PUT request: ");
Serial.println(httpResponseCode);
}
http.end();
} else {
Serial.println("WiFi disconnected!");
}
}
void setup() {
Serial.begin(115200);
for(auto module : modules){
// Setting the Pin Modes of all the pins:
pinMode(module.relayPin, OUTPUT);
pinMode(module.trigPin, OUTPUT);
pinMode(module.echoPin, INPUT);
// Setting relay input pins to LOW:
digitalWrite(module.relayPin, LOW);
}
// To Connect to the Wifi:
WiFi.begin(ssid, password);
Serial.print("Connecting to Wi-Fi");
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.print(".");
}
Serial.println("\nConnected to Wi-Fi");
calcDistances(distances);
}
void loop() {
calcDistances(distances);
for(int i = 0; i < n; i++){
if((distances[i] <= minHeight || (distances[i] - 1) == minHeight) && minHeight < maxHeight){
digitalWrite(modules[i].relayPin, HIGH);
}
else digitalWrite(modules[i].relayPin, LOW);
}
// Make a GET request
makeGetRequest();
// Make a PUT request
makePutRequest();
delay(5000);
}
Loading
esp32-devkit-c-v4
esp32-devkit-c-v4