#include <WiFi.h> //Enables the ESP32 to connect to a Wi-Fi netwrok
#include <WiFiClient.h> //Handles the connection to a server over Wi-Fi
#include "ThingSpeak.h" //provides function to send and recive data to/from ThingSpeak
#define Low_LED_Pin 12 //name for GPIO pins conneted to the LED(red)
#define High_LED_Pin 14 //name for GPIO pins conneted to the LED(green)
#define PIN_TRIG 5 //GPIO pin used to send trigger signals to the ultrasonic sensor
#define PIN_ECHO 17 //GPIO pin used to read the echo signal from ultrasonic sensor
const char* WIFI_NAME = "Wokwi-GUEST"; //Wi-Fi credentials for connection
const char* WIFI_PASSWORD = ""; //Wi-Fi credentials for connection
const int myChannelNumber = 2786848 ; //ThingSpeak channel ID
const char* myApiKey = "KXEX3ZBUWR5B44O9"; //API key for authenticating to ThingSpeak
const char* server = "api.thingspeak.com"; //Specifies the ThingSpeak server URL
WiFiClient client; //cretes a client object for establishing the connection to the ThingSpeak server
void setup() {
// put your setup code here, to run once:
Serial.begin(115200); //Intializes serial communication for debugging
pinMode(Low_LED_Pin, OUTPUT); //Configures pin as OUTPUT or INPUT
pinMode(High_LED_Pin, OUTPUT); //Configures pin as OUTPUT or INPUT
pinMode(PIN_TRIG, OUTPUT); //Configures pin as OUTPUT or INPUT
pinMode(PIN_ECHO, INPUT); //Configures pin as OUTPUT or INPUT
WiFi.begin(WIFI_NAME, WIFI_PASSWORD); //Starts Wi-Fi connection with the specified credentials
ThingSpeak.begin(client); //Links the client object to the ThingSpeak Library for data operations
}
void loop() {
// put your main code here, to run repeatedly:
digitalWrite(PIN_TRIG, HIGH); //sends 10 microsecond pulse to the trigger pin, activating the ultrasonic sensor
delayMicroseconds(10);
digitalWrite(PIN_TRIG, LOW);
int duration = pulseIn(PIN_ECHO, HIGH); //Measures the duration of the echo pulse in microseconds
int distance = duration / 58; //Converts the duration into distance in cm
Serial.print("Distance in CM: "); //prints the calc distance to the monitor
Serial.println(distance);
ThingSpeak.setField(1,distance); //sets the first field in ypur ThingSpeak channel with the distance vlaue
ThingSpeak.writeFields(myChannelNumber,myApiKey); //.sends the data to the ThingSpeak channel
if (distance < 20) {
digitalWrite(High_LED_Pin, HIGH); //distance less than 20 light green LED
digitalWrite(Low_LED_Pin, LOW);
}
else if (distance >300){
digitalWrite(Low_LED_Pin, HIGH); //distance more than 300 light red LED
digitalWrite(High_LED_Pin, LOW);
}
else{
digitalWrite(High_LED_Pin, LOW); //if none no LED is lit
digitalWrite(Low_LED_Pin, LOW);
}
delay(1000); //wait for 1 swcond before repeating the loop
}