#include <ESP32Servo.h>
#include <WiFi.h>
#include <HTTPClient.h>
// Define pins
const int trigPin = 5;
const int echoPin = 18;
const int potPin = 34; // Analog pin for potentiometer
const int relayPin = 4; // Relay control pin
const int servoPin = 21; // Servo control pin
Servo myservo;
const char* ssid = "Wokwi-GUEST";
const char* password = "";
// ThingSpeak settings
const char* server = "https://api.thingspeak.com/update?api_key=K7EZA72HWEB5D0NC&field1=0";
const char* apiKey = "K7EZA72HWEB5D0NC"; // Replace with your ThingSpeak Write API Key
// Function to measure distance using the ultrasonic sensor
long readUltrasonicDistance(int triggerPin, int echoPin) {
digitalWrite(triggerPin, LOW);
delayMicroseconds(2);
digitalWrite(triggerPin, HIGH);
delayMicroseconds(10);
digitalWrite(triggerPin, LOW);
long duration = pulseIn(echoPin, HIGH);
long distance = duration * 0.034 / 2; // Convert to cm
return distance;
}
void setup() {
Serial.begin(115200);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(potPin, INPUT);
pinMode(relayPin, OUTPUT);
myservo.attach(servoPin);
// Initial state of relay and servo
digitalWrite(relayPin, LOW);
myservo.write(0); // Initial position of servo
// Connect to WiFi
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.print(".");
}
Serial.println();
Serial.println("WiFi connected");
}
void sendDataToThingSpeak(long distance, float voltage) {
if (WiFi.status() == WL_CONNECTED) {
HTTPClient http;
String url = String(server) + "?api_key=" + apiKey + "&field1=" + String(distance) + "&field2=" + String(voltage);
http.begin(url);
int httpResponseCode = http.GET();
if (httpResponseCode > 0) {
String response = http.getString();
Serial.println(httpResponseCode);
Serial.println(response);
} else {
Serial.print("Error on sending POST: ");
Serial.println(httpResponseCode);
}
http.end();
} else {
Serial.println("WiFi not connected");
}
}
void loop() {
// Read the distance from the ultrasonic sensor
long distance = readUltrasonicDistance(trigPin, echoPin);
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
// Read the pH level (simulated by potentiometer)
int potValue = analogRead(potPin);
float voltage = potValue * (3.3 / 4095.0); // Convert to voltage (3.3V reference)
Serial.print("pH Level (simulated by potentiometer voltage): ");
Serial.println(voltage);
// Control relay and servo based on distance
if (distance <= 170) {
digitalWrite(relayPin, HIGH); // Turn on the relay
myservo.write(90); // Move servo to 90 degrees (or any desired position)
} else {
digitalWrite(relayPin, LOW); // Turn off the relay
myservo.write(0); // Move servo to 0 degrees (or any desired position)
}
// Send data to ThingSpeak
sendDataToThingSpeak(distance, voltage);
delay(5000); // Wait for 5 seconds before the next loop
}