ESP32 Web Server Control Servo motor with Arduino IDE

This tutorial is regarding controlling servo motor with ESP32 over a web server using Arduino IDE. You will discover how to control Servo motor with ESP32 and you will also ready to make a simple web server with a slider to control the position of servo motor in both positions. Web server consists of a slider with a position from 0-180. With this slider, a user can control the shaft position. We use the Arduino IDE to program ESP32 dev kit module.

Video demonstration

Prerequisites For This Tutorial 

To follow the concepts of this tutorial, you should have a background knowledge required to grasp concepts.

Components  Required

 We will be using these components for this tutorial:

  • ESP32 DOIT DEVKIT Development board
  • Few jumper wires
  • Servo motor ( you can use any sort of servo motor within the current limit of ESP32)

Interfacing Servo Motor With ESP32

In this section, We will review about basics of servo motor, types of servo motors, pinout and connection layout of servo motor interfacing with ESP32.  In order to understand, interfacing circuit, you first need to understand its working. Let’s start with the basics.

Servo motor is controlled by giving a series of pulses to control pin. Almost all servo’s used for hobbyist projects works on the 50Hz frequency or the time period of control signal should be 20ms. Control signal width defines the position of a shaft that how much it will rotate. Pulse width and position of shaft are directly proportional to each other. They can rotate from 0 to 180 degree depending on pulse width. you can go through following tutorial to know more about PWM and its related terms:

Picture shown below provides more details about it.

ESP32 servo motor position
ESP32 servo motor position source link

You don’t need to worry about working and how to generate this control signal. Because we will use Servo library for ESP32 to provide a control signal. In next section, We will show you how to add Servo library for ESP32.

Pinout

Servo motor pinout esp32

Servo motor consists of three pins:

  • Power pin is of red color.
  • Ground pin is of brown color.
  • Control signal usually has an orange, yellow and white color.
Wire of motor Possible colors of each wire
Vcc pin Red
GND pin Black, or brown
Control Signal / PWM pin  Yellow, orange, or white

Before connecting it with ESP32, we need to make sure how much current is required to operate. For example, different power servo motors are available in market. When you are using small power servo motor like S0009, you can directly connect it with an ESP32 board. Because its current requirement is less than 10ms. We will use S0009 in this tutorial as shown above. You can also connect SG90, SG92R series directly with board. But if you want to use high power servo motor with ESP32, you need to use motor driver IC like UNL2003 between these two.  Also if you want to use multiple Servos with ESP32, you still have to use current driver IC.

Connection diagram

Very simple connection layout is given here.ESP32 servo motor control with web server in Arduino IDE

Above schematic use ESP32 DOIT DEVKIT 30 pin version. But if you are using 36 pin version or any other ESP32 board, you should check its pinout and find GPIO pin 13.

Now, You just make a connection according to this layout on a breadboard. To connect a single servo with ESP32, we will connect according to these connections:

  • Connect Ground Pin of servo with Ground pin of ESP32
  • Power pin >> Vin Pin
  • Control Signal pin >> GPIO 13 of ESP32

you can use any pin of ESP32 as PWM pin because we need to provide PWM signal to control signal pin of servo. In this tutorial, we are using GPIO pin 13 as PWM pin as shown in layout. But you can also use any pin for control signal. But you need to specify the GPIO pin number inside the code which we will discuss in programming section of this guide.

Install Servo Library for ESP32

As mentioned in the last two sections, servo’s are controlled through a series of pulses with variable pulse width. But instead of creating its own code that how to create a series of pulses with variable pulse width, we can use ESP32 servo library. Follow these steps to download and install the library.

  • Follow this link to get ESP32 Servo library for Arduino IDE.
  • After downloading, you will get a .zip file.
  • Use any software to Unzip this downloaded folder.
  • You will get a folder with name ESP32-Arduino-Servo-Library-Master. 
  • Change the name of folder from ESP32-Arduino-Servo-Library-Master to  ESP32_Arduino_Servo_Library.
  • Copy this folder to Arduino library folder. You can find the Arduino library folder inside the Arduino installation folder.
  • Now open your Arduino IDE, library for servo will be there. Now you can use it with ESP32.

Remember, you might have already installed library for servo motor in your Arduino IDE. But that library will not work with your ESP32, because that is for other boards like Arduino Uno, Arduino mega and stm32. Now we can use this library to control position of servo from a web server.

Example code

Upload this code to Arduino IDE, this code rotates the servo for 180 degrees in clockwise direction and for 180 degrees in back direction.  Shaft will move from initial position till 180 degrees and then come back to the same position.

#include <Servo.h>

static const int servoPin = 13;  // defines pin number for PWM

Servo servo1;  // Create object for servo motor

void setup() {
Serial.begin(115200);
servo1.attach(servoPin);  // start the library 
}

void loop() {
for(int posDegrees = 0; posDegrees <= 180; posDegrees++) {
servo1.write(posDegrees);
Serial.println(posDegrees);
delay(20);
}

for(int posDegrees = 180; posDegrees >= 0; posDegrees--) {
servo1.write(posDegrees);
Serial.println(posDegrees);
delay(20);
}
}

Controlling servo with POT example

This sketch controls the position of servo with the help potentiometer.  GPIO32 is used as an analog pin. Voltage across POT is mapped to pulse width position which controls the shaft position.  you can read of ADC of ESP32 in this article.

#include <Servo.h>

static const int servoPin = 13;
static const int potentiometerPin = 32;

Servo servo1;

void setup() {
Serial.begin(115200);
servo1.attach(servoPin);
}

void loop() {
int servoPosition = map(analogRead(potentiometerPin), 0, 4096, 0, 180);
servo1.write(servoPosition);
Serial.println(servoPosition);
delay(20);
}

Now, We will show you an example of controlling servo motor from web server and after that, we will explain working of code and how to make a web server with esp32.

Creating Servo Web server with ESP32

After making the connection diagram and installing library, copy this code to Arduino IDE and upload it to ESP32 DOIT DEVKIT.

/*********
Microcontrollerslab.com
you can get more projects about ESP32
Microcontrollers lab
*********/

#include <WiFi.h> 
#include <Servo.h>

Servo ObjServo; // Make object of Servo motor from Servo library
// Objects are made for every servo motor,we want to control through this library

static const int ServoGPIO = 13; // define the GPIO pin with which servo is connected

// Variables to store network name and password
const char* ssid = "PTCL-BB"; // Enter your network name
const char* password = "5387c614"; //Enter your network password

// Set the server port nunber to deafualt 80
WiFiServer server(80);

// this variable header stores the HTTP requests data
String header;

// These variables used to store slider position 
String valueString = String(0);
int positon1 = 0;
int positon2 = 0;

void setup() 
{
Serial.begin(115200); //define serial commuination with baud rate of 115200
ObjServo.attach(ServoGPIO); // it will attach the ObjServo to ServoGPIO pin which is 13 
Serial.print("Making connection to "); // it will display message on serial monitor
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
// These lines prints the IP address value on serial monitor 
Serial.println("");
Serial.println("WiFi connected.");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
server.begin(); // It will start the servo motor with given position value. 
}

void loop(){
WiFiClient client = server.available(); // Listen for incoming clients

if (client)
{ // If a new client connects,

String header = client.readStringUntil('\r');
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 
// Feel free to change the background-color and font-size attributes to fit your preferences
client.println("<style>body { text-align: center; font-family: \"Trebuchet MS\", Arial; margin-left:auto; margin-right:auto;}");
client.println(".slider { width: 300px; }</style>");
client.println("<script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script>");

// Web Page
client.println("</head><body><h1>ESP32 with Servo</h1>");
client.println("<p>Position: <span id=\"servoPos\"></span></p>"); 
client.println("<input type=\"range\" min=\"0\" max=\"180\" class=\"slider\" id=\"servoSlider\" onchange=\"servo(this.value)\" value=\""+valueString+"\"/>");

client.println("<script>var slider = document.getElementById(\"servoSlider\");");
client.println("var servoP = document.getElementById(\"servoPos\"); servoP.innerHTML = slider.value;");
client.println("slider.oninput = function() { slider.value = this.value; servoP.innerHTML = this.value; }");
client.println("$.ajaxSetup({timeout:1000}); function servo(pos) { ");
client.println("$.get(\"/?value=\" + pos + \"&\"); {Connection: close};}</script>");

client.println("</body></html>"); 

//GET /?value=180& HTTP/1.1
if(header.indexOf("GET /?value=")>=0) 
{
positon1 = header.indexOf('=');
positon2 = header.indexOf('&');
valueString = header.substring(positon1+1, positon2);

//Rotate the servo
ObjServo.write(valueString.toInt());
Serial.println(valueString); 
} 

header = "";
client.stop();
Serial.println("Client disconnected.");
Serial.println("");
}
}
  • Before you upload code, you need to change network credentials and change them with your WiFI name and password.
  • After uploading this code to ESP32 board, open your serial monitor and note down the IP address as shown in picture below: servo motor web server accessing through IP address
  • Copy this IP address and open it with any web browser. you will see this web page in your browser. you will see a slider with position control. ESP32 servo motor Web server slider
  • You can control the position of servo’s shaft with the help of this slider.  ESP32 servo motor control with web server
  • You can move the slide in left or right position to rotate motor position in clockwise and ant-clockwise direction.

Code working

Now we will see how the code works and how to create a web server. you can check this ( create esp32 web server in Arduino ) tutorial for more information on creating a web server with ESP32. Main working of code is given below:

  • It will create a web page with a slider. Any web client can connect to this web page through an IP address we get in the last section.
  • The slider can control the position of shaft between 0 and 180 degrees. A web client can move the slider in left or right position to control shaft position.
  • Web client once opens the web page, they do not need to update the page, again and again, to update position of slider because we use AJAX javascript file to refresh the web page automatically when a user updates the position of slider.
  • Web page sends HTTP requests to ESP32 to update position of a servo motor.

These lines add libraries of the WiFi driver and servo motor.

#include <WiFi.h>   // add library of WiFi for ESP32
#include <Servo.h> // add library of Servo for ESP32

This line makes an object of Servo motor from the Servo library. Objects are made for every servo motor if we want to control multiple servos through this single servo library. We can create upto 12 objects.

Servo ObjServo;  // create object with name ObjServo

This line defines the name of GPIO pin to which we have connected servo motor.

static const int ServoGPIO = 13;  // Pin number to which control signal pin is connected

These variables store network name and password for connecting ESP32 with WiFi network

const char* ssid = "PTCL-BB"; // Enter your network name
const char* password = "5387c614"; //Enter your network password
WiFiServer server(80);// Set the server port nunber to deafualt 80

This variable header stores the HTTP requests data received from a web client.

String header;

These variables store previous and update values of servo position and slider position.

String valueString = String(0);
int positon1 = 0;
int positon2 = 0;

First line defines the baud rate of serial communication and second line attack the GPIO pin with object of servo motor which we created earlier.

Serial.begin(115200); //define serial communication with baud rate of 115200
ObjServo.attach(ServoGPIO); // it will attach the ObjServo to ServoGPIO pin which is 13

This part of the code is used for connecting ESP32 to WiFi router. ESP32 connects to WiFi router and displays the IP address on serial monitor.

Serial.print("Making connection to "); // it will display message on serial monitor
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
// These lines prints the IP address value on serial monitor 
Serial.println("");
Serial.println("WiFi connected.");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
server.begin(); // It will start the servo motor with given position value. 
}

Before explaining code inside the loop function, we will explain HTML part of this code which we have used inside the main function. This HTML part of code is used to create slider and web page layout.

Creating a Web page

Following code is used for HTML page. This web page is responsible for making a range slider and updating web page automatically.  If you are just a beginner with HTML and CSS, you can visit this website to learn the basics of HTML and CSS.

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" href="data:,">
<style>
body {
text-align: center;
font-family: "Trebuchet MS", Arial;
margin-left:auto;
margin-right:auto;
}
.slider {
width: 300px;
}
</style>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></sc
ript>
</head>
<body>
<h1>ESP32 with Servo</h1>
<p>Position: <span id="servoPos"></span></p>
<input type="range" min="0" max="180" class="slider" id="servoSlider"
onchange="servo(this.value)"/>
<script>
var slider = document.getElementById("servoSlider");
var servoP = document.getElementById("servoPos");
servoP.innerHTML = slider.value;
slider.oninput = function() {
slider.value = this.value;
servoP.innerHTML = this.value;
}
$.ajaxSetup({timeout:1000});
function servo(pos) {
$.get("/?value=" + pos + "&");
{Connection: close};
}
</script>
</body>
</html>

Creating a range slider

To create a range slider in HTML, we use <input> and </input> tags.  This line create a range slider with <input> and </input> tags.

<input type="range" min="0" max="180" class="slider" id="servoSlider"
onchange="servo(this.value)"/>
  • The type defines the type of slider because we want to create a range slider, therefore used “range” and define the minimum value of 0 and a maximum value of 180.
  • One change feature calls a javascript function which is explained below.

This is a javascript code which is used to update web page automatically and send HTTP request having values of the slider position. We write javascript functions between <script> </script> tags.  This code updates the web page with slider position value.

var slider = document.getElementById("servoSlider");
var servoP = document.getElementById("servoPos");
servoP.innerHTML = slider.value;
slider.oninput = function() {
slider.value = this.value;
servoP.innerHTML = this.value;
} 
$.ajaxSetup({timeout:1000});
 function servo(pos) {
 $.get("/?value=" + pos + "&");
 {Connection: close};
 }

These lines get the values of slider position from HTTP request data which is stored in header string. ObjServo.write() function rotate the servo motor according to received value of slider position.

if(header.indexOf("GET /?value=")>=0) 
{
positon1 = header.indexOf('=');
positon2 = header.indexOf('&');
valueString = header.substring(positon1+1, positon2);


ObjServo.write(valueString.toInt());
Serial.println(valueString); 
}

In summary, In this tutorial you learned:

  • you learned about serv motor.
  • we explained how to connect servo motor with ESP32
  • How to control servo motor with potentiometer
  • How to control servo motor from a web page using a Slider.

I hope you liked this tutorial, if you enjoyed this tutorial, you surely like to read our past editorials.

Leave a Comment

shares