#include "WiFi.h"
const char* ssid = "Wokwi-GUEST";
const char* password = "";
const int redPin = 15;
const int yellowPin = 2;
const int greenPin = 4;
const int trigPin = 13;
const int echoPin = 12;
long duration;
int distance;
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
WiFi.begin(ssid, password);
Serial.println("Hello, ESP32!");
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.println("Connecting to WiFi..");
}
Serial.println("Connected to the WiFi network");
// Print local IP address and start web server
Serial.println("");
Serial.println("WiFi connected.");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
pinMode(echoPin, INPUT); // Sets the echoPin as an Input
pinMode (redPin, OUTPUT);
pinMode (yellowPin, OUTPUT);
pinMode (greenPin, OUTPUT);
}
void loop() {
// Clears the trigPin
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
// Sets the trigPin on HIGH state for 10 micro seconds
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Reads the echoPin, returns the sound wave travel time in microseconds
duration = pulseIn(echoPin, HIGH);
// Calculate the distance
distance = (duration*0.034/2)+1;
// Prints the distance in the Serial Monitor
Serial.print("Distance (cm): ");
Serial.println(distance);
if(distance<=50){
digitalWrite (greenPin, HIGH); // turn on the LED
Serial.println("Green light is on");
}
else {
digitalWrite (greenPin, LOW);
}
if(distance>50&&distance<=150){
digitalWrite (yellowPin, HIGH); // turn on the LED
Serial.println("Yellow light is on");
}
else{
digitalWrite (yellowPin, LOW);
}
if(distance>150){
digitalWrite (redPin, HIGH); // turn on the LED
Serial.println("Red light is on");
}
else {
digitalWrite (redPin, LOW);
}
delay(1000);
}