#include <ESP32Servo.h>
#include <WiFi.h>
#include <HTTPClient.h>
Servo myServo; // Create a Servo object
const int trigPin = 12; // GPIO for the Trigger pin of HC-SR04
const int echoPin = 14; // GPIO for the Echo pin of HC-SR04
const char* ssid = "kishore"; // Replace with your WiFi SSID
const char* password = "kishore2006"; // Replace with your WiFi password
unsigned long myChannelNumber = 2628364;
const String thingSpeakServer = "http://api.thingspeak.com/update";
const String apiKey = "ZTCKD4XWEUTVLGCW"; // Replace with your ThingSpeak API key
void setup() {
Serial.begin(115200);
myServo.setPeriodHertz(50); // Standard 50Hz servo
myServo.attach(13); // Attach the servo to GPIO 13
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
// Connect to WiFi
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("Connected to WiFi");
}
void loop() {
// Send pulse
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Measure pulse duration
long duration = pulseIn(echoPin, HIGH);
// Convert duration to distance in cm
float distance = (duration / 2.0) * 0.0344;
if (distance <= 10) {
myServo.write(90); // Move servo to 90 degrees if distance <= 10 cm
} else {
myServo.write(0); // Move servo to 0 degrees otherwise
}
// Send data to ThingSpeak
if (WiFi.status() == WL_CONNECTED) {
HTTPClient http;
String url = thingSpeakServer + "?api_key=" + apiKey + "&field1=" + String(distance);
http.begin(url);
int httpCode = http.GET();
if (httpCode > 0) {
String payload = http.getString();
Serial.println("ThingSpeak response: " + payload);
} else {
Serial.println("Error in HTTP request");
}
http.end();
}
delay(5000); // Wait 5 seconds before the next measurement
}