Project Report On Iot Based Smart Keychain
Project Report On Iot Based Smart Keychain
Project Report On Iot Based Smart Keychain
PROJECT REPORT ON
2023-2024
2
ANURAG UNIVERSITY
Venkatapur(V),Ghatkesar(M), Medchal-Malkajgiri Dist-500088
DEPARTMENT OF ELECTRONICS AND COMMUNICATION
ENGINEERING
CERTIFICATE
This is to certify that the project report entitled “IOT BASED SMART KEYCHAIN” being
submitted by
3
DECLARATION
We hereby declare that the result embodied in this project report entitled “IOT BASED SMART
KEYCHAIN” is carried out by us during the year 2023-2024 for the partial fulfillment of the award of
Bachelor of Technology in Electronics and Communication Engineering, from ANURAG
UNIVERSITY. We have not submitted this project report to any other Universities / Institute for the
award of any degree.
BY
4
ACKNOWLEDGEMENT
This project is an acknowledgement to the inspiration, drive and technical assistance contributed by
many individuals. This project would have never seen light of this day without the help and guidance we
have received. We would like to express our gratitude to all the people behind the screen who helped us
to transform an idea into a real application. It’s our privilege and pleasure to express our profound sense
of gratitude to Dr. RAJESH THUMMA , Associate Professor, Department of ECE for his guidance
throughout this dissertation work. We express our sincere gratitude to Prof. N.MANGALA GOURI,
Head of Department, Electronics and Communication Engineering for his precious suggestions for the
successful completion of this project. He is also a great source of inspiration to our work. We would like
to express our deep sense of gratitude Anurag University for his tremendous support, encouragement and
inspiration. Lastly, we thank almighty, our parents, friends for their constant encouragement without
which this assignment would not be possible. We would like to thank all the other staff members, both
teaching and non- teaching, which have extended their timely help and eased my work.
BY
5
TABLE OF CONTENTS
CONTENTS
Name of the Content Page No
LIST OF FIGURES 6
LIST OF ABBREVATION
ABSTRACT 7
CHAPTER 1 : INTRODUCTION 8-10
1.1 IOT
CHAPTER 2: LITERATURE SURVEY 11-12
CHAPTER 3: HARDWARE REQUIREMENTS 13-15
3.1 NODEMCU ESP8266
3.2 JUMPER CABLES
3.3 AMS1117 3.3V VOLTAGE REGULATOR
3.4 LITHIUM POLYMER BATTERY
3.5 BUZZER
CHAPTER 4: SOFTWARE REQUIREMENTS 16-17
4.1 ARDUINO IDE
CHAPTER 5: PROPOSED METHODOLOGY 18-21
5.1 PROPOSED METHOD
CHAPTER 6: RESULTS AND DISCUSSION 22-23
6.1 RESULTS
CHAPTER 7: CONCLUSION AND FUTURE SCOPE 24
7.1 CONCLUSION
REFERENCES 25
APPENDIX 26
6
LIST OF FIGURES
7
ABSTRACT
Losing keys is a common yet frustrating experience in daily life. This project presents an IoT-
based smart keychain designed to assist in locating keys within close proximity. This project
introduces a Smart Key Finder system designed without Bluetooth, utilizing an Arduino Uno, a
Wi-Fi module ESP8266, and a voltage regulator to help users locate their misplaced keys.
The key finder comprises an Arduino Uno microcontroller, a Wi-Fi module ESP8266, a voltage
regulator, and a smartphone application. The Arduino Uno serves as the central processing unit,
interfacing with the Wi-Fi module to track key location. The Wi-Fi module connects the system to
the user's home Wi-Fi network, enabling remote access and control. The voltage regulator ensures a
stable power supply to all components.
The system operates by establishing a connection between the Arduino Uno and the user's
smartphone via the WiFi module. Users can send commands from a smartphone application to
trigger sound or light signals on the key finder device, assisting in locating misplaced keys within
the home. Additionally, the system can provide real-time location information through the
smartphone application.
This Smart Key Finder offers an affordable, efficient, and user-friendly solution to the problem of
lost keys, without relying on Bluetooth technology. The use of Arduino Uno, Wi-Fi connectivity,
and a voltage regulator enhances its functionality and ease of use, making it a valuable addition to
everyday life.
8
CHAPTER-1
INTRODUCTION
1.1 IOT: The Internet of things (IoT) is the extension of Internet connectivity into physical devices
and everyday objects. Embedded with electronics, Internet connectivity, and other forms of
hardware (such as sensors), these devices can communicate and interact with others over the
Internet, and they can be remotely monitored and controlled.
An IoT system consists of sensors/devices which “talk” to the cloud through some kind of
connectivity. Once the data gets to the cloud, software processes it and then might decide to
perform an action, such as sending an alert or automatically adjusting the sensors/devices without
the need for the user.
9
Fig 1.2 Working of IOT
Just like Internet has changed the way we work & communicate with each other, by connecting us
through the World Wide Web (internet), IoT also aims to take this connectivity to another level by
connecting multiple devices at a time to the internet thereby facilitating man to machine and
machine to machine interactions.Fig 1.2 describes the working of IOT.
10
Here, 4 fundamental components of IoT system, which tells us how IoT works. i . Sensors/Devices
First, sensors or devices help in collecting very minute data from the surrounding environment. All
of this collected data can have various degrees of complexities ranging from a simple temperature
monitoring sensor or a complex full video feed. A device can have multiple sensors that can bundle
together to do more than just sense things. For example our phone is a device that has multiple
sensors such as GPS, accelerometer, camera but our phone does not simply sense things.
The most rudimentary step will always remain to pick and collect data from the surrounding
environment be it a standalone sensor or multiple devices
Connectivity
Next, that collected data is sent to a cloud infrastructure but it needs a medium for transport. The
sensors
can be connected to the cloud through various mediums of communication and transports such as
cellular networks, satellite networks, Wi-Fi, Bluetooth, wide-area networks (WAN), low power
wide area network and many more.
Every option we choose has some specifications and trade-offs between power consumption, range,
and bandwidth. So, choosing the best connectivity option in the IOT system is important
Data Processing
Once the data is collected and it gets to the cloud, the software performs processing on the acquired
data. This can range from something very simple, such as checking that the temperature reading on
devices such as AC or heaters is within an acceptable range. It can sometimes also be very complex,
such as identifying objects (such as intruders in your house) using computer vision on video.
But there might be a situation when a user interaction is required, example- what if when the
temperature is too high or if there is an intruder in your house? That’s where the user comes into the
picture.
User Interface
Next, the information made available to the end-user in some way. This can achieve by triggering
alarms on their phones or notifying through texts or emails.
Also, a user sometimes might also have an interface through which they can actively check in on
11
their IOT system. For example, a user has a camera installed in his house, he might want to check
the video recordings and all the feeds through a web server.
However, it’s not always this easy and a one-way street. Depending on the IoT application and
complexity of the system, the user may also be able to perform an action that may backfire and
affect the system.
For example, if a user detects some changes in the refrigerator, the user can remotely adjust the
temperature via their phone.
There are also cases where some actions perform automatically. By establishing and implementing
some predefined rules, the entire IOT system shown in Fig 1.3 can adjust the settings automatically
and no human has to be physically present.
Also in case if any intruders are sensed, the system can generate an alert not only to the owner of
the house but to the concerned authorities.
12
CHAPTER-2
A Literature review also focuses on the knowledge and ideas established on a topic as well as their
strengths and weaknesses. Nowadays, technology is getting better and better to replacing the
traditional system to speed up the process by introducing the computerized system.
Several studies have been conducted on IoT based detection and tracking system. One of the
examples is the IoT
based fire alarm system. Asma Mahgoub, Abdullahal-Ali, Nourhan Tarrad, (2019) has designed an
IoT based fire alarm system. The author has proposed an IoT based wireless fire alarm system that
is easy to install. The proposed system was able to achieve its goals which were mainly building an
IoT based fire alarm system that was capable of detecting the presence of fire and call or sent SMS
to the necessary parties when a fire is detected[1]. The drawback of this system of the study is that
it could have used a rechargeable battery source instead of a power supply.
IoT was also incorporated widely to Human Activity Recognition (HAC) by monitoring the vital
signs remotely. Diego Castro, William coral, Camila Rodriguez (2017) has designed a wearable-
based human activity recognition using IoT based devices. The proposed system used an ESP8266
microcontroller. Each microcontroller program to detect the data from the sensors (heart rate,
respiration rate, skin temperature)[2]. An application has been created to record the data that were
taken from the sensors. These data can be checked by a medical professional daily. If the patient
lives far away from a medical assistance a call or a SMS will be sent to a hospital to monitor the
patient any vital sign are showing any problem. The proposed system was able to achieve its
objective which was to build a human activity recognition IoT based device to monitor and record
their vital signs. Also, to send a SMS or call the hospital if any sign doesn’t see normal[2]. The
drawback for this system is that it can be more lightweight and instead of putting the device in waist
13
it can be build smaller so it can fit in the arm.
A smart key system design for electric bike for Vietnam Environment proposed by Veerandi
Maleesha ,Ilya Kavalchuk along with Andrew Smith from School of Science and Technology ,
RMIT University provides the capability to perform the basic queries to determine the current
conditions of the electric bike, such as the battery charge status, security and external lighting
control of the bike to improve personal security. Solutions are proposed to acquire the charge and
light control unit status[3].
In this project we are designing a IoT based SMART KEY CHAIN using a Arduino uno , Nodemcu and
Wi-Fi module to locate misplaced keys. In this IoT-based smart keychain project leveraging the Arduino
and NodeMCU has explored the convergence of modern IoT technology and everyday objects to enhance
the utility and security of a commonplace item - the keychain.
14
CHAPTER-3
HARDWARE REQUIREMENTS
NodeMCU boards typically have 10 to 11 digital GPIO pins that can be used for general digital input
and output. These pins are often labeled as D0, D1, D2, D3, D4, D5, D6, D7, D8, D9, and D10.
You can use these pins for interfacing with digital sensors, controlling LEDs, and other digital devices.
Analog Pins: NodeMCU boards usually have one or more analog input pins that can be used to read
Special Function Pins: Some GPIO pins on the NodeMCU board have special functions, such as:
15
RX and TX: These pins are used for serial communication (UART). RX is for receiving data, and TX
is for transmitting data.
SDA and SCL: These pins are used for I2C communication.
MISO, MOSI, and SCK: These pins are used for SPI communication.
A0: It can be used as a digital GPIO or Analog input, depending on your project requirements.
The NodeMCU board also provides 3.3V and 5V pins for power supply and multiple ground (GND)
pins.
These pins are used to power the board and connect ground references.It's important to note that the
labeling of these pins may vary slightly depending on the specific NodeMCU board version you are
using. Always refer to the pinout diagram provided with your NodeMCU board to identify the pins
accurately.When working with NodeMCU, you can use these GPIO pins to interface with various
sensors, actuators, and other devices in your IoT projects. Be sure to configure the pins correctly in your
code to match your hardware connections.
3.2 Micro USB Cable: Fig 3.2 shows Micro USB cable used to connect the NodeMCU board to your
computer or power source for programming and power. The NodeMCU board typically features a micro
USB port for this purpose.
Programming and Debugging: When you're initially setting up the NodeMCU or need to upload
new firmware or code, you can use a micro USB cable to connect the NodeMCU to your
computer. This enables you to program and debug the board through the USB connection. Ensure
that you have the necessary drivers and development environment (e.g., Arduino IDE) set up on
16
your computer to program the NodeMCU.
Powering the NodeMCU: A micro USB cable can also serve as a power source for the
NodeMCU. By connecting the NodeMCU to a USB power adapter, power bank, or any other
USB power source using the micro USB cable, you can provide the necessary power to run your
IoT project. This is particularly useful when your NodeMCU project is deployed and needs a
steady power supply.
Serial Communication: When you connect the NodeMCU to your computer using a micro USB
cable, it allows for serial communication between your computer and the NodeMCU. This is
essential for uploading code, monitoring the board's serial output, and debugging.
Data Transfer: If your NodeMCU project involves data transfer with your computer, you can use
the micro USB cable for this purpose. For example, you can use it to transfer data from sensors
or other peripherals connected to the NodeMCU.
Connecting a NodeMCU to an Arduino using a micro USB cable involves setting up a serial
communication link between the two devices. This connection allows data to be exchanged between
them, enabling various applications. Here's how we connect a NodeMCU to an Arduino using a
micro USB cable :
Prepare the Hardware: You will need a NodeMCU board and an Arduino board. Ensure both
boards are powered via USB. Connect the NodeMCU to one USB port and the Arduino to
another.
Install Necessary Drivers: If you haven't already, make sure you've installed the appropriate
drivers for both the NodeMCU and the Arduino on your computer.
Upload Code to NodeMCU: Use the Arduino IDE to write and upload code to the NodeMCU.
Ensure that the code includes Serial communication, which will allow the NodeMCU to send and
receive data through the USB connection.
Arduino as a Serial Monitor: The Arduino can act as a simple serial monitor. You can use the
Arduino Serial Monitor to receive data from the NodeMCU and display it on your computer
screen.
Open the Arduino IDE, select the Arduino board connected to your computer, and open the
Serial Monitor. The Serial Monitor will display the data transmitted by the NodeMCU.
NodeMCU as a Serial Device: In your NodeMCU code, use the Serial.begin() function to set up
17
serial communication.
Data Exchange: Once the code is uploaded to both the NodeMCU and the Arduino, the two
devices can exchange data via the USB cable. The NodeMCU can send data to the Arduino,
which can display or process it.
Data Interpretation: Ensure that the data sent by the NodeMCU and received by the Arduino is
correctly formatted and interpreted according to your project's requirements.
3.1 Jumper Wires : Jumper wires are simple cables having connector pins on both ends that may be
used to connect two points without the use of solder. Jumper wires are commonly used with breadboards
and other prototyping tools to allow for quick circuit changes. It's quite straightforward, Jumper wires
are the most fundamental of all electrical components.
3.2 AMS1117 3.3V Voltage Regulator Default (GPT-3.5) : The AMS1117 shown in Fig 3.4
is a popular voltage regulator integrated circuit (IC) designed to provide a stable and regulated output
voltage of 3.3 volts. It's commonly used in electronic circuits to ensure a consistent power supply to
components that require this specific voltage level.
18
Fig 3.4 AMS1117 3.3 voltage regulator
Key features of the AMS1117 3.3V voltage regulator include:
Output Voltage: 3.3 volts ± 2%. This means it maintains a very close voltage output to 3.3V,
which is important for reliable operation of many digital and analog components.
Input Voltage Range: Typically, it can handle input voltages between 4.75V and 12V, making it
suitable for a variety of applications.
Low Dropout Voltage: The dropout voltage is the minimum voltage difference between the input
and output at which the regulator can still maintain the specified output voltage. The AMS1117
has a low dropout voltage, meaning it can operate efficiently even when the input voltage is only
slightly higher than the desired output voltage.
Current Limiting and Thermal Protection: It includes built-in current limiting and thermal
shutdown features to protect the device from overcurrent and overheating conditions.
TO-220 or SOT-223 Package: It's available in different package styles, including the TO-220 and
SOT-223, which affect its physical size and heat dissipation capabilities.
Overall, the AMS1117 3.3V voltage regulator is a reliable and cost-effective component for
ensuring a stable 3.3V power supply in various electronic circuits and applications.
19
3.2 Buzzer : A buzzer shown in the Fig 3.5 is a simple electronic device that produces a buzzing
or beeping sound when an electrical current passes through it. It is commonly used in various
applications, such as alarms, timers, and notifications, to provide an audible alert or signal. Buzzer
designs can vary, including electromagnetic and piezoelectric types, each with its own characteristics
and applications. They play a crucial role in alerting people to important events or situations.
20
CHAPTER-4
SOFTWARE REQUIREMENTS
4.1 The Arduino Integrated Development Environment - or Arduino Software (IDE) - Fig 4.1
contains a text editor for writing code, a message area, a text console, a toolbar with buttons for
common functions and a series of menus. It connects to the Arduino hardware to upload
Programs written using Arduino Software (IDE) are called sketches. These sketches are written in the
text editor and are saved with the file extension ino. The editor has features for cutting/pasting and for
searching/replacing text. The message area gives feedback while saving and exporting and also
displays errors. The console displays text output by the Arduino Software (IDE), including complete
error messages and other information. The bottom righthand corner of the window displays the
configured board and serial port. The toolbar buttons allow you to verify and upload programs, create,
open, and save sketches, and open the serial monitor.
21
CHAPTER-5
5.1 PROPOSED METHODOLOGY
Introduction :
We present the methodology for the development of a Smart Key Finder using Arduino, ESP8266, and
a Voltage Regulator. The primary objective of this project is to create a cost-effective and power-
efficient key tracking system without relying on Bluetooth, a buzzer, or GPS tracker technologies. This
methodology chapter outlines the key steps involved in achieving this goal.
Block Diagram :
The block diagram shown in the fig 5.1 illustrates the core components and their interactions in our
Smart Key Finder system. It includes the following components:
22
Arduino: This microcontroller is responsible for key detection and overall system control.
ESP8266: The ESP8266 module is used for wireless communication, transmitting key status to the
user's device.
Voltage Regulator: The voltage regulator ensures a stable power supply to all components, enhancing
the system's reliability.
Circuit Diagram
The circuit diagram shown in the fig 5.2 provides a detailed representation of the physical connections
between the components.
Arduino-Nodemcu ESP8266 Interface: The Arduino and ESP8266 are connected via serial communication
(UART), allowing them to exchange data.
Voltage Regulator: It takes an input voltage from a power source and provides a regulated output
voltage to power the Arduino and ESP8266.
23
Flow Chart :
The flow chart shown in the fig 5.3 outlines the software logic that governs the Smart Key Finder's
operation. It depicts the sequence of operations within the system:
Key Detection: The Arduino constantly checks for the presence of the key.
Key Detected? : If a key is detected, the system proceeds to notify the user; otherwise, it
continues monitoring.
24
Algorithm :
arduino
Copy
code
void setup() {
// Initialize components
void loop() {
if (detectKey())
{ notifyUser();
delay(1000);
bool detectKey() {
void notifyUser() {
The algorithm implemented in the Arduino code is responsible for the core functionality of the Smart
Key Finder. It constantly checks for the presence of the key, and when detected, it triggers the
notification process through the ESP8266.
25
ESP8266 Integration
The ESP8266 module is integrated into the system to handle wireless communication. It connects to
the user's network and transmits key status notifications to a designated device or server, ensuring that
the user can locate their key promptly.
Voltage Regulation
The Voltage Regulator plays a crucial role in the system by providing a stable power supply. It
regulates the input voltage from a power source, preventing voltage fluctuations that could affect the
reliability of the components.
Operational Explanation
This section provides a detailed operational explanation of the Smart Key Finder, covering various
scenarios, such as key detection, user notification, and power-saving modes. It clarifies how the system
functions seamlessly to meet its objectives.
We compare our Smart Key Finder solution with traditional Bluetooth and GPS-based key finders,
highlighting the advantages of cost-effectiveness, power efficiency, and simplicity in design.
26
CHAPTER-6
We've created a basic prototype of the IoT-based smart keychain project which is shown in the Fig 6.1
using a breadboard and powered it by drawing voltage from the Arduino itself rather than using an
external battery. This prototype demonstrates the core functionality of remotely activating a buzzer via
a web interface hosted on an ESP8266 module, which can be a valuable proof of concept and a starting
point for further development and refinement of your project.
27
The webpage shown in the Fig 6.2 serves as a simple control interface for the buzzer connected to
your ESP8266 module. It allows you to remotely toggle the buzzer's state by clicking the button on
the webpage, and the current state is displayed for feedback.
The above Fig 6.3 is an IoT-based smart keychain that uses an Nodemcu ESP8266 module to host a web interface accessible
via Wi-Fi. Users can access the interface through a web browser on any device connected to the same network. The interface
provides a button to remotely control a buzzer on the keychain, helping users locate their keys with the press of a button.
Functionality
The smart key finder successfully established a Wi-Fi connection with the user's smartphone and
triggered an alert when the keys were out of range.
Battery Life
In standby mode, the device's battery lasted approximately 3 months, demonstrating its efficiency and
long- lasting power source
Cost Analysis
The total cost of materials for our smart key finder was 300rs, significantly lower than popular
Bluetooth key finders, which can range from 1000rs to 5000rs.
28
Usefulness to Society
This project addresses the widespread problem of lost keys, potentially saving individuals hours of
searching and reducing stress associated with lost items.
Environmental Safety
The device uses low-power components and operates efficiently, minimizing its carbon footprint. Its
casing is also made from recyclable materials.
While Bluetooth and GPS trackers offer precise location data, they come at a higher cost and may
require frequent battery replacements. Our device offers a budget-friendly alternative.
Future Improvements
Future iterations could include Bluetooth connectivity for wider compatibility and GPS tracking for
precise location data. These enhancements could increase cost but significantly improve functionality.
Limitations
The device's Wi-Fi range is limited to 100 feet, and it may be affected by obstacles like walls,
which is a limitation we acknowledge.
29
CHAPTER-7
7.1 CONCLUSION
In conclusion, the IoT-based smart keychain project using Arduino, Nodemcu ESP8266, and a buzzer
is a rewarding endeavor that offers several valuable takeaways and outcomes:
Functional Smart Keychain: By successfully completing the project, you have created a practical and
functional device that allows you to remotely trigger a buzzer sound to locate your keys. This enhances
convenience and demonstrates your ability to integrate hardware and software components.
Hands-On Learning: Throughout the project, you gained hands-on experience in various domains,
including Arduino programming, ESP8266 configuration, hardware integration, and IoT development.
This experience serves as an excellent foundation for future electronics and IoT projects.
Problem-Solving Skills: You honed your problem-solving skills by identifying and addressing
challenges that inevitably arose during the project. Troubleshooting and debugging are crucial skills in
the world of electronics and programming. Customization Potential: The project can be customized and
expanded further to meet your specific needs. Additional features like GPS tracking, LED indicators,
or low battery notifications can be integrated to enhance functionality. User Experience
Considerations: If you designed a user-friendly web interface or mobile app, you learned the
importance of user experience (UX) in making your IoT device more accessible and enjoyable to use.
Scalability and Future Opportunities: This project can serve as a stepping stone for more advanced IoT
projects. You can explore further integrations, automation, or even commercialization if you wish to
turn your prototype into a marketable product. Community Engagement: Sharing your project with the
maker and IoT communities can foster collaboration, provide valuable feedback, and allow you to
contribute to the broader knowledge pool. Security Awareness: You likely gained an understanding of
the importance of security in IoT projects and learned how to implement measures to protect your
device from unauthorized access. In summary, the IoT-based smart keychain project is not just about
creating a gadget; it's a journey of learning, problem-solving, and innovation. It empowers you with
practical skills and opens the door to future opportunities in the exciting world of IoT and electronics.
Whether you use it as a personal tool or a starting point for larger endeavors, the knowledge and
experience gained from this project are invaluable.
30
REFERENCES
[1] Asma Mahgoub, Abdullah al-Ali, Nourhan Tarrad, (2019) has designed an IoT based fire alarm system
[2] Michel Mouly, Marie-Bernadette pautet (1992), The GSM System For MobileCommunications (1"
edition), New York: Thomas Haug
[3] Tom Igoe (2012), Getting Started With RFID (1" edition), United States of
America: Brian Jepson
[4] Mark Geddes (2016), Arduino Project Handbook (2nd edition), San Francisco,
United States.
[5] Robert Wilbert Rodenbeck, Roger Keith Russell, and Micheal Lee Long""Wireless
security control system", Stanley Security Solutions Inc,Best Access System, 1999-03-
12.
[6] Joseph Frank Scalisi, SkyBell Technologies Inc, "Smart Lock System and Methods",2013-07- 26.
[7] Erez Segev, and Shmuel Gan, "Intelligent Interactive Lock and Locking System" 2004-07-06.
31
Arduino code :
#include
<ESP8266WiFi.h>
#include <WiFiClient.h>
#include
<ESP8266WebServer.h>
ESP8266WebServer server(80);
const int buz_pin = D2;
char ssid[] = "Galaxy-
M20"; char pass[] =
"ac312124";
String html_code = "<!DOCTYPE html><html><head><style>.button {border: none;padding: 12px
40px;text-align: center;text-decoration: none;display: inline-block;font-size: 16px;margin: 4px
2px;cursor: pointer;}.button1 {background-color: black; color: white; border: 3px solid
#1c1c1b;border-radius: 30px}body {text-align: center;}</style></head><body><h2>IoT Based
Keychain</h2><p>Press the Button to Turn On/Off the Buzzer</p><form action=\"/BUZ\"
method=\"POST\"><button class=\"button button1\">Click Me!</button></form>";
boolean buzzing_state =
false; void handleRoot() {
server.send(200, "text/html", html_code + "Current state: <b>" + buzzing_state);
}
void handleBUZ() {
buzzing_state = !buzzing_state;
server.sendHeader("Location","/")
; server.send(303);
}
void handleNotFound(){
server.send(404, "text/plain", "404: Not found");
}
void setup(void){
Serial.begin(115200)
; delay(10);
32
pinMode(buz_pin, OUTPUT);
Serial.print("\n\nConnecting Wifi...
"); WiFi.begin(ssid, pass);
while (WiFi.status() != WL_CONNECTED)
{
delay(500);
}
Serial.println("OK!");
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
Serial.println();
server.on("/", HTTP_GET, handleRoot);
server.on("/BUZ", HTTP_POST, handleBUZ);
server.onNotFound(handleNotFound);
server.begin();
Serial.println("HTTP server started\n");
}
void loop(void){
server.handleClient();
if (buzzing_state == true) {
digitalWrite(buz_pin, HIGH);
delay(400);
yield();
digitalWrite(buz_pin, LOW);
delay(200);
yield();
delay(400);
yield();
}
}
33
CODE EXPLANATION
Include Libraries: You include the necessary libraries for working with ESP8266, Wi-Fi, and web
server functionality.
ESP8266WebServer Object: You create an ESP8266WebServer object named server to handle
HTTP requests on port 80.
Constants and Variables:
buz_pin is defined as D2, presumably connected to the
buzzer. ssid and pass are the Wi-Fi network credentials.
html_code contains the HTML code for the web page served by the ESP8266. It includes a button to
control the buzzer.
buzzing_state: A boolean variable to keep track of the buzzer's state (on/off).
handleRoot() Function: This function handles the root URL ("/") and sends an HTML
response that includes the current state of the buzzer.
handleBUZ() Function: This function is called when the button is pressed on the web page. It
toggles the buzzing_state and sends a redirect response back to the root URL.
handleNotFound() Function: This function handles requests for URLs that are not found and sends
a 404 response.
setup() Function:
Initializes the serial communication for
debugging. Sets up the buzzer pin as an
output.
Connects to the Wi-Fi network.
Defines routes for the root URL, "/BUZ" (for controlling the buzzer), and a 404
handler. Starts the web server.
loop() Function:
Handles incoming client requests using server.handleClient().
If buzzing_state is true, it turns on the buzzer for a short period and then turns it off, creating a
buzzing effect.
34