ESP32

Controlling Servo Motor Using ESP32 Web Server

Introduction:

In the rapidly evolving landscape of the Internet of Things (IoT), remote control of devices has become a game-changer. Among the myriad of devices, servo motors hold immense potential for a wide range of applications. Their precise positioning and motion control capabilities make them indispensable in fields such as robotics, automation, and beyond. In this article, we delve into the fascinating world of controlling servo motor using ESP32 microcontroller and its remarkable web server capabilities. Through two comprehensive examples, we demonstrate how the ESP32, coupled with intuitive interfaces, empowers users to seamlessly and dynamically control servo motors with ease.

In the first example, we showcase a user-friendly approach to controlling a servo motor using a TextBox and a Button interface through the ESP32 web server. By establishing a connection between a web browser and the ESP32, users can input specific angle values into the TextBox. With a simple click of the Button, the ESP32 processes the command and orchestrates precise positioning of the servo motor according to the entered angle. This interactive method provides an accessible means for remote servo motor manipulation, making it suitable for individuals with varying levels of technical expertise. Whether it’s adjusting the angle of a robotic arm or controlling the position of a camera, this example demonstrates the versatility of the ESP32 web server interface in enabling precise and responsive servo motor control. Moving beyond text-based input, the second example explores a visually engaging method of servo motor control using a Slider interface, facilitated by the ESP32 web server. Leveraging the ESP32’s capabilities, we create a dynamic web page with a Slider element that represents the full range of servo motor angles. Users can intuitively adjust the Slider’s position to set the desired angle for the servo motor. The ESP32 swiftly captures the changes and transmits the updated angle information, resulting in seamless and accurate adjustments of the servo motor’s position. This example showcases the interactive nature of the ESP32 web server, enabling real-time servo motor control through an engaging and intuitive visual interface. Whether it’s controlling the tilt of a surveillance camera or adjusting the position of a robotic gripper, this example exemplifies the versatility of the ESP32 in transforming servo motor control into a user-friendly and immersive experience.




The ESP32 microcontroller, with its robust features and built-in web server capabilities, provides the foundation for these innovative servo motor control examples. By seamlessly integrating with web technologies, the ESP32 offers a powerful platform for remote control applications. Leveraging the ESP32’s Wi-Fi connectivity and web server functionalities, users can establish a secure connection between their web browser and the microcontroller, enabling real-time communication and servo motor manipulation from anywhere in the world.

Beyond the two examples mentioned, the possibilities for servo motor control using ESP32 web server are virtually endless. With the freedom to develop custom web pages and interface elements, developers can create tailored solutions to suit specific applications. Whether it’s designing an intuitive graphical interface for controlling multiple servo motors simultaneously or integrating advanced features such as data logging and motion profiling, the ESP32 web server opens up a world of possibilities for servo motor control.

In this article, we will guide you through the implementation details of both examples, providing step-by-step instructions and code snippets to help you kickstart your own servo motor control projects using the ESP32 web server. We will explore the necessary hardware and software components, discuss the programming techniques involved, and offer insights into best practices for optimal performance.

Join us on this exciting journey of controlling servo motor using ESP32 web server, as we unlock the potential of remote control, automation, and IoT innovation. By combining the power of the ESP32 with intuitive web interfaces, we empower individuals and businesses to harness the full capabilities of servo motors and revolutionize the way we interact with our physical environment. Get ready to embark on a transformative adventure where the ESP32 takes center stage in shaping the future of servo motor control.



Amazon link:

ESP32

Servo Motors

Jumper wires

Breadboard

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!

Servo Motor Construction and Operating Principles:

Image depicting SG90 servo motor control through an ESP32 web server.

The SG90 servo motor is a commonly used micro servo motor in hobbyist and small-scale robotics projects. It is known for its compact size, affordability, and ease of use. The SG90 servo motor operates on the principle of a closed-loop control system, which allows for precise positioning and control of its output shaft.

Construction:

The SG90 servo motor consists of several key components that work together to enable its motion control capabilities. These components include:

Image of a 3D representation of a servo motor construction with a control circuit board used for an ESP32 web server.

DC Motor: At the core of the servo motor is a small DC motor. It is responsible for generating the rotational motion of the output shaft. The motor is typically a brushed DC motor, which is simple in design and efficient in converting electrical energy into mechanical motion.

Gear Train: To increase torque and reduce the speed of the output shaft, the SG90 servo motor incorporates a gear train. The gear train consists of a series of gears with different sizes that are interlocked and transmit motion from the motor to the output shaft. This gearing mechanism allows the servo motor to achieve high torque output while maintaining a relatively small form factor.

Control Circuitry: The servo motor includes an internal control circuit that receives control signals and converts them into appropriate motor movements. This circuitry typically consists of a microcontroller, position feedback potentiometer, and a motor driver. The microcontroller interprets the control signals and adjusts the motor’s rotation based on the desired position.

Output Shaft: The output shaft is the part of the servo motor that extends from the casing and connects to external mechanisms. It allows for the transfer of rotational motion to other components, such as linkages or mechanical arms, enabling the servo motor to perform various tasks.



Operating Principles:

The SG90 servo motor operates based on the principle of feedback control. When a control signal is applied to the motor, the internal control circuitry compares the desired position with the current position of the output shaft, as detected by the position feedback potentiometer. Based on this comparison, the control circuit adjusts the motor’s rotation to minimize the positional error.

The control signal, often referred to as a PWM (Pulse Width Modulation) signal, consists of a train of pulses. The width of the pulses determines the desired position or angle of the servo motor. For example, a pulse width of 1.5 milliseconds might correspond to a center position, while shorter or longer pulse widths represent different angles.

When the control circuit receives the PWM signal, it generates a corresponding control signal to the motor driver, which provides the necessary power and voltage to the DC motor. The motor driver adjusts the voltage polarity and magnitude to control the motor’s speed and direction, allowing for precise positioning of the output shaft.

As the motor rotates, the position feedback potentiometer continuously monitors the position of the output shaft. It sends this information back to the control circuit, which compares it with the desired position. If there is a discrepancy, the control circuit adjusts the motor’s rotation accordingly to minimize the error and maintain the desired position.

Overall, the SG90 servo motor’s construction and operating principles make it a versatile component for controlling precise motions in various applications, including robotics, remote-controlled vehicles, and model airplanes.

Specifications:

Operating Voltage: The SG90 servo motor typically operates at a voltage range of 4.8V to 6V, making it compatible with common power sources such as batteries or regulated power supplies.

Stall Torque: The stall torque is the maximum torque output that the servo motor can exert when stalled (i.e., not rotating). The SG90 servo motor usually has a stall torque ranging from 1.8 kg/cm to 2.2 kg/cm, providing sufficient force for small-scale tasks.

Operating Speed: The operating speed of the servo motor refers to how quickly it can rotate from one position to another. The SG90 servo motor typically has an operating speed of around 0.1 seconds per 60 degrees, which means it can perform relatively fast movements.

Weight: The weight of the SG90 servo motor is generally lightweight, ranging from 8 grams to 9 grams. This low weight makes it suitable for applications where weight is a crucial factor, such as aerial robotics or small robotic systems.

Dimensions: The dimensions of the SG90 servo motor are compact and standardized, with approximate dimensions of 23 mm x 12.2 mm x 29mm (LxWxH). These dimensions allow for easy integration into various projects with limited space.



Features:

Position Control: The SG90 servo motor offers precise position control, allowing you to set the desired angle or position of the output shaft. This feature is achieved through the servo’s closed-loop control system, which continuously adjusts the motor’s rotation to minimize positional error.

PWM Control: The SG90 servo motor is typically controlled using a PWM signal. This feature enables easy interfacing with microcontrollers, embedded systems, or other devices capable of generating PWM signals, providing a convenient method for controlling the motor’s position and movement.

Plug-and-Play Compatibility: The SG90 servo motor often comes with standard connectors, such as a 3-pin header or jumper wires. This plug-and-play compatibility simplifies the process of connecting the servo motor to your control system, reducing the need for additional wiring or soldering.

Low Power Consumption: The SG90 servo motor is designed to be energy-efficient, consuming low power during operation. This characteristic is particularly beneficial for battery-powered applications, as it helps extend the battery life and reduces overall power requirements.

Durable Construction: Despite its small size, the SG90 servo motor is typically built with durable materials, ensuring its reliability and longevity. It can withstand moderate loads and operate reliably under normal working conditions.

About SG90 servo motor wires

Image showing the wiring connections for controlling an SG90 servo motor through an ESP32 web server.

The SG90 servo motor consists of three wires, each serving a specific purpose. The power wire, typically color-coded as red, is responsible for supplying electrical power to the servo motor. It connects to the positive terminal of the power source, which is usually a voltage in the range of 4.8V to 6V. This wire carries the DC voltage required to operate the internal components of the servo motor, including the motor itself and the control circuitry.

The ground wire, usually color-coded as brown or black, is used to complete the electrical circuit and provide a reference point for the electrical signals. It connects to the negative terminal of the power source, ensuring proper electrical grounding and allowing for the flow of electrical current through the motor. The ground wire helps maintain a stable electrical reference for the servo motor’s operation.

The signal wire, often color-coded as yellow or white, is responsible for carrying the control signal to the servo motor. It transmits the Pulse Width Modulation (PWM) control signal from the controlling device, such as a microcontroller or a servo controller board, to the servo motor. The control signal’s timing and pulse width determine the desired position or angle of the servo motor’s output shaft. The signal wire carries this control information, instructing the servo motor to move to the specified position.

It’s crucial to make the correct wire connections when using the SG90 servo motor. Swapping the power and ground wires or connecting the signal wire incorrectly can result in malfunctioning or erratic behavior of the servo motor. Properly understanding the functions and connections of the power, ground, and signal wires ensures accurate control over the SG90 servo motor’s movements in your projects.




Controlling Servo Motor using ESP32 Web Server Circuit Diagram

Image displaying the circuit diagram for connecting an SG90 servo motor with an ESP32 web server.

Connect the control signal wire (typically yellow or white) of the SG90 servo motor to GPIO13 on the ESP32. GPIO13 is a General-Purpose Input/Output pin capable of generating the required PWM signals for servo motor control. This connection allows the ESP32 to send control signals to the servo motor and adjust its position.

Connect the power supply wire (Vcc) of the SG90 servo motor to the 5V pin on the ESP32. This ensures that the servo motor receives the necessary power supply voltage. It is important to verify that the voltage supplied by the 5V pin matches the operating voltage requirements of the servo motor. Most servo motors operate at 5V, but always refer to the specifications of your specific servo motor to confirm the voltage requirement.

Connect the ground wire (GND) of the servo motor to the GND (ground) pin on the ESP32. This establishes a common ground reference between the ESP32 and the servo motor, completing the electrical circuit. It ensures proper communication and operation between both devices.

With these connections established, the ESP32 microcontroller, along with the web server functionality, can control the position of the servo motor. By sending control signals through GPIO13, the ESP32 can adjust the servo motor’s position according to the received commands.

Always consult the datasheets, pin diagrams, and documentation of your specific servo motor and ESP32 board to ensure accurate wiring and compatibility for your project. This will help you understand any specific requirements or considerations related to your hardware setup.



Required Library Installation:

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

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

Image depicting the Arduino IDE interface for installing the ESP32 Servo Motor Library to enable web server control.

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

Image depicting the installation of the ESP32 Servo Motor Library via the Library Manager in the Arduino IDE for ESP32 web server development.

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

Image showcasing the search for the ESP32 Servo Motor Library in the Library Manager of the Arduino IDE, used for controlling the servo motor from a web server.

 

The library you are looking for should appear in the search results. Click on the library entry. You will see an “Install” button next to the library. Click on it to start the installation process. But in my case I already installed it.

Once the installation is finished, you can close the Library Manager window.

The ESP32 Arduino Servo library should now be installed and ready for use in your Arduino sketches. You can include the library in your code by adding the following line at the beginning of your sketch:

#include <ESP32Servo.h>

With the library installed, you will have access to the necessary functions and features to control servo motors using the ESP32 microcontroller. You can proceed with writing your code to control the servo motor’s position and movement using the library’s functions.

Note: Make sure you have an active internet connection while installing the library from the Arduino Library Manager, as it requires downloading the library files from the internet.

Repeat the same steps for installing the wifi library

Image depicting the installation of the WiFi library for ESP32 web server and servo motor control.



ESP32 Web Server and Servo Motor Examples:

Controlling Servo Motor using ESP32 Web Server textbox and button:

Controlling a servo motor using a ESP32 web server, textbox, and button provides a convenient way to manipulate the servo’s position remotely. This approach allows users to access and control the servo motor from any device with a web browser, such as a computer, smartphone, or tablet. By utilizing a web-based interface, the servo motor can be controlled without the need for a dedicated application or physical interaction with the hardware.

In this example, we will explore how to set up a ESP32 web server that interacts with a servo motor, allowing users to input desired positions through a textbox and trigger the movement using a button. The servo motor, typically used in various applications such as robotics and automation, is a rotary actuator capable of precise angle positioning.

Controlling servo motor using ESP32 web server Code:



Program explanation:

These two lines include the necessary libraries for working with Wi-Fi and servo motors in an ESP32 environment.

This line declares an instance of the Servo class, which will be used to control the servo motor.

These lines define the Wi-Fi network’s SSID (the name of the network) and password. You need to replace the values with the SSID and password of your own Wi-Fi network.

This line sets the port number (TCP port) on which the server will listen for incoming connections. The value 80 is commonly used for HTTP communication.

Here, a WiFiServer object named server is created, which will handle incoming connections on the specified port. A WiFiClient object named client is also declared, which will represent a connected client.

This code is an HTML webpage with embedded JavaScript. It defines a webpage with a title “Servo Control” and a heading “Servo Control”. It includes an input field for entering an angle between 0 and 180, and a button labeled “Set Angle”. When the button is clicked, the JavaScript function setServoAngle() is called.

Inside the function, it retrieves the entered angle from the input field, creates an XMLHttpRequest object (used for making HTTP requests), and sends a GET request to the server endpoint “/setAngle” with the angle as a parameter. This code is typically used in a web application to control a servo motor by sending the desired angle to a server for further processing.




This code sets up an esp32 Arduino sketch with a setup() function. Inside the setup() function, several actions are performed.

First, the serial communication is initialized with a baud rate of 9600 using Serial.begin(9600). This allows communication between the ESP32 and the computer via the serial port.

Next, a Wi-Fi connection is established by calling WiFi.begin(ssid, password), where ssid and password are variables representing the network name and password, respectively.

A while loop is used to wait until the Wi-Fi connection is successfully established. During each iteration of the loop, there is a delay of 1000 milliseconds (1 second), and a message “Connecting to WiFi…” is printed to the serial monitor using Serial.println().

Once the Wi-Fi connection is established (WiFi.status() == WL_CONNECTED), the code proceeds to the next line.

The server.begin() function is called to start a web server.

An attached servo motor is declared using servo.attach(13), where the servo is connected to GPIO pin 13. The servo.write(0) command sets the initial angle of the servo to 0 degrees.

Various status messages are then printed to the serial monitor using Serial.println() to indicate the current state of the system, such as the servo angle being set to 0 degrees, the server starting, and the IP address of the ESP32 Wi-Fi connection.



This code is the loop() function of an ESP32 Arduino sketch. It continuously runs in a loop, performing several actions.

First, it checks if there is a client connected to the web server by calling server.available(). If there is a client, it proceeds to the next lines.

Inside the nested if (client.connected()) statement, it enters a while loop to process the client’s request. It reads the client’s request line by line using client.readStringUntil(‘\r’) and trims any leading or trailing whitespace from the request using request.trim().

If the request starts with “GET /setAngle”, it extracts the angle value from the request parameters and converts it to an integer. If the angle is within the valid range of 0 to 180 degrees, it sets the servo angle to the extracted value and prints a corresponding message to the serial monitor.

If the request starts with “GET / “, indicating a request for the homepage, it sends an HTTP response back to the client with a status of 200 (OK), specifying the content type as text/html, and includes the webPage content in the response body.

After processing the request, the code calls client.stop() to close the connection with the client.

Finally, there is a delay(100) statement which pauses the execution of the loop for 100 milliseconds before starting the next iteration. This delay helps prevent excessive processing and allows for smoother operation of the program.



Controlling Servo Motor using ESP32 Web Server Slider:

Controlling servo motor using ESP32 web server and a slider provides a user-friendly and intuitive way to manipulate the servo’s position remotely. With this setup, users can easily adjust the servo’s angle by simply moving a slider on a web-based interface accessible from any device with a web browser. The ESP32, a powerful microcontroller with built-in Wi-Fi capabilities, acts as both the web server and the servo motor controller, making it an ideal choice for this project.

A servo motor is a rotary actuator commonly used in robotics and automation projects for precise angle positioning. By controlling the servo’s position remotely, users can achieve fine-grained control over the motor’s movement without physical interaction or complex programming.

In this example, we will explore how to build a web server using the ESP32 microcontroller, allowing users to control a servo motor through a slider on a web-based interface. The web server will serve a webpage that includes a slider widget, and as users adjust the slider’s position, the ESP32 will receive the updated value and adjust the servo motor’s angle accordingly.

To accomplish this, we will utilize the WiFi library, which enables the ESP32 to host a web server and handle HTTP requests. By creating a webpage with an interactive slider element, users can easily and intuitively control the servo motor’s position. The ESP32, acting as the server, will listen for the slider value changes and convert them into servo motor control signals.

The combination of an ESP32 microcontroller, a web server, and a slider widget provides a straightforward and accessible solution for controlling a servo motor remotely. Whether you are adjusting a camera angle, controlling a robotic arm, or automating precise movements, this setup offers a convenient way to achieve your goals.

Controlling Servo Motor using ESP32 web server Slider Code:



Code Explanation:

In this code snippet, the ESP32Servo library is included. This library provides the necessary functions to control a servo motor using the ESP32 microcontroller.

An instance of the Servo class, named servo, is declared. This instance will be used to control the servo motor.

The variables ssid and password are defined to store the SSID and password of your Wi-Fi network, respectively. Make sure to replace the placeholder values (“Fawad” and “computer007”) with your actual network credentials.

The variable port is set to 80, which is the default port number for web communication. This is the port number the server will listen on for incoming connections.

A WiFiServer object, named server, is created using the specified port. This object will handle the incoming client connections.

A WiFiClient object, named client, is declared. This object will be used to interact with the connected clients.

With these initializations, the code is ready to establish a connection with the Wi-Fi network and listen for incoming connections on the specified port.

The webPage string in the code snippet represents an HTML page that will be served to clients accessing the ESP32 web server. It starts with the <!DOCTYPE html> declaration, which specifies the document type as HTML. The <html> element serves as the root element of the HTML page. Inside the <head> section, there is a <title> tag that sets the title of the page to “Servo Control”.

The <style> section contains CSS rules that define the appearance of the page. The rules target various elements such as the <body>, <h1>, <form>, <input>, and <output>. These rules specify properties like font-family, background-color, color, text-align, padding, and margin.

Within the <body> section, there is an <h1> tag displaying the heading “Servo Control”. The <form> tag represents a form that contains an <input> element of type “range” with an id of “angle”. This input element allows users to select an angle between 0 and 180 for controlling the servo motor. The onchange attribute is set to the JavaScript function setServoAngle(), which is responsible for updating the angle value display and sending a request to the server to update the servo motor position.

Below the <input> element, there is an <output> tag with an id of “angleValue”. This tag is initially set to 0 and will display the selected angle value.

Overall, the HTML page provides a user interface for controlling the servo motor position using a range input and displays the current angle value. It utilizes JavaScript and XMLHttpRequest to handle user interactions and communicate with the server for updating the servo motor’s position.




The setup() function is responsible for initializing the ESP32 and preparing it for operation. Here is a breakdown of the code within the function:

First, Serial.begin(9600) initializes the serial communication at a baud rate of 9600. This allows the ESP32 to communicate with a computer through the Serial Monitor, enabling debugging and data exchange.

Next, WiFi.begin(ssid, password) initiates a connection to a Wi-Fi network using the provided SSID (network name) and password. The ESP32 attempts to establish a connection, and the code enters a while loop to check the status of the Wi-Fi connection using WiFi.status(). The loop continues until the ESP32 successfully connects to the Wi-Fi network, indicated by the WL_CONNECTED status.

Once the Wi-Fi connection is established, server.begin() initializes the WiFiServer object server on the specified port number, allowing the ESP32 to listen for incoming connections from clients.

The line servo.attach(13) attaches the servo motor to GPIO 13 on the ESP32, enabling the control of the servo motor’s position. The servo.write(0) command sets the initial angle of the servo motor to 0 degrees.

Serial print statements are used to provide feedback and information during the setup process. They display messages such as “Servo angle set to 0 degrees,” “Server started,” and the IP address of the ESP32 obtained from WiFi.localIP().

In summary, the setup() function initializes the serial communication, establishes a Wi-Fi connection, sets up the server for incoming connections, attaches the servo motor to the appropriate GPIO pin, and provides feedback via serial prints. It prepares the ESP32 for servo motor control and sets the initial servo angle to 0 degrees.



First, client = server.available() checks if there is a client connection request received by the server. If a request is detected, the code proceeds to the next steps.

Inside the nested if (client.connected()) condition, the code enters a while loop while (client.available()) to handle the data available from the client. This loop executes as long as there is data available.

The request variable stores the data received from the client, and request.trim() removes any leading or trailing white spaces.

The code checks if the received request starts with “GET /setAngle” using request.startsWith(“GET /setAngle”). If it does, it indicates a request to set the angle of the servo motor.

Next, the code searches for the angle value in the request using request.indexOf(‘?’). If a valid index is found, it extracts the angle value from the request and converts it to an integer using toInt().

If the extracted angle is within the valid range of 0 to 180 degrees, the code sets the servo motor’s angle to the received value using servo.write(angle). It also displays the angle value in the Serial Monitor for debugging purposes.

The code then checks if the received request starts with “GET / ” using request.startsWith(“GET / “). This condition is true when the client requests the root page (“/”) of the server.

Inside this condition, the code sends an HTTP response back to the client with a status code, content type, and an empty line followed by the webPage content. This HTML content is the web page that allows users to control the servo motor angle through a range input.

After handling the client request, client.stop() closes the client connection.

Finally, the delay(100) statement adds a small delay of 100 milliseconds to avoid overwhelming the server with continuous requests and to allow other processes to run smoothly.

In summary, the loop() function continuously listens for incoming client connections, reads and processes their requests. If the request is to set the servo angle, it updates the servo motor position accordingly. If the request is for the root page (“/”), it sends the HTML page for servo control.

 

Related Articles

Leave a Reply

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

Back to top button