In this tutorial, you’ll learn how to build a web server with the ESP32 that controls the shaft’s position of a servo motor using a slider. First, we’ll take a quick look at how to control a servo with the ESP32, and then we’ll build the web server.
Updated 13 June, 2024
Parts Required
To follow this tutorial, you need the following parts:
- ESP32 DOIT DEVKIT V1 Board – read ESP32 Development Boards Review and Comparison
- Micro Servo Motor – S0009/S90 or Servo Motor – S0003
- Jumper wires
You can use the preceding links or go directly to MakerAdvisor.com/tools to find all the parts for your projects at the best price!
Connecting the Servo Motor to the ESP32
Servo motors have three wires: power, ground, and signal. The power is usually red, the GND is black or brown, and the signal wire is usually yellow, orange, or white.
Wire | Color |
Power | Red |
GND | Black, or brown |
Signal | Yellow, orange, or white |
When using a small servo like the S0009 as shown in the figure below, you can power it directly from the ESP32.
But if you’re using more than one servo or a different model, you’ll probably need to power up your servos using an external power supply.
If you’re using a small servo like the S0009, you need to connect:
- GND -> ESP32 GND pin;
- Power -> ESP32 VIN pin;
- Signal -> GPIO 13 (or any PWM pin).
Note: in this case, you can use any ESP32 GPIO, because any GPIO can produce a PWM signal. However, we don’t recommend using GPIOs 9, 10, and 11 which are connected to the integrated SPI flash and are not recommended for other uses.
Recommended reading: ESP32 Pinout Reference: Which GPIO pins should you use?
Schematic
In our examples, we’ll connect the signal wire to GPIO 13. So, you can follow the next schematic diagram to wire your servo motor.
(This schematic uses the ESP32 DEVKIT V1 module version with 36 GPIOs – if you’re using another model, please check the pinout for the board you’re using.)
How to Control a Servo Motor?
You can position the servo’s shaft at different angles from 0 to 180º. Servos are controlled using a pulse width modulation (PWM) signal. The duty cycle of the PWM signal sent to the motor will determine the shaft’s position.
To control the motor you can simply use the PWM capabilities of the ESP32 by sending a 50Hz signal with the appropriate pulse width. Or you can use a library to make this task much simpler.
Preparing the Arduino IDE
Before proceeding make sure you have installed the ESP32 boards in your Arduino IDE and the ServoESP32 Library.
ESP32 with Arduino IDE
We’ll program the ESP32 using Arduino IDE. So, make sure you have the ESP32 add-on installed. Follow the next tutorial if you haven’t already:
Alternatively, you may also want to program the ESP32 using VS Code and the platformIO extension:
Installing the ESP32Servo Library
The ESP32Servo Library makes it easier to control a servo motor with your ESP32 using the Arduino IDE. Follow the next steps to install the library in the Arduino IDE:
- Go to Sketch > Include Library > Manage Libraries…
- Search for ESP32Servo.
- Install the library.
Testing an Example
After installing the library, go to your Arduino IDE and copy the following code.
/*********
Rui Santos & Sara Santos - Random Nerd Tutorials
Complete project details at https://RandomNerdTutorials.com/esp32-servo-motor-web-server-arduino-ide/
Based on the ESP32Servo Sweep Example
*********/
#include <ESP32Servo.h>
static const int servoPin = 13;
Servo servo1;
void setup() {
Serial.begin(115200);
servo1.attach(servoPin);
}
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);
}
}
Understanding the code
This sketch rotates the servo 180 degrees to one side, and 180 degrees to the other. Let’s see how it works.
First, you need to include the Servo library:
#include <ESP32Servo.h>
Define the pin connected to the servo data pin. In this case, we’re connecting to GPIO 13, but you can use any other suitable pins.
static const int servoPin = 13;
Learn more about the ESP32 GPIOs: ESP32 Pinout Reference: Which GPIO pins should you use?
Then, you need to create a Servo object. In this case, it is called servo1.
Servo servo1;
setup()
In the setup(), you initialize a serial communication for debugging purposes and attach GPIO 13 to the servo object.
void setup() {
Serial.begin(115200);
servo1.attach(servoPin);
}
loop()
In the loop(), we change the motor’s shaft position from 0 to 180 degrees, and then from 180 to 0 degrees. To set the shaft to a particular position, you just need to use the write() method on the Servo object. You pass as an argument, an integer number with the position in degrees.
myservo.write(pos);
Testing the Sketch
Upload the code to your ESP32. After uploading the code, you should see the motor’s shaft rotating to one side and then, to the other.
Creating the ESP32 Web Server
Now that you know how to control a servo with the ESP32, let’s create the web server to control it. The web server we’ll build:
- It contains a slider from 0 to 180, that you can adjust to control the servo’s shaft position;
- The current slider value is automatically updated on the web page without the need to refresh it. For this, we use AJAX to send HTTP requests to the ESP32 in the background;
- Refreshing the web page doesn’t change the slider value, or the shaft position.
You may also like: Build Web Servers with ESP32 and ESP8266 eBook.
Creating the HTML Page
Let’s start by taking a look at the HTML text the ESP32 needs to send to your browser.
<!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"></script>
</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 Slider
The HTML page for this project involves creating a slider. To create a slider in HTML you use the <input> tag. The <input> tag specifies a field where the user can enter data.
There are a wide variety of input types. To define a slider, use the “type” attribute with the “range” value. In a slider, you also need to define the minimum and the maximum range using the “min” and “max” attributes.
<input type="range" min="0" max="180" class="slider" id="servoSlider" onchange="servo(this.value)"/>
You also need to define other attributes like:
- the class to style the slider
- the id to update the current position displayed on the web page
- And finally, the onchange attribute to call the servo function to send an HTTP request to the ESP32 when the slider moves.
Adding JavaScript to the HTML File
Next, you need to add some JavaScript code to your HTML file using the <script> and </script> tags. This snippet of the code updates the web page with the current slider position:
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;
}
And the next lines make an HTTP GET request on the ESP IP address in this specific URL path /?value=[SLIDER_POSITION]&.
$.ajaxSetup({timeout:1000});
function servo(pos) {
$.get("/?value=" + pos + "&");
}
For example, when the slider is at 0, you make an HTTP GET request on the following URL:
http://192.168.1.135/?value=0&
And when the slider is at 180 degrees, you’ll have something as follows:
http://192.168.1.135/?value=180&
This way, when the ESP32 receives the GET request, it can get the value parameter in the URL and move the servo motor accordingly.
Code
Now, we need to include the previous HTML text in the sketch and rotate the servo accordingly. This next sketch does precisely that.
Copy the following code to your Arduino IDE, but don’t upload it yet. First, we’ll take a quick look at how it works.
/*********
Rui Santos & Sara Santos - Random Nerd Tutorials
Complete project details at https://RandomNerdTutorials.com/esp32-servo-motor-web-server-arduino-ide/
*********/
#include <WiFi.h>
#include <ESP32Servo.h>
Servo myservo; // create servo object to control a servo
// twelve servo objects can be created on most boards
// GPIO the servo is attached to
static const int servoPin = 13;
// Replace with your network credentials
const char* ssid = "REPLACE_WITH_YOUR_SSID";
const char* password = "REPLACE_WITH_YOUR_PASSWORD";
// Set web server port number to 80
WiFiServer server(80);
// Variable to store the HTTP request
String header;
// Decode HTTP GET value
String valueString = String(5);
int pos1 = 0;
int pos2 = 0;
// Current time
unsigned long currentTime = millis();
// Previous time
unsigned long previousTime = 0;
// Define timeout time in milliseconds (example: 2000ms = 2s)
const long timeoutTime = 2000;
void setup() {
Serial.begin(115200);
myservo.attach(servoPin); // attaches the servo on the servoPin to the servo object
// Connect to Wi-Fi network with SSID and password
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
// Print local IP address and start web server
Serial.println("");
Serial.println("WiFi connected.");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
server.begin();
}
void loop(){
WiFiClient client = server.available(); // Listen for incoming clients
if (client) { // If a new client connects,
currentTime = millis();
previousTime = currentTime;
Serial.println("New Client."); // print a message out in the serial port
String currentLine = ""; // make a String to hold incoming data from the client
while (client.connected() && currentTime - previousTime <= timeoutTime) { // loop while the client's connected
currentTime = millis();
if (client.available()) { // if there's bytes to read from the client,
char c = client.read(); // read a byte, then
Serial.write(c); // print it out the serial monitor
header += c;
if (c == '\n') { // if the byte is a newline character
// if the current line is blank, you got two newline characters in a row.
// that's the end of the client HTTP request, so send a response:
if (currentLine.length() == 0) {
// HTTP headers always start with a response code (e.g. HTTP/1.1 200 OK)
// and a content-type so the client knows what's coming, then a blank line:
client.println("HTTP/1.1 200 OK");
client.println("Content-type:text/html");
client.println("Connection: close");
client.println();
// Display the HTML web page
client.println("<!DOCTYPE html><html>");
client.println("<head><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">");
client.println("<link rel=\"icon\" href=\"data:,\">");
// CSS to style the on/off buttons
// 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) {
pos1 = header.indexOf('=');
pos2 = header.indexOf('&');
valueString = header.substring(pos1+1, pos2);
//Rotate the servo
myservo.write(valueString.toInt());
Serial.println(valueString);
}
// The HTTP response ends with another blank line
client.println();
// Break out of the while loop
break;
} else { // if you got a newline, then clear currentLine
currentLine = "";
}
} else if (c != '\r') { // if you got anything else but a carriage return character,
currentLine += c; // add it to the end of the currentLine
}
}
}
// Clear the header variable
header = "";
// Close the connection
client.stop();
Serial.println("Client disconnected.");
Serial.println("");
}
}
How the Code Works
First, we include the Servo library and create a Servo object called myservo.
#include <ESP32Servo.h>
Servo myservo; // create servo object to control a servo
We also create a variable to hold the GPIO number the servo is connected to. In this case, GPIO13.
const int servoPin = 13;
Don’t forget that you need to modify the following two lines to include your network credentials.
const char* ssid = "REPLACE_WITH_YOUR_SSID";
const char* password = "REPLACE_WITH_YOUR_PASSWORD";
Then, create variables that will be used to extract the slider position from the HTTP request.
// Decode HTTP GET value
String valueString = String(5);
int pos1 = 0;
int pos2 = 0;
setup()
In the setup(), you need to attach the servo to the GPIO it is connected to, with myservo.attach().
myservo.attach(servoPin); // attaches the servo on the servoPin to the servo object
loop()
The first part of the loop() creates the web server and sends the HTML text to display the web page. We use the same method we’ve used in this web server project.
The following part of the code retrieves the slider value from the HTTP request.
//GET /?value=180& HTTP/1.1 if(header.indexOf("GET /?value=")>=0) { pos1 = header.indexOf('='); pos2 = header.indexOf('&'); valueString = header.substring(pos1+1, pos2);
When you move the slider, you make an HTTP request on the following URL, that contains the slider position between the = and & signs.
http://your-esp-ip-address/?value=[SLIDER_POSITION]&
The slider position value is saved in the valueString variable.
Then, we set the servo to that specific position using myservo.write() with the valueString variable as an argument. The valueString variable is a string, so we need to use the toInt() method to convert it into an integer number – the data type accepted by the write() method.
myservo.write(valueString.toInt());
Testing the Web Server
Now you can upload the code to your ESP32 – make sure you have the right board and COM port selected. Also don’t forget to modify the code to include your network credentials.
After uploading the code, open the Serial Monitor at a baud rate of 115200. Press the ESP32 EN/RST button to restart the board, and copy the ESP32 IP address that shows up on the Serial Monitor.
Open your browser, paste the ESP IP address, and you should see the web page you created previously. Move the slider to control the servo motor.
In the Serial Monitor, you can also see the HTTP requests you’re sending to the ESP32 when you move the slider.
Experiment with your web server for a while to see if it’s working properly.
Watch the Video Tutorial and Project Demo
This guide is available in video format (watch below) and in written format (continue reading).
Wrapping Up
In summary, in this tutorial, you’ve learned how to control a servo motor with the ESP32 and how to create a web server with a slider to control its position.
This is just an example of how to control a servo motor. Instead of a slider, you can use a text input field, several buttons with predefined angles, or any other suitable input fields.
This is an excerpt from our course: Learn ESP32 with Arduino IDE. If you like ESP32 and want to learn more about it, we recommend enrolling in Learn ESP32 with Arduino IDE course.
We have tutorials on how to interface other motors with the ESP32:
- ESP32 with DC Motor and L298N Motor Driver – Control Speed and Direction
- ESP32 with Stepper Motor (28BYJ-48 and ULN2003 Motor Driver)
- ESP32 Web Server: Control Stepper Motor (HTML Form)
- ESP32 Web Server: Control Stepper Motor (WebSocket)
Learn more about the ESP32 and about building web servers with our resources:
- Learn ESP32 with Arduino IDE (eBook)
- Build Web Servers with ESP32 and ESP8266 (eBook)
- Free ESP32 Projects and Tutorials…
We hope you’ve found this tutorial useful.
Thanks for reading.
GOOD PL. SEND MORE ARTICALS
Help me.
I can not control several servos.
please tell me.
I don’t have any tutorials on controlling multiple servos…
You have any idea about controlling multiple servos and thnx
It’s possible, but I don’t have any tutorials on that exact subject at the moment.
I am trying to do the same project but with an Arduino Uno WiFi REV2, would it still work, if so, what code do I need to change?
Cool!
I’ve expanded the program to run two servos, so that I can control a tilt/pan for a camera. Next, I’ll add the shutter release button.
Great! I’m glad you’ve found this tutorial useful! 🙂
exactly what i’ll be working on if you don’t mind would you share your code. It would save me and
probably a lot of others a lot of time
Cool! Exactly what I’m looking for Alan. Woud you please share your code. I’m keenly intrested.
Secondly may I ask for the mechanics you have used.
Thank you!
Hi Alan,
if you don’t mind would you share your code with me too?
Thanks a lot!
Regards,
Antonio
Hi Alan, could you pass me the code?
Can you share the code, I will like to understand it for school project
could you share with me
Hey, I saw your comment on using the esp32 to control multiple servos via the web based on the Rui Santos code. He mentions you can add up to 12 servos, but doesn’t provide instruction or code on how to control more than 1.
Would you mind sharing your code with me?
Many Thanks,
-Thomas
thank u for this , u are great
Hi
Can you tell how did you manage to get that simple servo example working?
As i try it with my Wemos ESP32 OLED board, it says that
#error “This library only supports boards with an AVR, SAM, SAMD, NRF52 or STM32F4 processor.”
and when i look the examples, the simple servo appears into INCOMPATIBLE folder.
I appreciate if you could help me out.
I am developing a BLE temperature tag to control my servo so that it opens a vent of my room according to the outside temp.
I will be using Ruuvi tags.
Thanks,
Jussi
Hi Jussi.
The example we’re using worked just fine when we tested.
Did you installed the right library? The ESP32-Arduino-Servo-Library?
Hello Sara and Rui,
I too am receiving this same error message. I have downloaded using the link provided and renamed the folder but no joy. I have tried this now on two different Wemos d1 mini ESP32 WRoom boards and on an ESP32 Dev Kit. All give the same error message. I have even loaded the Arduino IDE on newly formatted Win10 machine and installed the esp32 addon to the arduino IDE then downloaded the servo library into that and still get the same error.
Any thoughts would be greatly appreciated.
Brian
Hi Brian.
Please note that we’re using this library: https://github.com/RoboticsBrno/ESP32-Arduino-Servo-Library
It may conflict with the Arduino Servo library.
So, remove the arduino servo library out of the libraries folder, and the issue should be resolved.
See my answer here: https://rntlab.com/question/unit-9-esp32-control-servo-motor-library-problem/
Regards,
Sara
If the user puts the library in as #include <ESP32Servo.h> all will work without deleting any other servo libraries
how i change slider by button OPEN = 180° CLOSE = 0° thx
Hi Francisco.
Instead of the slider, you need to create two buttons on the HTML page: the OPEN and the CLOSE button.
We have a tutorial that creates two buttons with the ESP32 to turn on an LED:
https://randomnerdtutorials.com/esp32-web-server-arduino-ide/
Then, you just need to change what happens when a button is pressed.
Instead of lighting up the LED, copy the code that turns the motor 0º or 180º.
I hope this helps.
Regards,
Sara 🙂
Hi, Sara Santos.
I do not understand html and it’s hard for me to know that I have to replace
Excellent tutorial, thanks for all the information, please can you tell me, what I have to do to control step motors, using the same principle of this tutorial. Thank you
Hi Victor.
At the moment, I don’t have any tutorial about that subject. I’ll prepare an article about that soon.
Regards,
Sara 🙂
Hello, great tutorial. You shoul add that if the chip you will use is the ESP8266, then you have to use the #include instead of #include .
Anyway your tutorials are the best, thank you.
Yes.
Thank you Javier!
🙂
I can control many of them from difference port but not work separately, and i can’t even add another slide in webpage for other servo
how do i control a 7.4v servo with the esp32 ? i dont know how to connect it to an external powewr supply
Hi.
You should connect your external power supply to the servo power pin.
Then, the GND of the servo should connect to the ESP32 GND and to the external power supply GND.
Before wiring everything, please check all the connections and datasheet of your servo motor.
Regards,
Sara
Is there a quick explanation/separate tutorial explaining how this same project could be done but by uploading the html file via SPIFFS? I’ve tried going through the steps from a different tutorial about SPIFFS and deleting the “display html page” client.println lines from the ino file, but i cannot get it to work
Hi Winston.
We have a tutorial about that. It uses SPIFFS and the asynchronous web server library. I’m not sure if you want to stick with this style of web server, or if you didn’t mind using the asynchronous web server:
https://randomnerdtutorials.com/esp32-web-server-spiffs-spi-flash-file-system/
We have another tutorial that gets the HTML file via SD card and creates a web server using the same style of this tutorial. You may find something useful on the code of that project:
https://randomnerdtutorials.com/build-an-all-in-one-esp32-weather-station-shield/
I hope this helps.
Regards,
Sara
Hi Rui,
thank you for this informative and well dokumented tutorial! It works out of the box! Now, after successfull building my first web-server-ESP based application I’m looking for more. I like to build a pan and tild web-cam stand. May be you can help?
Thank you again
Hi.
Thank you for following our tutorials.
Unfortunately, we don’t have any tutorial for what you are looking for.
But you just need to create another servo object, and another servo slider to control a second servo and control the pan and tilt cam.
Regards,
Sara
Might be a dumb question but…can this be controlled from anywhere or do you have to be on the same local network? If so this could be used as a great way to dispense treats for pets away from home 🙂
Hi Steve.
This example is only accessible on your local network.
Regards,
Sara
Hi,
You can use it from outside your home. Just configure your Router in section PORT FORWARDING.
Richard
Heeeeelp please, I am trying to connect an MG995 to my ESP32, I upload the code and it does not do what it should do and I followed all the steps
Hi.
With those details, it is very difficult to understand what can be wrong.
That servo motor probably needs an external power supply.
Regards,
Sara
Hello,
Thank you for all the information.
Im stuck with a problem . When uploading the code in Arduino it shows an error “Fatal error: waiting for packet content”.
I can only fully upload the code succsefully if the ESP32 doesnt have any signal wire connected.
Do you know why?
Thank you!
Hi.
What do you mean by “doesnt have any signal wire connected”.
Read this tutorial and see if it helps: https://randomnerdtutorials.com/solved-failed-to-connect-to-esp32-timed-out-waiting-for-packet-header/
Regards,
Sara
There is an initial light when it is at 0 and not maximum light at 180 is it because of the servo library. How can I have a 0% PWM and 100% PWM
Hi James.
What do you mean? I think I didn’t understand your question.
You can read our guide about PWM with the ESP32 here:https://randomnerdtutorials.com/esp32-pwm-arduino-ide/
I hope this helps.
Regards,
Sara
Hi! I don’t get how the html page is linked with the webserver code in Arduino
could you help me with that!?
Take a look at the second sketch.
Everything is explained in detail in the article.
Regards,
Sara
I have everything working with a 12v stepper motor (external 9v supply).
However, I would like to change the min and max range. I can do this by simply changing the values in the input code but I would like to be able to put variables instead.
For example: String leftMAX = -16; String rightMAX = 16.
This works okay:
client.println(“”);
But this doesn’t work:
client.println(“”);
I’m using this to limit the closing of vertical window blinds.
The code didn’t appear in my comment.
Maybe this will:
This works:
‘min=\”-16\” max=\”16\” ‘
This doesn’t:
‘ min=\leftMAX max=\rightMAX’
If the code doesn’t appear again then this is the problem:
I cannot replace the string in min or max with a String variable.
Hope you understand.
GOT IT! After noticing that you used String valuestring = String(0);
I used:
int MAXright = 16;
int MAXleft = -16;
String rightMAX = String(rightMAX );
String leftMAX = String(leftMAX );
This works perfectly.
This way I can adjust the maximum limits of the blinds by changing MAXright and MAXleft and storing them in EPROM.
Hello,
in a comment above I have read that I have to replace the standard servo -library with yours through deleting.
Take a moment take a few deep breaths and think about it…..
You are offering a tutorial for newbees and make them fiddling deep inside the arduino-IDE????
In my opinion this is a nerdy awful style. Does the ESP32 REALLY need its own servo-library?
If the ESP-board really needs it to get it working you should take the effor that the includename should DIFFER from the standard servo-library-name.
What is so hard about using a different filename?
Your tutorials should be foolproof as possible.
So I renamed the servo.h to ESP32servo.h.
I have done copy&paste with the raw code
from https://raw.githubusercontent.com/RuiSantosdotme/ESP32-Course/master/code/Servo/WiFi_Web_Server_Servo/WiFi_Web_Server_Servo.ino
into the Arduino-IDE. The sourcecode compiles and is beeing uploaded into the ESP32-board. The code starts to work and on the serial monitor I get this output.
I can connect with my webbrowser to the shown IP-adress and get the slider.
I can move the slider but I get no serial-output about the new position.
This is the serial output:
22:42:52.634 -> Connecting to WLANBuero
22:42:53.217 -> …………..
22:42:59.720 -> WiFi connected.
22:42:59.720 -> IP address:
22:42:59.720 -> 192.168.178.43
22:43:09.148 -> New Client.
22:43:09.148 -> GET / HTTP/1.1
22:43:09.148 -> Host: 192.168.178.43
22:43:09.148 -> Connection: keep-alive
22:43:09.148 -> Cache-Control: max-age=0
22:43:09.148 -> Upgrade-Insecure-Requests: 1
22:43:09.148 -> User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.137 Safari/537.36 Vivaldi/2.7.1628.33
22:43:09.182 -> DNT: 1
22:43:09.182 -> Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,/;q=0.8,application/signed-exchange;v=b3
22:43:09.182 -> Accept-Encoding: gzip, deflate
22:43:09.182 -> Accept-Language: de-DE,de;q=0.9,en-US;q=0.8,en;q=0.7
22:43:09.218 ->
22:43:09.218 -> Client disconnected.
22:43:09.218 ->
22:43:09.218 -> New Client.
If I understand right the connection gets immediatly closed. So as the code was inserted by a copy & paste, does compile code starts to work
What is wrong?
best regards
Stefan
Hi Stefan.
Follow the suggestion in this discussion, it should solve your problem: https://rntlab.com/question/solved-esp32-web-server-drops-connection-crashes/
Regards,
Sara
Hi everyone,
First of all, great project, I love the idea of controlling devices from a web page.
I am trying to adapt the project to a relay, but It doesn’t seem to turn off, It is always on, so the current is always passing…
I tried with a led, and it works.
Have you got an idea of what sould I change?
Thank tou very much, and keep making!
Hi Thomas.
To control a relay, we recommend following this tutorial: https://randomnerdtutorials.com/esp32-relay-module-ac-web-server/
Regards,
Sara
Rui Santos thanks for this tutorial & Sara Santos I LUV U !
Hello Rui / Sara
I see your demo wants internet connectivity :
<
script src=”https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js”>
What changes could I make for this app to work in AP (Access Point) mode with no web access ?.
Thanks.
Have you find any solution for that yet?
Hello Rui and Sara – firstly, thanks for your inspirational videos and tutorials. You see to use 2 techniques for your web server apps – either as you have in this tutorial with the web text inside the main loop OR using the AsyncTP and ESPASyncWebServer route like you have on others. When should you use which one?
thanks a lot
Hi.
It is better to use the ESPAsyncWebServer library, because it creates an asynchronous web server.
This means that the ESP32 can do other tasks and still have the ability to handle the web server.
In the other technique, the ESP32 is in a loop constantly checking if there is a new request from a client. It is more difficult to add other tasks and still be able to handle the web server.
All our recent projects use the Asynchronous Web server.
Regards,
Sara
Thanks – thats great! I just came across “web sockets”. Do you guys plan to use these at all – (I don’t know what they are or if they work better)
Hi.
Yes, we plan to start publishing some tutorials about that.
Websockets work better 🙂
And can be implemented using the AsyncWebServer library.
Regards,
Sara
Hi Sara,
Thank you again for the nice tutorial. I works on my ESP Wifi and very happy with your code.
Any chance if you can help me to add a Button functions-
for example Button click to servo pos 10deg and few more set buttons in your code.
Cheers.
Sam
Hi
It works only if you have internet connection. How would you set it up if just on ap without internet?
Thanks
Hi.
You can set the ESP32 as an access point instead of a station: https://randomnerdtutorials.com/esp32-access-point-ap-web-server/
Regards,
Sara
https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js
It is not working in Access point mode due to above script.
is there anybody have any alternative solution to work a servo in access point mode with slide bar control (without internet)?
@RuiSantosdotme
#RuiSantosdotme
Hi.
You can try to use websocket instead to control the motors: https://randomnerdtutorials.com/esp32-web-server-websocket-sliders/
Regards,
Sara
Hi.
I wanted to control a DC motor and a servo motor together using ESP32 however I am unable to do this. Either the dc motor will move with full speed and ignoring the dutycycle value while the servo won’t move at all, OR the servo will move but the DC motor won’t and will keep vibrating. This will happen depending on where I attach the servo in my code. If you can help me I would really appreciate it. Thanks in advanced
Hi.
Make sure you’re using different PWM channels for each motor.
Try with different channels. For example, use channel 0 and channel 4.
Regards,
Sara
Dear Rui and Sarah, thank you so much for your work really help to do a lot of useful things.
I liked your slider in this example but I would like the value entered by it to change not at the end of the movement of the slider, but during movement. That is in real time.
Of course, I do not ask you to rewrite the program for me. I will be glad to have a hint or idea on how to do this, if it is of course possible at all.
Most sincerely,
George
Hi.
Use “oninput” instead of “onchange”.
Regards,
Sara
Hello it sems like my servo, a SG90 model goes only half of its way. So its not doing 0-180°, it makes 45-135°. What could be wrong?
thanks
Hi.
How are you powering your motor?
Regards,
Sara
via the yp-05 usb adapter, it is set to 5v and from there i connect the servo, like in the picture here
You may need to power your servo motor using an external power supply.
Regards,
Sara
but in the picture it is not external why is it working for you!
Your USB ports might not provide enough power.
Regards,
Sara
they adapter i meant
Thanks for the tutorial. To control multiple motors, do i need to create a html id for each and copy paste javascript function for each with their respective id. Thank you
Hi.
Yes. That’s correct!
Regards,
Sara
Hi Sara,
I need some help to add few button to get the servo to move to a specific
pos Forward ++ or Back — and a fix button for example 90 and 180deg, can you help with what to add in your code above. Slider works perfectly. I just need the some additional. thanks.
Hi can this code be modified to be used in an Async Webserver? thank you
Hi.
You can use this tutorial instead: https://randomnerdtutorials.com/esp32-web-server-slider-pwm/
And modify to control a servo motor.
Regards,
Sara
Ya I saw it already after i researched further and looking at it at the moment already, it’s exactly what i needed. Thank you very much
Hi,
How can I control the Servo Speed in this code?
you get your answer?
If so, can you share with me?
Unfortunately not.
Hi
Thank you for the great tutorial. I’ve altered the code slightly to use 2 servos, but am having trouble getting the response from my 2nd slider to the Arduino.
May I please email you the code to have a quick look? PLEASE?
I would like to use this project but to control the servos using PCA9685 – 16-channel 12-bit PWM I2C servo driver – Adafruit 815. How can it be done?
Hello everyone,
i got this example running on an ESP8266 (D1mini) with a few changes. I work with both Arduino and EPSs and i hate name conflicts at libraries. That’s why i was looking for an alternative for the servo control and came across the “MobaTools” by MicroBahner. This is an interesting multi-purpose library, which can also solve one or the other previous questions.
#include <ESP8266WiFi.h>
#include <MobaTools.h>
MoToServo myservo; // create servo object to control a servo
The customized sketch runs flawlessly
Regards
Hi.
Thanks for sharing this solution.
Regards,
Sara
Hi!
I am using a servo with external power supply.
I connected the ground of the external power supply to the gnd pin
and connected the signal of the servo to pin 13.
I already tested the servo with the servo example in arduino ide and it works.
In this project when i move the slider the servo does not move.
Anyone knows what could be the problem. I amd using the servo DSS-M155 by the way.
Thanks in advance
ok tutorial is awesome, thanks… but i would like to use buttons instead of a slider… so one button would be open for example and move servo to 100 degrees and another button would say close and move servo back to 0 degrees. on the webpage instead of the slider on the page. just learning and trying to figure this button thing instead of the slider. any ideas? thanks again for the tutorial
Hi.
Take a look at other web server examples we have using buttons.
Then, you just need to insert the commands to actually move the motors (instead of turning on and off LEDs).
You can use this tutorial as a starting point: https://randomnerdtutorials.com/esp32-web-server-arduino-ide/
I hope this helps.
Regards,
Sara
Hello folks,
I would suggest a easy way to accurated control servo without any library.
Since the period duration vary according to the servo used, we need to have a way to calibrate the duration for minimum (0 degree) and maximum (180 degree).
Follow the code:
// microseconds min for 0 degree, max for 180 degree and the difference between them
// values for min and max should be calibrated according to the servo used
float xmin = 420.0, xmax = 2390.0, dif = xmax – xmin;
int pos=0;
void setup()
{
ledcSetup(0, 50, 16);
ledcAttachPin(13, 0);
}
void loop()
{
// in steps of 1 degree
for (pos = 0; pos <= 180; pos += 1) { // goes from 0 degrees to 180 degrees
// tell servo to go to position in variable ‘pos’
ledcWrite(0, int((float(pos) / 180.0 * dif + xmin) / 20000.0 * 65535.0));
delay(15); // waits 15ms for the servo to reach the position
}
for (pos = 180; pos >= 0; pos -= 1) { // goes from 180 degrees to 0 degrees
// tell servo to go to position in variable ‘pos’
ledcWrite(0, int((float(pos) / 180.0 * dif + xmin) / 20000.0 * 65535.0));
delay(15); // waits 15ms for the servo to reach the position
}
}
Hi guys,
I have very strange issue. Just did Fresh install of Arduinio IDE on my Macbook, imported library ServoESP32 (followed exact instructions), selected board (WROOM or even tried others, such as ESP32 DOIT DEVKIT V1 Board ), pressed Verify and got bellow error.
Web editor gives me same issue.
Any ideas what could I possibly do wrong?
In file included from /private/var/folders/kd/pyxkmv7j1qv3pyj7m49v1krc0000gn/T/.arduinoIDE-unsaved202385-95025-1wy3715.runif/01-SimpleServo/01-SimpleServo.ino:1:
/Users/roko/Documents/Arduino/libraries/ESP32_Arduino_Servo_Library/src/Servo.h:68:81: error: call to non-‘constexpr’ function ‘const _Tp& std::min(const _Tp&, const _Tp&) [with _Tp = int]’
static const int TIMER_RESOLUTION = std::min(16, SOC_LEDC_TIMER_BIT_WIDE_NUM);
^
/Users/roko/Documents/Arduino/libraries/ESP32_Arduino_Servo_Library/src/Servo.h: In member function ‘T ServoTemplate::mapTemplate(T, T, T, T, T) const’:
/Users/roko/Documents/Arduino/libraries/ESP32_Arduino_Servo_Library/src/Servo.h:256:28: error: ‘is_floating_point_v’ is not a member of ‘std’
if constexpr (std::is_floating_point_v) {
^~~~~~~~~~~~~~~~~~~
/Users/roko/Documents/Arduino/libraries/ESP32_Arduino_Servo_Library/src/Servo.h:256:28: note: suggested alternative: ‘is_floating_point’
if constexpr (std::is_floating_point_v) {
^~~~~~~~~~~~~~~~~~~
is_floating_point
/Users/roko/Documents/Arduino/libraries/ESP32_Arduino_Servo_Library/src/Servo.h:256:49: error: expected primary-expression before ‘>’ token
if constexpr (std::is_floating_point_v) {
^
/Users/roko/Documents/Arduino/libraries/ESP32_Arduino_Servo_Library/src/Servo.h:256:50: error: expected primary-expression before ‘)’ token
if constexpr (std::is_floating_point_v) {
^
Multiple libraries were found for “Servo.h”
Used: /Users/roko/Documents/Arduino/libraries/ESP32_Arduino_Servo_Library
Not used: /Users/roko/Library/Arduino15/libraries/Servo
Not used: /Users/roko/Documents/Arduino/libraries/ServoESP32
exit status 1
Compilation error: exit status 1
I have same error: are you using Arduino IDE 2.2.1?
I have a project based on this tutorial and it work fine using IDE 1.8.19
Once updated to new version this error appear.
Can anyone help us to solve?
Hi, I also got a similar error. I tried one by one the available library versions, Alhamdulillah the error disappeared if I used version 1.0.3.
you can use that version now. Hope to hear good news from you.
Great website with amazing explanations 👍👍
Hi,
what I did to solve is replace
if constexpr (std::is_floating_point_v) {
to
if constexpr (0) {
and
static const int TIMER_RESOLUTION = std::min(16, SOC_LEDC_TIMER_BIT_WIDE_NUM);
to
static const int TIMER_RESOLUTION = 14;
That solved the issue for me
Another good tutorial Thanks! With a few basic changes I was able to adapt this to the ESP8266. Thanks again Sara & Rui!
1 Change the library to #include <ESP8266WiFi.h>
2 Change the attach method from myservo.attach(servoPin); to myservo.attach(servoPin,500,2400);
3. Change the static const int servoPin = (*); * = What ever pin you’re using on the ESP8266
can i control on servo by bluetooth?
It just worked~~ thank you.
You may face compilation errors with the latest ESP32Servo library. Please downgrade to an older revision. The same goes for the ESP32 board definitions. Version 3.0 has many changes that may not be working for you.
Is it there any way to control servo speed?
Very good tutorial, this was my first build and your process made it easy. One item I want to change is replace the website scroll bar with a switch/button something that causes the servo to perform a full range of motion from it’s set position 160 degrees and back to set position. But my coding/html skills are too basic to get there yet. Is there a similar project to this?