Components Needed
• Arduino Uno
• 3 LEDs (Red, Yellow, Green)
• 3 Resistors (220 ohms)
• Buzzer
• Ultrasonic Sensor (HC-SR04)
• Breadboard and jumper wires
Circuit Diagram
1. Green LED:
◦ Anode (long leg) to Arduino pin 7 through a 220-ohm resistor.
◦ Cathode (short leg) to GND.
2. Yellow LED:
◦ Anode (long leg) to Arduino pin 6 through a 220-ohm resistor.
◦ Cathode (short leg) to GND.
3. Red LED:
◦ Anode (long leg) to Arduino pin 5 through a 220-ohm resistor.
◦ Cathode (short leg) to GND.
4. Buzzer:
◦ Positive lead to Arduino pin 8.
◦ Negative lead to GND.
5. Ultrasonic Sensor (HC-SR04):
◦ VCC to 5V on the Arduino.
◦ GND to GND on the Arduino.
◦ Trig to Arduino pin 9.
◦ Echo to Arduino pin 10.
CODE: Define pins for LEDs, Buzzer, and Ultrasonic Sensor
const int redLED = 5;
const int yellowLED = 6;
const int greenLED = 7;
const int buzzer = 8;
const int trigPin = 9;
const int echoPin = 10;
// Timing constants in milliseconds
const int buzzerTime = 1000; // 1 second
void setup() {
// Initialize the LED pins as outputs
pinMode(redLED, OUTPUT);
pinMode(yellowLED, OUTPUT);
pinMode(greenLED, OUTPUT);
pinMode(buzzer, OUTPUT);
// Initialize the ultrasonic sensor pins
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
// Start with the green light
digitalWrite(greenLED, HIGH);
digitalWrite(yellowLED, LOW);
digitalWrite(redLED, LOW);
digitalWrite(buzzer, LOW);
// Initialize Serial Monitor for debugging
Serial.begin(9600);
}
void loop() {
long duration, distance;
// Send a 10us pulse to trigger the ultrasonic sensor
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Read the echo pin
duration = pulseIn(echoPin, HIGH);
// Calculate the distance
distance = duration * 0.034 / 2;
// Print the distance for debugging
Serial.print("Distance: ");
Serial.println(distance);
// Control the LEDs and buzzer based on the distance
if (distance > 30) {
// Green light phase
digitalWrite(greenLED, HIGH);
digitalWrite(yellowLED, LOW);
digitalWrite(redLED, LOW);
digitalWrite(buzzer, LOW);
} else if (distance > 10 && distance <= 30) {
// Yellow light phase
digitalWrite(greenLED, LOW);
digitalWrite(yellowLED, HIGH);
digitalWrite(redLED, LOW);
digitalWrite(buzzer, LOW);
} else if (distance <= 10) {
// Red light phase with buzzer
digitalWrite(greenLED, LOW);
digitalWrite(yellowLED, LOW);
digitalWrite(redLED, HIGH);
digitalWrite(buzzer, HIGH);
delay(buzzerTime);
digitalWrite(buzzer, LOW);
}
delay(100); // Small delay to avoid excessive readings
}
Requirements
ESP32 board
LED
Resistor (220 ohms)
Breadboard and jumper wires
Arduino IDE
Circuit Diagram
LED Anode (long leg): Connect to GPIO 23 (pin G23) on the ESP32.
LED Cathode (short leg): Connect to one end of a 220-ohm resistor.
Other end of the resistor: Connect to GND on the ESP32.
Code
First, make sure you have the necessary libraries. You can install the WiFi library for the ESP32 from the Arduino Library Manager.
Here's the code to create a web server and control an LED:
cpp
Copy code
#include <WiFi.h>
// Replace with your network credentials
const char ssid = "YOUR_SSID";
const char password = "YOURPASSWORD";
// Set web server port number to 80
WiFiServer server(80);
// Variable to store the HTTP request
String header;
// LED GPIO pin
const int ledPin = 23;
bool ledState = false;
void setup() {
// Initialize the LED pin as an output
pinMode(ledPin, OUTPUT);
digitalWrite(ledPin, LOW);
// Start Serial communication for debugging purposes
Serial.begin(115200);
// Connect to Wi-Fi network
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WLCONNECTED) {
delay(1000);
Serial.print(".");
}
// Print the local IP address
Serial.println("");
Serial.println("WiFi connected.");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
// Start the server
server.begin();
}
void loop() {
WiFiClient client = server.available(); // Listen for incoming clients
if (client) { // If a new client connects,
Serial.println("New Client."); // print a message out in the serial port
String currentLine = ""; // make a String to hold incoming data from the client
while (client.connected()) { // loop while the client's connected
if (client.available()) { // if there's bytes to read from the client,
char c = client.read(); // read a byte, then
Serial.write(c); // print it out the serial monitor
header += c;
if (c == '\n') { // if the byte is a newline character
// if the current line is blank, you got two newline characters in a row.
// that's the end of the client HTTP request, so send a response:
if (currentLine.length() == 0) {
// HTTP headers always start with a response code (e.g. HTTP/1.1 200 OK)
// and a content-type so the client knows what's coming, then a blank line:
client.println("HTTP/1.1 200 OK");
client.println("Content-type:text/html");
client.println("Connection: close");
client.println();
// Display the HTML web page
client.println("!DOCTYPE html<html>");
client.println("<head><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">");
client.println("<link rel=\"icon\" href=\"data:,\">");
// CSS to style the on/off buttons
client.println("<style>html { font-family: Helvetica; display: inline-block; margin: 0px auto; text-align: center;}");
client.println(".button { background-color: #4CAF50; border: none; color: white; padding: 16px 40px;");
client.println("text-decoration: none; font-size: 30px; margin: 2px; cursor: pointer;}");
client.println(".button2 {background-color: #555555;}</style></head>");
// Web Page Heading
client.println("<body><h1>ESP32 Web Server</h1>");
// Display current state, and ON/OFF buttons for LED
if (ledState) {
client.println("<p>LED is ON</p>");
client.println("<p><a href=\"/ledOff\"><button class=\"button button2\">OFF</button></a></p>");
} else {
client.println("<p>LED is OFF</p>");
client.println("<p><a href=\"/ledOn\"><button class=\"button\">ON</button></a></p>");
}
client.println("</body></html>");
// The HTTP response ends with another blank line
client.println();
// Break out of the while loop
break;
} else { // if you got a newline, then clear currentLine
currentLine = "";
}
} else if (c != '\r') { // if you got anything else but a carriage return character,
currentLine += c; // add it to the end of the currentLine
}
// Check to see if the client request was "GET /ledOn" or "GET /ledOff":
if (currentLine.endsWith("GET /ledOn")) {
ledState = true;
digitalWrite(ledPin, HIGH);
}
if (currentLine.endsWith("GET /ledOff")) {
ledState = false;
digitalWrite(ledPin, LOW);
}
}
}
// Clear the header variable
header = "";
// Close the connection
client.stop();
Serial.println("Client disconnected.");
Serial.println("");
}
}
Explanation
WiFi Setup:
The ssid and password variables store your WiFi credentials.
The WiFi.begin(ssid, password) function connects to your WiFi network.
The while (WiFi.status() != WL_CONNECTED) loop waits until the ESP32 connects to the WiFi.
Web Server Setup:
WiFiServer server(80) creates a web server on port 80.
server.begin() starts the server.
Handling Client Requests:
WiFiClient client = server.available() waits for a client to connect.
The server reads the HTTP request and checks if the client requested to turn the LED on or off.
Based on the request, it changes the state of the LED using digitalWrite(ledPin, HIGH) or digitalWrite(ledPin, LOW).
Generating HTML Response:
The HTML response is generated and sent back to the client. The HTML contains buttons to turn the LED on and off.
Loop:
The loop() function continuously listens for incoming client connections and handles their requests.
Uploading the Code
Connect your ESP32 board to your computer via USB.
Select the correct board and port in the Arduino IDE:
Go to Tools -> Board, and select your ESP32 model (e.g., "ESP32 Dev Module").
Go to Tools -> Port, and select the appropriate COM port for your ESP32.
Click the Upload button in the Arduino IDE to upload the code to your ESP32.
Using the Web Server
Open the Serial Monitor in the Arduino IDE to see the IP address assigned to your ESP32.
Open a web browser and enter the IP address in the address bar (e.g., 192.168.1.100).
You should see a web page with buttons to turn the LED on and off.
This setup allows you to control the LED connected to your ESP32 from any device on the same WiFi network using a web browser.
#include <WiFi.h>
#include <WebServer.h>
// Replace with your network credentials
const char ssid = "your_SSID";
const char password = "yourPASSWORD";
// Create an instance of the web server on port 80
WebServer server(80);
// Define the pin connected to the buzzer
const int buzzerPin = 25;
// Define a melody and its duration
const int melody[] = {262, 294, 330, 349, 392, 440, 494, 523};
const int noteDurations[] = {4, 4, 4, 4, 4, 4, 4, 4};
// HTML content to be served
String getIndexHtml() {
return R"rawliteral(
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>ESP32 Web Server</title>
<style>
body { font-family: Arial, sans-serif; text-align: center; }
h1 { color: #333; }
button { padding: 10px 20px; font-size: 16px; }
</style>
</head>
<body>
<h1>ESP32 Web Server</h1>
<button onclick="playMelody()">Play Melody</button>
<p id="status"></p>
<script>
function playMelody() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("status").innerHTML = this.responseText;
}
};
xhttp.open("GET", "play", true);
xhttp.send();
}
</script>
</body>
</html>
)rawliteral";
}
// Function to play the melody on the buzzer
void playMelody() {
for (int thisNote = 0; thisNote < 8; thisNote++) {
int noteDuration = 1000 / noteDurations[thisNote];
tone(buzzerPin, melody[thisNote], noteDuration);
int pauseBetweenNotes = noteDuration * 1.30;
delay(pauseBetweenNotes);
noTone(buzzerPin);
}
}
// Handle the root URL
void handleRoot() {
server.send(200, "text/html", getIndexHtml());
}
// Handle the play melody request
void handlePlay() {
playMelody();
server.send(200, "text/plain", "Playing melody...");
}
void setup() {
// Start the serial communication
Serial.begin(115200);
// Set the buzzer pin as output
pinMode(buzzerPin, OUTPUT);
// Connect to Wi-Fi
WiFi.begin(ssid, password);
while (WiFi.status() != WLCONNECTED) {
delay(1000);
Serial.println("Connecting to WiFi...");
}
Serial.println("Connected to WiFi");
// Print the IP address
Serial.println(WiFi.localIP());
// Define routes
server.on("/", handleRoot);
server.on("/play", handlePlay);
// Start the server
server.begin();
Serial.println("Server started");
}
void loop() {
// Handle client requests
server.handleClient();
}
#define BUZZERPIN 23 // G23 Pin
#define BUZZERGROUND 2 // G2 Pin
int melody[] = {
NOTEC4, NOTED4, NOTEE4, NOTEF4, NOTEG4, NOTEA4, NOTEB4, NOTEC5
};
// note durations: 4 = quarter note, 8 = eighth note, etc.:
int noteDurations[] = {
4, 4, 4, 4, 4, 4, 4, 4
};
void setup() {
pinMode(BUZZERPIN, OUTPUT);
pinMode(BUZZERGROUND, OUTPUT);
digitalWrite(BUZZERGROUND, LOW); // Connect G2 to ground
// iterate over the notes of the melody:
for (int thisNote = 0; thisNote < 8; thisNote++) {
// to calculate the note duration, take one second divided by the note type.
// e.g., quarter note = 1000 / 4, eighth note = 1000 / 8, etc.
int noteDuration = 1000 / noteDurations[thisNote];
tone(BUZZERPIN, melody[thisNote], noteDuration);
// to distinguish the notes, set a minimum time between them.
// the note's duration + 30% seems to work well:
int pauseBetweenNotes = noteDuration * 1.30;
delay(pauseBetweenNotes);
// stop the tone playing:
noTone(BUZZER_PIN);
}
}
void loop() {
// no need to repeat the melody.
}
#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>
const char ssid = "YourSSID";
const char password = "YourPassword";
const int trigPin = D1;
const int echoPin = D2;
const int buzzerPin = D3;
ESP8266WebServer server(80);
void setup() {
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(buzzerPin, OUTPUT);
Serial.begin(115200);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting to WiFi...");
}
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
server.on("/", handleRoot);
server.on("/activate", handleActivate);
server.begin();
Serial.println("HTTP server started");
}
void loop() {
server.handleClient();
long duration, distance;
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = (duration / 2) / 29.1; // Calculate distance in cm
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
if (distance < 10) {
tone(buzzerPin, 1000); // Activate buzzer if object is too close
} else {
noTone(buzzerPin);
}
delay(500);
}
void handleRoot() {
long duration, distance;
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = (duration / 2) / 29.1; // Calculate distance in cm
String html = "<html><body>";
html += "<h1>Distance: ";
html += distance;
html += " cm</h1>";
html += "<form action='/activate' method='get'><input type='submit' value='Activate Buzzer'></form>";
html += "</body></html>";
server.send(200, "text/html", html);
}
void handleActivate() {
server.send(200, "text/plain", "Buzzer activated!");
tone(buzzerPin, 1000); // Activate the buzzer
delay(1000); // Buzz for 1 second
noTone(buzzerPin); // Turn off the buzzer
}
#include <ESP8266WiFi.h>
// Replace with your network credentials
const char ssid = "Airtel_PRAKASH";
const char password = "9941113669";
// Set web server port number to 80
WiFiServer server(80);
// Variable to store the HTTP request
String header;
// Current state of the buzzer
String buzzerState = "off";
// Assign GPIO pin for the buzzer
const int buzzerPin = D2;
void setup() {
Serial.begin(115200);
pinMode(buzzerPin, OUTPUT);
digitalWrite(buzzerPin, LOW);
// Connect to Wi-Fi network
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.print(".");
}
// Print local IP address and start web server
Serial.println("");
Serial.println("WiFi connected.");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
server.begin();
}
void loop() {
WiFiClient client = server.available(); // Listen for incoming clients
if (client) { // If a new client connects,
Serial.println("New Client."); // print a message out in the serial port
String currentLine = ""; // make a String to hold incoming data from the client
while (client.connected()) { // loop while the client's connected
if (client.available()) { // if there's bytes to read from the client,
char c = client.read(); // read a byte, then
Serial.write(c); // print it out the serial monitor
header += c;
if (c == '\n') { // if the byte is a newline character
if (currentLine.length() == 0) {
// HTTP headers always start with a response code (e.g. HTTP/1.1 200 OK)
// and a content-type so the client knows what's coming, then a blank line:
client.println("HTTP/1.1 200 OK");
client.println("Content-type:text/html");
client.println("Connection: close");
client.println();
// Display the HTML web page
client.println("!DOCTYPE html<html>");
client.println("<head><title>ESP8266 Buzzer Control</title></head>");
client.println("<body><h1>ESP8266 Buzzer Control</h1>");
client.println("<p>Buzzer State: " + buzzerState + "</p>");
client.println("<p><a href=\"/H\"><button>ON</button></a></p>");
client.println("<p><a href=\"/L\"><button>OFF</button></a></p>");
client.println("</body></html>");
// The HTTP response ends with another blank line
client.println();
break;
} else { // if you got a newline, then clear currentLine
currentLine = "";
}
} else if (c != '\r') { // if you got anything else but a carriage return character,
currentLine += c; // add it to the end of the currentLine
}
// Check if the client is requesting the buzzer to be turned on or off
if (header.indexOf("GET /H") >= 0) {
Serial.println("Buzzer ON");
buzzerState = "on";
digitalWrite(buzzerPin, HIGH);
} else if (header.indexOf("GET /L") >= 0) {
Serial.println("Buzzer OFF");
buzzerState = "off";
digitalWrite(buzzerPin, LOW);
}
}
}
// Clear the header variable
header = "";
// Close the connection
client.stop();
Serial.println("Client disconnected.");
Serial.println("");
}
}