ESP32
ESP32 Servo Motor Web Server with Arduino IDE
Connecter un servomoteur à l'ESP32
Les servomoteurs ont trois fils : alimentation, masse et signal. L'alimentation est généralement rouge, le GND est noir ou marron et le fil de signal est généralement jaune, orange ou blanc.

|
Wire |
Color |
|
Power |
Red |
|
GND |
Black, or brown |
|
Signal |
Yellow, orange, or white |
Lorsque vous utilisez un petit servo comme le S0009 comme indiqué dans la figure ci-dessous, vous pouvez l'alimenter directement depuis l'ESP32.

Mais si vous utilisez plusieurs servos ou autres types, vous devrez probablement alimenter vos servos à l’aide d’une alimentation externe.

Si vous utilisez un petit servo comme le S0009, vous devez connecter :
- GND -> ESP32 GND pin;
- Power -> ESP32 VIN pin;
- Signal -> GPIO 13 (or any PWM pin).
Remarque : dans ce cas, vous pouvez utiliser n'importe quel GPIO ESP32, car n'importe quel GPIO est capable de produire un signal PWM. Cependant, nous ne recommandons pas d'utiliser les GPIO 9, 10 et 11 connectés au flash SPI intégré et ne sont pas recommandés pour d'autres utilisations.
Schema
Dans nos exemples, nous connecterons le fil de signal au GPIO 13. Vous pouvez donc suivre le schéma suivant pour câbler votre servomoteur.
Comment contrôler un Servo Motor ?
Vous pouvez positionner l'arbre du servo dans différents angles de 0 à 180º. Les servos sont contrôlés à l'aide d'un signal de modulation de largeur d'impulsion (PWM).

Cela signifie que le signal PWM envoyé au moteur déterminera la position de l'arbre. Pour contrôler le moteur, vous pouvez simplement utiliser les capacités PWM de l'ESP32 en envoyant un signal de 50 Hz avec la largeur d'impulsion appropriée. Ou vous pouvez utiliser une bibliothèque pour rendre cette tâche beaucoup plus simple.
Copier le fichier ESP32Servo.zip dans votre répertoire /documents/arduino/librairies
Essayer un exemple
Après avoir installer la librairie redemarrer l'IDE Arduino. Sélectionner ESP32 Dev Module :
#include <ESP32Servo.h>
Servo myservo; // create servo object to control a servo
// 16 servo objects can be created on the ESP32
int pos = 0; // variable to store the servo position
// Recommended PWM GPIO pins on the ESP32 include 2,4,12-19,21-23,25-27,32-33
int servoPin = 27;
void setup() {
// Allow allocation of all timers
ESP32PWM::allocateTimer(0);
ESP32PWM::allocateTimer(1);
ESP32PWM::allocateTimer(2);
ESP32PWM::allocateTimer(3);
myservo.setPeriodHertz(50); // standard 50 hz servo
myservo.attach(servoPin, 1000, 2000); // attaches the servo on pin 18 to the servo object
// using default min/max of 1000us and 2000us
// different servos may require different min/max settings
// for an accurate 0 to 180 sweep
}
void loop() {
for (pos = 0; pos <= 180; pos += 1) { // goes from 0 degrees to 180 degrees
// in steps of 1 degree
myservo.write(pos); // tell servo to go to position in variable 'pos'
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
myservo.write(pos); // tell servo to go to position in variable 'pos'
delay(15); // waits 15ms for the servo to reach the position
}
}
Comprendre le code
Ce croquis fait pivoter le servo de 180 degrés d'un côté et de 180 degrés de l'autre. Voyons voir comment ça fonctionne. Tout d’abord, vous devez inclure la bibliothèque Servo :
#include <Servo.h>
Then, you need to create a servo object. In this case it is called myservo.
Servo myservo;
setup()
Dans setup(), vous initialisez une communication série à des fins de débogage et attachez GPIO 27 à l'objet servo.
void setup() {
myservo.attach(13);
}
loop()
Dans loop(), nous modifions la position de l'arbre du moteur de 0 à 180 degrés, puis de 180 à 0 degrés. Pour définir l'arbre dans une position particulière, il vous suffit d'utiliser la méthode write() dans l'objet servo. Vous passez en argument, un nombre entier avec la position en degrés.
myservo.write(pos);
Tester le programme
Téléchargez le code sur votre ESP32. Après avoir téléchargé le code, vous devriez voir l’arbre du moteur tourner d’un côté puis de l’autre.

Creating the ESP32 Web Server
Maintenant que vous savez comment contrôler un servo avec l'ESP32, créons le serveur Web pour le contrôler (en savoir plus sur la création d'un serveur Web ESP32). Le serveur Web que nous allons construire :
- Contient un curseur de 0 à 180, que vous pouvez régler pour contrôler la position de l'arbre du servo ;
- La valeur actuelle du curseur est automatiquement mise à jour dans la page Web, ainsi que la position de l'arbre, sans qu'il soit nécessaire d'actualiser la page Web. Pour cela, nous utilisons AJAX pour envoyer des requêtes HTTP à l'ESP32 en arrière-plan ;
- L'actualisation de la page Web ne modifie pas la valeur du curseur, ni la position de l'arbre.

Challenge au choix :
1 - ajouter deux boutons pour tourner dans un sens et un pour aller dans l'autre sens
2- corriger le programme pour faire fonctionner l'AJAX
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 retrieve the value parameter in the URL and move the servo motor to the right position.
Code
Now, we need to include the previous HTML text in the sketch and rotate the servo accordingly. This next sketch does precisely that.
Note: as we’ve mentioned previously, you need to have the ESP32 add-on installed in your Arduino IDE. Follow one of the following tutorials to install the ESP32 board in the Arduino IDE, if you haven’t already:
- Windows instructions – ESP32 Board in Arduino IDE
- Mac and Linux instructions – ESP32 Board in Arduino IDE
Copy the following code to your Arduino IDE, but don’t upload it yet. First, we’ll take a quick look on how it works.
/*********
Rui Santos
Complete project details at https://randomnerdtutorials.com
*********/
#include <WiFi.h>
#include <Servo.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 <Servo.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, GPIO 13.
const int servoPin = 13;
Don’t forget that you need to modify the following two lines to include your network credentials.
// Replace with your network credentials const char* ssid = "";
const char* password = "";
Then, create a couple of 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 “Enable” 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’ve 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.
Créé avec HelpNDoc Personal Edition: Produire des livres électroniques facilement

