#include <WiFi.h>
#include <HTTPClient.h>
#define TRIG_PIN 5
#define ECHO_PIN 18
#define LED_PIN 23
// Replace with your WiFi credentials
const char* ssid ="Wokwi-GUEST";
const char* password = "";
// ThingSpeak details
const char* server = "http://api.thingspeak.com/update";
const char* apiKey = "mwa0000038550648";
const char* channelID = "3057597"; // Store channel ID separately (string)
// Optional: print channel ID at startup
void printChannelInfo() {
Serial.print("ThingSpeak Channel ID:3057597 ");
Serial.println(channelID);
Serial.print("ThingSpeak Write API Key:mwa0000038550648 ");
Serial.println(apiKey);
}
void setup() {
Serial.begin(115200);
pinMode(TRIG_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
pinMode(LED_PIN, OUTPUT);
digitalWrite(LED_PIN, LOW);
// Connect to WiFi
WiFi.begin(ssid, password);
Serial.print("Connecting to WiFi");
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("\nConnected to WiFi");
printChannelInfo();
}
void loop() {
// Trigger ultrasonic sensor
digitalWrite(TRIG_PIN, LOW);
delayMicroseconds(2);
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
// Read echo duration
long duration = pulseIn(ECHO_PIN, HIGH);
// Calculate distance in cm
float distance = duration * 0.034 / 2;
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
int occupancy = 0;
// Determine occupancy
int ledState = 0;
if (distance > 0 && distance < 400) {
occupancy = 1; // Occupied
digitalWrite(LED_PIN, HIGH);
} else {
occupancy = 0; // Free
digitalWrite(LED_PIN, LOW);
}
if (WiFi.status() == WL_CONNECTED) {
HTTPClient http;
// Build URL with occupancy data (channel ID NOT included in URL)
String url = String(server) + "?api_key=" + apiKey + "&field1=" + occupancy + "&field2=" + ledState;
http.begin(url);
int httpResponseCode = http.GET();
if (httpResponseCode > 0) {
String response = http.getString();
Serial.print("ThingSpeak response: ");
Serial.println(response);
} else {
Serial.print("Error sending to ThingSpeak. HTTP code: ");
Serial.println(httpResponseCode);
}
http.end();
} else {
Serial.println("WiFi Disconnected");
}
delay(15000); // Wait 15 seconds per ThingSpeak API limits
}Loading
esp32-devkit-c-v4
esp32-devkit-c-v4