Controlling Relays Using ESP32 Web Server


In the realm of automation and the Internet of Things (IoT), the ability to remotely control devices is paramount. One versatile and widely adopted platform for such applications is the ESP32 microcontroller, renowned for its robust performance and built-in Wi-Fi capabilities. In my previous article, I explained how to control server motor using esp32 web server with different widgets. But In this article, we delve into the fascinating world of controlling relays using an ESP32 web server, opening up new possibilities for seamless device management.

Relays serve as indispensable components in countless electronic systems, allowing the control of high-power devices through low-power signals. By combining the ESP32’s capabilities with the flexibility of a web server, we harness the power of the internet to provide a user-friendly interface for relay control from anywhere in the world.

Throughout this article, we explore the step-by-step process of creating a web server on the ESP32 microcontroller, enabling users to access and control relays through a web browser. We delve into the setup and configuration of the ESP32, ensuring its connectivity to the local network. Additionally, we guide readers through the process of creating a responsive web page interface, enabling intuitive relay control through the ESP32’s IP address.

The project’s significance lies in its potential to revolutionize home automation, industrial control systems, and various IoT applications. By harnessing the power of web technologies, users gain the ability to remotely monitor and manipulate devices, making daily routines more efficient and convenient. Whether it is controlling lights, appliances, or security systems, the ESP32 web server empowers users to maintain control from the comfort of their smartphones or computers.

Relays are essential components when it comes to controlling devices remotely through an ESP32 web server. The combination of an ESP32 microcontroller, which offers built-in Wi-Fi connectivity, and relays provides a powerful platform for seamless device management and automation.

To control relays from an ESP32 web server, the first step is to establish a connection between the ESP32 and the local network. The ESP32’s Wi-Fi capabilities allow it to connect to the internet, providing a pathway for remote control. Once connected, the ESP32 can act as a web server, hosting a web page that serves as the user interface for relay control.

The web page interface can be designed to display the status of the relays and provide control options. Users can access this interface from any device connected to the same network, such as a smartphone, tablet, or computer. Through the web page, users can send commands to the ESP32, instructing it to activate or deactivate the relays based on their requirements.

The ESP32 web server receives these commands and processes them accordingly. When a user selects a relay control option on the web page, the ESP32 triggers the appropriate GPIO pins connected to the relay coils. By energizing or de-energizing the coils, the ESP32 effectively controls the state of the relays, allowing the flow of current or interrupting it as desired.

Moreover, this project encourages exploration and experimentation, as users can easily expand upon the foundation laid here to integrate additional features, such as sensor readings, data logging, or even advanced automation algorithms. The versatility of the ESP32, coupled with the ubiquity of web interfaces, opens the door to limitless possibilities for controlling relays and creating custom automation solutions.

As we dive into the details of this project, we aim to provide a comprehensive guide that caters to both beginners and experienced enthusiasts. By the end of this article, readers will have gained a solid understanding of the ESP32’s capabilities, web server implementation, and relay control, empowering them to embark on their own automation journeys.

Amazon links:



Relay module

Ac Bulb

Jumper wires


Power supply

*Please Note: These are affiliate links. I may make a commission if you buy the components through these links. I would appreciate your support in this way!

About Relay:

Relays are fundamental electrical components that play a crucial role in controlling high-power circuits using low-power signals. They act as electrically operated switches, allowing the flow of current to be redirected or interrupted based on the activation or deactivation of an electromagnetic coil. This mechanism makes relays versatile devices widely used in various applications, ranging from industrial automation to home electronics.

At their core, relays consist of four essential components: the coil, the contacts, the armature, and the yoke. The coil, typically made of copper wire, generates a magnetic field when an electrical current passes through it. This magnetic field attracts the armature, a movable part within the relay, which is connected to the contacts. The contacts are conductive metal plates that can be in one of two positions: normally open (NO) or normally closed (NC).

ESP32 Web Server
Image source:

In a normally open relay, the contacts remain disconnected until the coil is energized. Once the coil receives an electrical current, the armature is magnetically attracted, causing the contacts to close and complete the circuit. Conversely, in a normally closed relay, the contacts are initially connected, and the coil de-energizes them when activated. This basic functionality allows relays to control the flow of current, enabling the switching of high-power devices using low-power control signals.

Relays are available in various types to suit different applications. Some common types include electromechanical relays, solid-state relays, reed relays, and latching relays. Electromechanical relays are the most traditional type and consist of mechanical moving parts. Solid-state relays, on the other hand, utilize semiconductor components to achieve switching without any mechanical motion, offering advantages such as faster switching speeds and longer lifespans.

The applications of relays are vast and diverse. In industrial automation, relays are employed to control motors, solenoids, and other high-power equipment. They serve as critical components in process control systems, allowing for precise regulation of machinery. In residential and commercial settings, relays are used to control lighting systems, heating, ventilation, and air conditioning (HVAC) units, and home appliances. They provide a safe and efficient means of managing power distribution and reducing energy consumption.

Additionally, relays find applications in automotive systems, telecommunications, robotics, and many other fields. Their ability to handle high currents and voltages, along with their electrical isolation capabilities, make them indispensable in situations where the control circuit and the power circuit need to be separated for safety or functional reasons.

With the advent of IoT and smart home technologies, relays have also found their way into interconnected systems. By integrating relays with microcontrollers or single-board computers, such as the ESP32, users can remotely control devices, monitor energy consumption, and create sophisticated automation routines through web interfaces or mobile apps.

About esp32 board:

The ESP32, developed by Espressif Systems, is a powerful microcontroller specifically designed for low-power, wireless, and IoT applications. It boasts an array of features and capabilities that make it a versatile platform for a wide range of projects.

At its core, the ESP32 is powered by the Xtensa LX6 processor, a dual-core CPU that can operate at speeds of up to 240 MHz. This processing power, combined with its integrated Wi-Fi and Bluetooth capabilities, positions the ESP32 as an ideal choice for IoT applications that require wireless communication.

The microcontroller offers an extensive selection of peripherals, including digital and analog I/O, SPI, I2C, UART, PWM, ADC, and DAC. Moreover, it comes equipped with a built-in hall-effect sensor and temperature sensor, expanding its potential applications even further. The digital I/O pins can be configured as either inputs or outputs, with a voltage handling capacity of up to 3.3V.

One of the standout features of the ESP32 is its exceptional low-power consumption. It boasts a deep-sleep mode that enables it to consume as little as 0.1 µA of power, making it highly suitable for battery-powered projects. Additionally, it incorporates an RTC (real-time clock) that can wake up the microcontroller at specified times, further reducing power consumption and maximizing energy efficiency.

When it comes to programming, the ESP32 offers flexibility and support for multiple languages, including C, C++, MicroPython, and Arduino. Developers can choose to program the ESP32 using the Espressif SDK or the popular Arduino IDE, ensuring a smooth and accessible development experience. Furthermore, a wealth of third-party libraries and tools are available, simplifying the programming process even further.

Connectivity options are abundant with the ESP32, which supports Wi-Fi, Bluetooth, BLE (Bluetooth Low Energy), and NFC (Near Field Communication). It adheres to Wi-Fi standards 802.11b/g/n and can function as either an access point or a station. Additionally, it supports Bluetooth 4.2 and BLE, making it an excellent choice for building low-power Bluetooth devices.

Thanks to its scalability, the ESP32 finds applications across various domains, such as smart homes, wearables, and industrial automation. Its adaptability makes it equally suitable for consumer and commercial projects, facilitating the development of connected devices that require low-power, wireless communication.

To aid in understanding the pin configuration, refer to the pinout diagram of the ESP32 board provided below:

ESP32 Web Server

About Esp32 Web Server:

The ESP32 Web Server is a remarkable feature of the ESP32 microcontroller that allows it to host a web server and provide a user interface accessible through a web browser. This powerful capability opens up a world of possibilities for remote control, monitoring, and interaction with devices and systems.

With the ESP32 Web Server, developers can create custom web pages that can be accessed from any device connected to the same network as the ESP32. Users can simply open a web browser on their computer, smartphone, or tablet, enter the IP address of the ESP32, and instantly access the web interface.

The web server functionality enables seamless communication between the user and the ESP32, facilitating remote control of devices, data display, configuration, and even real-time updates. The user interface can be designed to suit the specific application requirements, providing an intuitive and user-friendly experience.

To set up an ESP32 Web Server, developers need to configure the network settings of the ESP32 to connect it to the local network. This typically involves connecting the ESP32 to a Wi-Fi network and obtaining an IP address. Once connected, the ESP32 can start serving web pages and respond to HTTP requests from clients.

Developers can leverage various programming frameworks and libraries to build the web server functionality. The Arduino IDE, for instance, provides an ESP32 library that simplifies the process of creating a web server and handling client requests. Other frameworks and libraries, such as WiFi, ESPAsyncWebServer and ESP8266WebServer, offer additional features and flexibility for more advanced applications.

Using the web server, developers can implement various functionalities, such as controlling relays, reading sensor data, logging information, updating firmware, and more. Through the web interface, users can interact with these functionalities by submitting forms, clicking buttons, or accessing different web pages.

The ESP32 Web Server also supports secure communication through HTTPS, allowing for encrypted data transmission and authentication. This is particularly crucial when sensitive data is involved or when secure access to the web server is required.

Overall, the ESP32 Web Server capability revolutionizes the way devices are controlled and monitored by providing a platform-independent interface accessible from any device with a web browser. It simplifies the development process, enhances user interaction, and expands the possibilities for remote control and monitoring applications in fields such as home automation, industrial systems, IoT, and beyond.

Circuit diagram:

ESP32 Web Server

Install Required Library:

To install the ESP32 Arduino wifi library, you can follow these steps:

Open the Arduino IDE (Integrated Development Environment) on your system.

ESP32 Web Server

Navigate to “Sketch” in the menu bar and select “Include Library” -> “Manage Libraries.”

ESP32 Web Server

In the Library Manager window, you will see a search bar at the top. Enter “wifi” in the search field.

The search results will display the available WiFi libraries. Look for the library named “WiFi” by Arduino.

ESP32 Web Server

On the right side of the library name, you will see an “Install” button. Click on it to start the installation process. But In my case, I already installed it as you can see.

ESP32 Web Server Programming:

Code Explanation:

The code snippet provided demonstrates the process of controlling relays using an ESP32 microcontroller and a web server. The required libraries, such as WiFi, WiFiClient, and WebServer, are included at the beginning.

The next step involves defining the Wi-Fi network credentials by specifying the SSID (network name) and password. In this example, the SSID is set to “Fawad” and the password is set to “computer007”. These values may need to be modified to match the desired Wi-Fi network.

Four relay pins are then defined using an array. The pins are denoted by their respective GPIO numbers on the ESP32. In this case, the relay pins are set to GPIO 13, 14, 12, and 27.

An instance of the WebServer class is created, listening on port 80. Port 80 is commonly used for HTTP communication.

An array called “relayState” is initialized to keep track of the state of each relay. Each element in the array corresponds to a relay pin defined earlier. The initial state for all relays is set to false, indicating that they are initially turned off.

The provided code demonstrates the implementation of a web server that controls relays and provides a user interface to toggle their status. The function handleRoot() is responsible for generating the HTML content that will be sent as a response to the client when the root URL (“/”) is accessed.

The HTML code contains a combination of Bootstrap CSS and custom styles to ensure proper formatting and layout. JavaScript is used to dynamically update the relay status and handle relay toggling.

The updateRelayStatus() function is defined to update the status and appearance of each relay button. It uses an XMLHttpRequest object to asynchronously send a GET request to the server for retrieving the current status of each relay. Based on the response, the status text and button label are updated accordingly. The button’s CSS classes are modified to change its color based on the relay state.

To continuously update the relay status, the setInterval() function is called with a 2-second interval to repeatedly execute updateRelayStatus().

Within the HTML body, a container is created with a heading for controlling relays. A loop is used to generate the HTML elements for each relay. For each relay, the relay number, status, and a toggle button are displayed. The status is initially set based on the relayState array, which indicates whether the relay is ON or OFF. The button’s appearance and label are determined by the relay state as well.

The toggleRelay(relayIndex) function is defined to handle the button click event for toggling a relay. It sends a GET request to the server with the relay index to indicate which relay should be toggled. After the request is sent, the button’s appearance and label are updated based on the new relay state.

Finally, the HTML code is sent as a response with a status code of 200 (OK) and the “text/html” content type.

This code snippet combines HTML, CSS, and JavaScript to create a web-based interface for controlling relays connected to an ESP32 microcontroller.

The handleRelayToggle() function is responsible for processing requests to toggle the state of a relay in the ESP32 web server. When a request is received, the function first extracts the relay index from the request parameter and converts it to an integer.

Next, it checks if the relay index is within the valid range. This is done by comparing the relay index against the number of elements in the relayPins array, obtained using sizeof(relayPins) / sizeof(relayPins[0]). If the relay index is valid (greater than or equal to 0 and less than the array size), the code proceeds.

For a valid relay index, the function then toggles the state of the corresponding relay. It flips the value stored in the relayState array at the specified index using the logical NOT operator (!). This changes the state from true to false or vice versa.

The state of the relay is then updated by calling digitalWrite() with the corresponding relay pin from the relayPins array and the new state (HIGH for ON or LOW for OFF).

Finally, the server responds with an HTTP status code of 200 (OK), along with a response message indicating the current state of the relay (“Relay is ON” or “Relay is OFF”). If the relay index is invalid, meaning it is outside the valid range, the server responds with an HTTP status code of 400 (Bad Request) and an error message indicating an invalid relay index.

Overall, the handleRelayToggle() function handles relay toggling requests, updates the relay state, and sends an appropriate response back to the client.

The handleRelayStatus() function is designed to handle requests for retrieving the status of a relay in the ESP32 web server. When a request is received, the function first extracts the relay index from the request parameter and converts it to an integer using the toInt() function.

Next, it checks if the relay index is within the valid range. This is done by comparing the relay index against the number of elements in the relayPins array, obtained using sizeof(relayPins) / sizeof(relayPins[0]). If the relay index is valid (greater than or equal to 0 and less than the array size), the code proceeds.

For a valid relay index, the function sends an HTTP response with a status code of 200 (OK) and a plain text message indicating the current state of the relay. The message is determined by accessing the corresponding element in the relayState array and checking if it is true or false. If the relay state is true, the response message is set to “Relay is ON”. Otherwise, if the state is false, the message is set to “Relay is OFF”.

If the relay index is found to be invalid, meaning it is outside the valid range, the server responds with an HTTP status code of 400 (Bad Request) and an error message indicating an invalid relay index.

In summary, the handleRelayStatus() function processes requests for retrieving the status of a relay. It validates the relay index, sends the appropriate response with the current state of the relay, and handles errors if the relay index is invalid.

The for loop iterates over each element in the relayPins array. It sets the pin mode of each relay pin to OUTPUT using the pinMode() function. This step ensures that the specified pins are configured to control the relays.

Serial communication is initialized by calling Serial.begin(115200). This sets the baud rate for the serial communication to 115200 bits per second.

A small delay of 100 milliseconds is added using delay(100). This provides a brief pause to allow the system to stabilize before proceeding with further initialization.

The ESP32 connects to a Wi-Fi network by calling WiFi.begin(ssid, password), where ssid and password are variables holding the credentials of the Wi-Fi network. A while loop is then used to wait until the connection is established. Within the loop, a delay of 1 second is added using delay(1000), and a message “Connecting to WiFi…” is printed to the serial monitor using Serial.println().

Once the Wi-Fi connection is established, a message “Connected to WiFi” is printed to the serial monitor.

The web server functionality is set up by associating specific URL paths with corresponding handler functions. The server.on() function is used to define the routes. For example, when the root URL (“/”) is accessed, the handleRoot() function is invoked. Similarly, /relay/toggle and /relay/status routes are associated with the handleRelayToggle() and handleRelayStatus() functions, respectively.

The web server is started by calling server.begin(), enabling it to listen for incoming HTTP requests.

Finally, a message “Web server started” is printed to the serial monitor, indicating that the web server is up and running.

The loop() function is a crucial part of the Arduino sketch that runs repeatedly in an infinite loop after the setup() function has finished executing. Let’s explain the logic of the provided loop() function:

The loop() function contains only one line of code: server.handleClient();. This line is responsible for handling incoming client requests to the web server. It allows the web server to process and respond to the requests.

By calling server.handleClient(), the web server checks if there are any pending client requests. If a request is received, the server processes it and sends the appropriate response based on the defined routes and handler functions. After handling the client request, the web server returns to the loop() function and continues to check for new requests.

The loop() function is designed to continuously run and handle client requests as they come in. It ensures that the web server remains responsive and can serve multiple clients simultaneously.

Practical Demonstration:

Once the code is uploaded open the Serial Monitor in the Arduino IDE. It will display the ESP32’s IP address. Copy the IP address.

ESP32 Web Server

And paste in the web browser, and make sure your computer and esp32 are connected with the same network.

ESP32 Web Server

You can access the same IP address in mobile and tablet as well

ESP32 Web Server

Video Tutorial:

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button