Esp32 servo library

Esp32 servo library DEFAULT

Unit 9 – esp32 Control Servo Motor : Library problem

Hi
I am having a problem while uploading using the servo library specified in the class instructions:
Arduino: 1.8.10 (Windows 10), Board: “DOIT ESP32 DEVKIT V1, 80MHz, 921600, None”
WARNING: library Servo claims to run on avr, megaavr, sam, samd, nrf52, stm32f4 architecture(s) and may be incompatible with your current board which runs on esp32 architecture(s).
In file included from C:\Users\jack\Documents\ELECTRONICS\esp32\Code\ServoSweep\ServoSweep.ino:7:0:
C:\Program Files (x86)\Arduino\libraries\Servo\src/Servo.h:75:2: error: #error “This library only supports boards with an AVR, SAM, SAMD, NRF52 or STM32F4 processor.”
#error “This library only supports boards with an AVR, SAM, SAMD, NRF52 or STM32F4 processor.”
Multiple libraries were found for “Servo.h”
Used: C:\Program
Not used: C:\Users\jack\Documents\Arduino\libraries\ESP32_Arduino_Servo_Library exit status 1
Error compiling for board DOIT ESP32 DEVKIT V1.
This report would have more information with “Show verbose output during compilation” option enabled in File -> Preferences.

Sours: https://rntlab.com/question/unit-9-esp32-control-servo-motor-library-problem/

ESP32 - Servo Motor

Servo motor is a component that can rotate its handle (usually between 0° and 180°). It used to control the angular position of the object.

The servo motor used in this example includes three pins:

  • VCC pin (typically red) needs to be connected to VCC (5V)

  • GND pin (typically black or brown) needs to be connected to GND (0V)

  • Signal pin (typically yellow or orange) receives the PWM control signal from an ESP32's pin.

  • Servo Motor Pinout

This section is the in-depth knowledge. DON'T worry if you don't understand. Ignore this section if it overloads you, and come back in another day. Keep reading the next sections.

After connecting VCC pin and GND pin to 5V and 0V, respectively, we can control the servo motor by generating proper PWM signal to signal pin.

The angle is determined by the width of PWM signal.

Datasheet of the servo motor provides us the following parameters:

  • Period of PWM (PERIOD)

  • Minimum width of PWM (WIDTH_MAX)

  • Maximum width of PWM (WIDTH_MIN)

These parameters are fixed in ESP32 Servo library. We do NOT need to know the value of parameters.

The angle is determined as follows:

  • If PWM's width = WIDTH_MIN, the servo motor rotates to 0°.

  • If PWM's width = WIDTH_MAX, the servo motor rotates to 180°.

  • If PWM's width is between WIDTH_MIN and WIDTH_MAX, the servo motor rotates to angle between 0° and 180° in proportion.

  • How Servo Motor Works

Some of ESP32 pins can be programmed to generate PWM signal. We can control the servo motor by connecting the servo motor's signal pin to an ESP32's pin, and programming to generate PWM on the ESP32's pin.

Thanks to ESP32 Servo library, controlling servo motor is a piece of cake. We even do NOT need to know how servo motor works. We also do NOT need to know how to generate PWM signal. We JUST need to learn how to use the library.

ESP32 Servo Motor Wiring Diagram

Image is developed using Fritzing. Click to enlarge image

#include <Servo.h>

If you control more than one servo motors, you just need to declare more Servo objects:

Servo myServo1;Servo myServo2;

  • Set the control pin of ESP32, which connects to the signal pin of the servo motor. For example, pin 9:

myServo.attach(9);

  • Lastly, rotate the angle of the servo motor to the desired angle. For example, 90°:

myServo.write(90);

  • If this is the first time you use ESP32, see how to setup environment for ESP32 on Arduino IDE

  • Connect the ESP32 board to your PC via a micro USB cable

  • Open Arduino IDE, select the right ESP32 board and COM port

  • On Arduino IDE, Go to File Examples Servo Sweep example

#include <Servo.h>Servo myservo; int pos = 0; voidsetup() { myservo.attach(9); }voidloop() {for (pos = 0; pos <= 180; pos += 1) { myservo.write(pos); delay(15); }for (pos = 180; pos >= 0; pos -= 1) { myservo.write(pos); delay(15); }}

  • Click Upload button on Arduino IDE to compile and upload code to ESP32 board

  • How to upload ESP32 code on Arduino IDE
  • See the result: Servo motor rotates slowly about 180° in clockwise and counter-clockwise direction

Read the line-by-line explanation in comment lines of code!

By using map() and millis() functions, we can control the speed of servo motor smoothly without blocking other code

#include <Servo.h>Servo myServo;unsignedlong MOVING_TIME = 3000; unsignedlong moveStartTime;int startAngle = 30; int stopAngle = 90; voidsetup() { myServo.attach(9); moveStartTime = millis(); }voidloop() {unsignedlong progress = millis() - moveStartTime;if (progress <= MOVING_TIME) {long angle = map(progress, 0, MOVING_TIME, startAngle, stopAngle); myServo.write(angle); }}

We are considering to make the video tutorials. If you think the video tutorials are essential, please subscribe to our YouTube channel to give us motivation for making the videos.

Use the servo motor to do one of the following projects:

  • The Servo library supports up to 12 motors on ESP32 UNO and 48 on the ESP32 Mega.

  • Power from 5V pin of ESP32 maybe NOT enough for servo motor in one of the following cases:

    • Using a high-torque servo motor, which can carry a high-weight thing.

    • Using many servo motors.

In these cases, we may need to provide an extra power source for servo motor.

ESP32 Servo Motor Extra Power

Image is developed using Fritzing. Click to enlarge image

As we can see in the above diagram, the VCC pin of servo motor doest NOT connect to the 5V pin of ESP32. It connects to the positive pin of an extra power source. The negative pin of extra power source is connected to the GND pin of ESP32.

The above code also works with the following servo motors:

※ NOTE THAT:

Note that this tutorial is incomplete. We will post on our Facebook Page when the tutorial is complete. Like it to get updated.

※ NOTICES

  • We are AVAILABLE for HIRE. See how to hire us to do your project

  • If this tutorial is useful for you, please support us to make more tutorials.

  • We spent a lot of time and effort to create the content for this tutorial, please respect our work! Please do not copy the content to share on other websites. Howerver, please feel free to share the link of this tutorial anywhere

Follow Us On

Share with your friends!

Sours: https://esp32io.com/tutorials/esp32-servo-motor
  1. App store dji go
  2. Birch desk with drawers
  3. Campsites near fresno
  4. Redline hot wheels

Servo Library for ESP32

Servo - Class for manipulating servo motors connected to ESP32 pins. int attach(pin ) - Attaches the given GPIO pin to the next free channel (channels that have previously been detached are used first), returns channel number or 0 if failure. All pin numbers are allowed, but only pins 2,4,12-19,21-23,25-27,32-33 are recommended. int attach(pin, min, max ) - Attaches to a pin setting min and max values in microseconds; enforced minimum min is 500, enforced max is 2500. Other semantics are the same as attach(). void write () - Sets the servo angle in degrees; a value below 500 is treated as a value in degrees (0 to 180). These limit are enforced, i.e., values are constrained as follows: Value Becomes ----- ------- < 0 0 0 - 180 value (treated as degrees) 181 - 499 180 500 - (min-1) min min-max (from attach or default) value (treated as microseconds) (max+1) - 2500 max
Sours: https://github.com/jkb-git/ESP32Servo
NodeMcu (ESP8266) control Servo motor basic usage

In this tutorial we’re going to show you 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 on how to control a servo with the ESP32, and then we’ll build the web server.

Watch the Video Tutorial and Project Demo

This guide is available in video format (watch below) and in written format (continue reading).

Parts Required

For this tutorial we’ll use the following parts:

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.

WireColor
PowerRed
GNDBlack, or brown
SignalYellow, 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 other type, 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 is able to produce a PWM signal. However, we don’t recommend using GPIOs 9, 10, and 11 that are connected to the integrated SPI flash and are not recommend 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 in various angles from 0 to 180º. Servos are controlled using a pulse width modulation (PWM) signal. This means that 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

There’s an add-on for the Arduino IDE allows you to program the ESP32 using the Arduino IDE and its programming language. Follow one of the next tutorials to prepare your Arduino IDE to work with the ESP32, if you haven’t already.

After making sure you have the ESP32 add-on installed, you can continue this tutorial.

Installing the ESP32_Arduino_Servo_Library

The ESP32 Arduino Servo 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 your Arduino IDE:

  1. Click here to download the ESP32_Arduino_Servo_Library. You should have a .zip folder in your Downloads folder
  2. Unzip the .zip folder and you should get ESP32-Arduino-Servo-Library-Master folder
  3. Rename your folder from  to ESP32_Arduino_Servo_Library
  4. Move the ESP32_Arduino_Servo_Library folder to your Arduino IDE installation libraries folder
  5. Finally, re-open your Arduino IDE

Testing an Example

After installing the library, go to your Arduino IDE. Make sure you have the ESP32 board selected, and then, go to File > Examples > ServoESP32 > Simple Servo.

View raw code

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:

Then, you need to create a servo object. In this case it is called myservo.

setup()

In the setup(), you initialize a serial communication for debugging purposes, and attach GPIO 13 to the servo object.

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 in the servo object. You pass as an argument, an integer number with the position in degrees.

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 (learn more about building an ESP32 Web Server). The web server we’ll build:

  • 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 in the web page, as well as the shaft position, without the need to refresh the web page. For this, we use AJAX to send HTTP requests to the ESP32 on the background;
  • Refreshing the web page doesn’t change the slider value, neither the shaft position.

Creating the HTML Page

Let’s start by taking a look at the HTML text the ESP32 needs to send to your browser.

View raw code

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.

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:

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:

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.

View raw code

How the Code Works

First, we include the Servo library, and create a servo object called myservo.

We also create a variable to hold the GPIO number the servo is connected to. In this case, GPIO 13.

Don’t forget that you need to modify the following two lines to include your network credentials.

Then, create a couple of variables that will be used to extract the slider position from the HTTP request.

setup()

In the setup(), you need to attach the servo to the GPIO it is connected to, with myservo.attach().

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.

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.

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 on 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 you want to learn more about it, we recommend enrolling in Learn ESP32 with Arduino IDE course.

You might also like reading:

We hope you’ve found this tutorial useful.

Thanks for reading.




Sours: https://randomnerdtutorials.com/esp32-servo-motor-web-server-arduino-ide/

Library esp32 servo

Today we’ll see a few ways of interfacing servo motors to the ESP32 microcontroller and controlling them with code, with a potentiometer, and over WiFi.

Introduction

We have already looked at both the ESP32 microcontroller and at using analog servo motors, and today we’ll put both of them together. We’ll see how to interface and control servo motors with the ESP32 and we’ll take advantage of the microcontrollers’ WiFi capabilities to control a servo with a web-based interface.

As you’ll soon see, controlling a servo motor with the ESP32 is quite similar to using an Arduino, with the added advantage of the ESP32’s wealth of ports and capabilities.

Servos & ESP32

Controlling an analog servo motor, which is the type of servo motors most commonly used by hobbyists, is a task that most microcontrollers have no problem performing.  Arduino’s, for example, have no problem controlling servos and the Arduino IDE even comes with a built-in servo motor library and a few bits of sample code to get you started.

Servo Motors & ESP32

So why use an ESP32, especially as most Arduino’s are less expensive?  Depending upon your application there may be no reason, or there may be several. Here are a few:

  • The ESP32 has a wealth of I/O ports, more than most Arduino’s.
  • The ESP32 has analog outputs as well as analog inputs.
  • There are built-in sensors in the ESP32, including a hall-effect sensor.
  • The ESP32 has I/O pins that can be used as touch switches
  • It has a lot of PWM output pins, so it can drive several servo motors.
  • It has built-in WiFi and Bluetooth capabilities.

The latter reason is why many people choose the ESP32 over an Arduino for controlling servo motors. Built-in WiFi and Bluetooth open the door to all sorts of remote control possibilities. 

Servo Motors

Servo motors are geared DC motors that have an integrated servomechanism with a feedback loop to allow precise positioning of the motor shaft. A high gear ratio allows a small servo to have an impressive torque rating. 

Most servos are limited in rotation to either 180 or 270 degrees, with 180-degree servo motors being more common.   There are specially modified servo motors that can rotate beyond 360-degrees, but we won’t be working with those today.

Servo motors come in a wide range of sizes and can be controlled either with an analog PWM signal or with a digital I/O signal. The inexpensive servos we use for hobbyist applications are usually analog servo motors, which are the types we will be using today.

Servo Motors

A very common and inexpensive servo motor is the SG90. It’s a small plastic-gear servo that has become a standard for experimenting and is also used in a lot of RC hobby applications. It has a “cousin”, the MG90, which has similar specifications but uses metal gears.

The SG90, like most servo motors, can be powered from 5-6 volts, so servo motors are great for battery-powered applications.

Servo Motor Connections

Most analog servo motors like the SG90 use a 3-wire color-coded cable for interfacing. Although the color-coding is not an official standard many manufacturers use the same colored wires:

  • Orange– The PWM servo control input. This is a logic-level signal, and most servo motors can accept 3.3-volt logic as well as 5-volt logic.  Some models, especially 270-degree rotation servos,  use a White wire for this connection.
  • Red – The servo motor power supply input. Generally 5-6 volts DC, but be sure to check first.
  • Brown – The ground connection. On some servo motors, this is a Black wire.

Servo Motor Pinout - Normal

Most servo motor cables terminate in a 3-pin Dupont female connector.  You can use jumper wires to connect this to a solderless breadboard.

Servo Positioning

Analog servo motors use PWM, or Pulse Width Modulation, to control the motor shaft position. 

The PWM signal is usually about 50Hz, which is a period of 20ms. Within that period the pulse width is varied, a shorter pulse positions the servo towards the zero-degree mark while a longer one moves the motor shaft towards the 180 (or 270) degree position.

The pulse is continually applied to the control lead on the motor, locking the shaft into the desired position.

If you’d like a more detailed overview of servo motor operation check out the article Using Servo Motors with the Arduino. 

ESP32 PWM

Most microcontrollers can be used to generate PWM signals and the ESP32 is certainly no exception. In fact, the ESP32 has the capability of controlling 16 PWM outputs independently.

One thing to note about the ESP32, however, is that many of the GPIO pins have multiple functions.  So when selecting a PWM pin to use with your servo motor you’ll want to be sure that you don’t need one of the pins other functions in your design.

Even with that slight restriction, there are still several PWM pins available to drive servo motors, LEDs, and many other devices.

ESP32Servo Library

The Arduino IDE comes with a built-in servo motor control library, which is appropriately named “Servo”. Unfortunately, it won’t work with the ESP32.

There are many servo motor control libraries available for the ESP32, many of which emulate the Arduino Servo library while adding new functionality.

I’ve chosen to use the ESP32Servo Library by Kevin Harrington. This library duplicates the functionality of the original Arduino Servo library while adding a few extra features of its own.

IDE Setup

In order to work with ESP32 boards in the Arduino IDE, you are going to need to add a new Board Manager into the IDE. You’ll then use that new Board Manager to import the ESP32 boards and software examples.

You’ll need to open the Preferences box, which you’ll find under the File menu item, and then add the following location to the “Additional Boards Manager URLs” box:

https://raw.githubusercontent.com/espressif/arduino-esp32/gh-pages/package_esp32_index.json

After doing that and restarting the IDE you can go into the Boards Manager, which you’ll find under the Tools/Boards menu item, and search for ESP32. You should see an entry for “esp32 by Espressif Systems”. Highlight this entry and click on the Install button. 

For more detailed instructions see my ESP32 introductory article.

Library Installation

You can install the ESP32Servo Library directly from within your Arduino IDE using the Library Manager.

Open the Library Manager, which you’ll find under the Sketch/Include Library/Manage Libraries menu item.

Type “ESP32Servo” into the search box. From the displayed libraries select the ESP32Servo library, when you do the OK button will appear. Click that button to install the library.

Once the library is installed open your File/Examples menu and scroll down to the section for ESP32Servo. You’ll see a number of examples, some with familiar names. The ones that look familiar are modified versions of the example sketches from the Arduino Servo Library.

We are going to test out a couple of those sketches right now, but before we do we’ll need to get our ESP32 and servo motor all hooked up.

ESP32 Servo Hookup

For our first two experiments you’ll need the following parts:

  • An ESP32 WROOM based module. You don’t need to use the same module I used, just make sure you have a pinout diagram of your module handy so that you can wire to the correct pins.
  • A Servo Motor. I used an SG90, but any small analog servo motor will work. You can fine-tune the servo position in the code for just about any servo motor.
  • A Potentiometer. I used a 10k linear pot, but any value from 5k upwards should work. Just make sure it is a linear-taper pot, i.e. it is at half-value when the shaft is turned to the halfway point.
  • A Servo Power Supply. I always advocate powering motors with a power supply independent of the microcontroller. The servos usually need 5-6 volts. A 4-cell AA or AAA battery pack makes a great power supply for a servo motor.

For our experiments, you can just power the ESP32 using the USB connection to your computer. To run the circuit away from the computer you can use it’s 5-volt or 3.3-volt power pins to power it independently.

Here is the hookup, if your module has a different pinout then just make sure to use GPIO pin 18 for the PWM output. If you would like to use a different PWM-capable pin you’ll need to change the code to match.

ESP32 Servo Hookup

For my tests, I elected to use a breadboard power supply to supply the motor voltage with 5-volts. You can also use a 6-volt battery or other suitable supply to power the motor.

Make sure you use 3.3-volts on the connection to the potentiometer and not 5-volts.

Servo Motor & ESP32 with Breadboard Power Supply

Once you have it all wired up connect it to your computer with the USB cable.

Example 1 – Sweep

The two examples we are going to look at are both updated versions of classic Arduino sketches. You won’t need to write any code, as these example sketches were included when you installed the ESP32Servo library.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

/* Sweep

by BARRAGAN <http://barraganstudio.com>

This example code is in the public domain.

 

modified 8 Nov 2013

by Scott Fitzgerald

 

modified for the ESP32 on March 2017

by John Bennett

 

see http://www.arduino.cc/en/Tutorial/Sweep for a description of the original code

 

* Different servos require different pulse widths to vary servo angle, but the range is

* an approximately 500-2500 microsecond pulse every 20ms (50Hz). In general, hobbyist servos

* sweep 180 degrees, so the lowest number in the published range for a particular servo

* represents an angle of 0 degrees, the middle of the range represents 90 degrees, and the top

* of the range represents 180 degrees. So for example, if the range is 1000us to 2000us,

* 1000us would equal an angle of 0, 1500us would equal 90 degrees, and 2000us would equal 1800

* degrees.

*

* Circuit: (using an ESP32 Thing from Sparkfun)

* Servo motors have three wires: power, ground, and signal. The power wire is typically red,

* the ground wire is typically black or brown, and the signal wire is typically yellow,

* orange or white. Since the ESP32 can supply limited current at only 3.3V, and servos draw

* considerable power, we will connect servo power to the VBat pin of the ESP32 (located

* near the USB connector). THIS IS ONLY APPROPRIATE FOR SMALL SERVOS.

*

* We could also connect servo power to a separate external

* power source (as long as we connect all of the grounds (ESP32, servo, and external power).

* In this example, we just connect ESP32 ground to servo ground. The servo signal pins

* connect to any available GPIO pins on the ESP32 (in this example, we use pin 18.

*

* In this example, we assume a Tower Pro MG995 large servo connected to an external power source.

* The published min and max for this servo is 1000 and 2000, respectively, so the defaults are fine.

* These values actually drive the servos a little past 0 and 180, so

* if you are particular, adjust the min and max values to match your needs.

*/

 

#include <ESP32Servo.h>

 

Servo myservo;  // create servo object to control a servo

// 16 servo objects can be created on the ESP32

 

intpos=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

intservoPin=13;

 

voidsetup(){

// 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,500,2400);// 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

}

 

voidloop(){

 

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

}

}

The function of the Sweep sketch is pretty simple, it sweeps the servo motor shaft from zero to 180 degrees and then back to zero. It repeats this as long as it is powered up.

The only modifications made to the Sweep sketch from the original are the changes necessary to use the ESP32Servo library instead of the Arduino Servo library.

After including the ESP32Servo library we define an object called “myservo” to represent the servo motor.  We also define the GPIO pin that the control input for the servo is connected to.

In the setup you will note the timer allocation statements, something you will need to do when using the ESP32Servo library. 

We then define the frequency that we will be using to drive the servo control. 50Hz is pretty standard, but you can play with this value to improve servo performance.

Then we attach our servo object to the servo motor. You’ll notice three parameters here:

  • The servo GPIO pin number.
  • The minimum pulse width, which should drive the servo to the zero position.
  • The maximum pulse width, which should drive the servo to its maximum position, typically 180 degrees.

The loop is very simple and consists of two for-loop counters. One counts from 0 to 180 and steps the servo in one direction, the other steps it in reverse back to the zero point. We then repeat everything.

Hook everything up, load up the code and take a look at it working. You should see the servo sweep back and forth.

ESP32 Servo Sweep Test

When I did this it worked, but not very well. My servo motor did indeed sweep, but it wasn’t a full 180-degrees. More like about half that.

The way to fix this is to modify the sketch and change the values for the minimum and maximum time. Every servo is different so you can experiment to find the best fit for your motor. For the SG90 I was using the values of 500 and 2400 seemed to work.

Example 2 – Knob

Knob is another “classic” Arduino sketch, it’s entire purpose is to allow you to position a servo motor using a potentiometer.  If that was ALL you wanted to do then using a microcontroller is a bit of an overkill, but of course, this is just a demonstration!

As with the Sweep sketch Knob has been modified to support the ESP32Servo library instead of the original Arduino library. It has also been adjusted to account for the increased resolution of the ESP32’s analog to digital converters (ADC) over the Arduino’s.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

/*

Controlling a servo position using a potentiometer (variable resistor)

by Michal Rinott <http://people.interaction-ivrea.it/m.rinott>

 

modified on 8 Nov 2013

by Scott Fitzgerald

 

modified for the ESP32 on March 2017

by John Bennett

see  http://www.arduino.cc/en/Tutorial/Knob for a description of the original code

 

* Different servos require different pulse widths to vary servo angle, but the range is

* an approximately 500-2500 microsecond pulse every 20ms (50Hz). In general, hobbyist servos

* sweep 180 degrees, so the lowest number in the published range for a particular servo

* represents an angle of 0 degrees, the middle of the range represents 90 degrees, and the top

* of the range represents 180 degrees. So for example, if the range is 1000us to 2000us,

* 1000us would equal an angle of 0, 1500us would equal 90 degrees, and 2000us would equal 1800

* degrees.

*

* Circuit: (using an ESP32 Thing from Sparkfun)

* Servo motors have three wires: power, ground, and signal. The power wire is typically red,

* the ground wire is typically black or brown, and the signal wire is typically yellow,

* orange or white. Since the ESP32 can supply limited current at only 3.3V, and servos draw

* considerable power, we will connect servo power to the VBat pin of the ESP32 (located

* near the USB connector). THIS IS ONLY APPROPRIATE FOR SMALL SERVOS.

*

* We could also connect servo power to a separate external

* power source (as long as we connect all of the grounds (ESP32, servo, and external power).

* In this example, we just connect ESP32 ground to servo ground. The servo signal pins

* connect to any available GPIO pins on the ESP32 (in this example, we use pin 18.

*

* In this example, we assume a Tower Pro SG90 small servo connected to VBat.

* The published min and max for this servo are 500 and 2400, respectively.

* These values actually drive the servos a little past 0 and 180, so

* if you are particular, adjust the min and max values to match your needs.

*/

 

// Include the ESP32 Arduino Servo Library instead of the original Arduino Servo Library

#include <ESP32Servo.h>

 

Servo myservo;  // create servo object to control a servo

 

// Possible PWM GPIO pins on the ESP32: 0(used by on-board button),2,4,5(used by on-board LED),12-19,21-23,25-27,32-33

intservoPin=18;      // GPIO pin used to connect the servo control (digital out)

// Possible ADC pins on the ESP32: 0,2,4,12-15,32-39; 34-39 are recommended for analog input

intpotPin=34;        // GPIO pin used to connect the potentiometer (analog in)

intADC_Max=4096;     // This is the default ADC max value on the ESP32 (12 bit ADC width);

                        // this width can be set (in low-level oode) from 9-12 bits, for a

                        // a range of max values of 512-4096

  

intval;    // variable to read the value from the analog pin

 

voidsetup()

{

// Allow allocation of all timers

ESP32PWM::allocateTimer(0);

ESP32PWM::allocateTimer(1);

ESP32PWM::allocateTimer(2);

ESP32PWM::allocateTimer(3);

  myservo.setPeriodHertz(50);// Standard 50hz servo

  myservo.attach(servoPin,500,2400);   // attaches the servo on pin 18 to the servo object

                                         // using SG90 servo min/max of 500us and 2400us

                                         // for MG995 large servo, use 1000us and 2000us,

                                         // which are the defaults, so this line could be

                                         // "myservo.attach(servoPin);"

}

 

voidloop(){

  val=analogRead(potPin);            // read the value of the potentiometer (value between 0 and 1023)

  val=map(val,0,ADC_Max,0,180);     // scale it to use it with the servo (value between 0 and 180)

  myservo.write(val);                  // set the servo position according to the scaled value

  delay(200);                          // wait for the servo to get there

}

The servo motor object is created and attached exactly as it was in the previous sketch.

Note the value of 4096 for ADC_Max, it represents the maximum value for the analog to digital converter. By default, the ESP32 uses a 12-bit A/D converter. 

In the loop, all we do is read the potentiometer position by obtaining a value from the A/D converter. This is mapped to a range of 0-180.

We then use this value to write to the servo object, which moves the servo motor to the desired position.

ESP32 Servo Knob Sketch

Run the sketch and twist the potentiometer. You should observe the servo motor moving when you move the potentiometer.

Multiple Servos with PCA9685

The ESP32 has the capability of driving 16 PWM channels, so you can drive several servo motors directly.  Some ESP32 Servo libraries only support a limited number of motors, however, the ESP32Servo library that we are using will support all 16 PWM pins.

However, bear in mind that the GPIO pins that support PWM also have other functions, some of which you might need in your project. 

You also might need MORE than 16 servo motors for a project as wild as it might sound. A “robot spider” with eight legs and three degrees of freedom per leg would need 24 servo motors, give it four degrees of freedom and the number goes up to 32.

Or you may want to minimize the number of connections to the ESP32, or locate your motors away (but not too far away) from the microcontroller.

All of these requirements sound like a good fit for the PCA9685.

PCA9685 16-Channel PWM Module

The PCA96845 is a 16-channel PWM controller module that can be used with servo motors, LEDs, and pretty well anything that you can control with a PWM pulse.

The module is an I2C device, so all of the work of timing and producing PWM signals is done onboard, freeing the host device (the ESP32 in this case) from having to deal with it.

This device has six selectable address bits, and you can cascade up to 62 of them on the same I2C bus.  This would allow you to control up to 992 servo motors! 

PCA9685 Modules

You can buy the device assembled or as a board with headers and terminals that you solder in yourself, allowing you more flexibility in incorporating the PCA9685 into your project.

The connections on the PCA9685 module are duplicated on each end, making it easy to use multiple modules.  By using right-angled Dupont male and female connectors you could “daisy chain” the modules. Just make sure to select a unique I2C address for each module. 

As I don’t have 992 servo motors in stock in the workshop at the moment I’ll confine myself to one module and two servo motors, but the coding principles can be extended to any number of modules and servo motors.

ESP32 PCA9685 Hookup

The PCA9685 is an I2C device and can operate with either 3.3 or 5-volt logic and power. We will be using 3.3-volt logic and will power the module from the ESP32.

ESP32 PCA9685 Servo Hookup

The I2C connections to the ESP32 are as follows:

  1. SDA – IO21
  2. SCL – IO22

Actually you can use any two pins on the ESP32 for your I2C connections and define them in software. GPIO pins 21 and 22 are the default if new pins are not declared.

You’ll note the use of pullup resistors for the I2C data and clock lines. As we are using 3.3-volt logic you should use values in the 2.4k to 3.3k neighborhood.

I connected my servo motors to connectors 0 and 12, but you can choose any two you like, and you may add more servo motors.  When you look at the code you’ll see how to define your motor hookup and how to address each motor.

For a power supply, I used a battery-holder with four type AA batteries. Any 5 or 6-volt power supply should suffice, especially if you are using small SG90 servo motors as I did.

ESP32 PCA9685 Code

A great source for obtaining PCA9685 modules is Adafruit, and if you know Adafruit then you’ll know that they don’t sell anything without creating extensive documentation, articles, code samples, and libraries. The PCA9685 is no different, so we will be using an Adafruit library that works with both the Arduino and the ESP32.

Here is the sketch I used to control the two servo motors using the ESP32 and the PCA9685.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

/*

  ESP32 PCA9685 Servo Control

  esp32-pca9685.ino

  Driving multiple servo motors with ESP32 and PCA9685 PWM module

  Use I2C Bus

 

  DroneBot Workshop 2020

  https://dronebotworkshop.com

*/

 

// Include Wire Library for I2C

#include <Wire.h>

 

// Include Adafruit PCA9685 Servo Library

#include <Adafruit_PWMServoDriver.h>

 

// Creat object to represent PCA9685 at default I2C address

Adafruit_PWMServoDriver pca9685=Adafruit_PWMServoDriver(0x40);

 

// Define maximum and minimum number of "ticks" for the servo motors

// Range from 0 to 4095

// This determines the pulse width

 

#define SERVOMIN  80  // Minimum value

#define SERVOMAX  600  // Maximum value

 

// Define servo motor connections (expand as required)

#define SER0  0   //Servo Motor 0 on connector 0

#define SER1  12  //Servo Motor 1 on connector 12

 

// Variables for Servo Motor positions (expand as required)

intpwm0;

intpwm1;

 

voidsetup(){

 

  // Serial monitor setup

  Serial.begin(115200);

 

  // Print to monitor

  Serial.println("PCA9685 Servo Test");

 

  // Initialize PCA9685

  pca9685.begin();

 

  // Set PWM Frequency to 50Hz

  pca9685.setPWMFreq(50);

 

}

 

voidloop(){

 

  // Move Motor 0 from 0 to 180 degrees

  for(intposDegrees=0;posDegrees<=180;posDegrees++){

 

    // Determine PWM pulse width

    pwm0=map(posDegrees,0,180,SERVOMIN,SERVOMAX);

    // Write to PCA9685

    pca9685.setPWM(SER0,0,pwm0);

    // Print to serial monitor

    Serial.print("Motor 0 = ");

    Serial.println(posDegrees);

    delay(30);

  }

 

  // Move Motor 1 from 180 to 0 degrees

  for(intposDegrees=180;posDegrees>=0;posDegrees--){

 

    // Determine PWM pulse width

    pwm1=map(posDegrees,0,180,SERVOMIN,SERVOMAX);

    // Write to PCA9685

    pca9685.setPWM(SER1,0,pwm1);

    // Print to serial monitor

    Serial.print("Motor 1 = ");

    Serial.println(posDegrees);

    delay(30);

  }

 

  // Move Motor 0 from 180 to 0 degrees

  for(intposDegrees=180;posDegrees>=0;posDegrees--){

 

    // Determine PWM pulse width

    pwm0=map(posDegrees,0,180,SERVOMIN,SERVOMAX);

    // Write to PCA9685

    pca9685.setPWM(SER0,0,pwm0);

    // Print to serial monitor

    Serial.print("Motor 0 = ");

    Serial.println(posDegrees);

    delay(30);

  }

 

 

  // Move Motor 1 from 0 to 180 degrees

  for(intposDegrees=0;posDegrees<=180;posDegrees++){

 

    // Determine PWM pulse width

    pwm1=map(posDegrees,0,180,SERVOMIN,SERVOMAX);

    // Write to PCA9685

    pca9685.setPWM(SER1,0,pwm1);

    // Print to serial monitor

    Serial.print("Motor 1 = ");

    Serial.println(posDegrees);

    delay(30);

  }

 

 

}

The code makes use of an Adafruit library for the PCA9685, the Adafruit PWM Servo Driver library. You can obtain this directly within your Library Manager, just as you did with the ESP32Servo library.

We also use the Wire library, which is the built-in library for working with I2C.

As with our previous sketches we need to calculate some values to represent the minimum and maximum pulse width for our servo motors. Unlike the previous sketches we don’t specify this time period in microseconds but instead in “ticks”.

So what is a “tick”?

A tick is a time period used by the PCA9685.  On the PCA9685 you specify a pulse frequency in Hz. Each cycle of the pulse is divided into 4096 periods called “ticks”.

To make the pulse have a 50% duty-cycle you would hold it HIGH for the first 2048 ticks and then low for the remaining 2048 ticks.  For a 25% duty-cycle you would keep it HIGH for only 1024 ticks.

So the constants SERVOMIN and SERVOMAX represent the number of ticks in the minimum and maximum pulse widths.

Next, we define connections for our individual servo motors. As I connected my first motor on connector 0 and my second one on connector 12 I used 0 and 12, you can, of course, connect to any of the 16 connectors and define your motors accordingly.

I also defined a couple of variables to be used to represent the servo position.

In the Setup, we initialize the Serial Monitor, note the baud rate which is typical of ESP32 projects.  We also print to the monitor.

Then we initialize the PCA9685 and set its PWM frequency to 50Hz. You can experiment with this to improve your servo performance if you wish.

In the Loop, I got lazy and essentially copied the Sweep example twice! The difference here is that I’m driving the two servo motors and alternating between them. 

The key to understanding this part of the code is to see how the position data is written to the servo motor.  The setPWM function from the Adafruit library is used to position the motor. It has three parameters:

  • The Servo connector number, from 0 to 15
  • The Starting Tick for the pulse. In this example it is always set to 0.
  • The Ending Tick for the pulse. 

The tick values are determined using a map command against the SERVOMIN and SERVOMAX values.

ESP32 Servo & PCA9685

Hook everything up and load the code and then reset the ESP32. You should observe the two motors alternating through sweeps.

Web Remote Controlled Servo

Probably the greatest attraction of using an ESP32 with a servo motor is the potential for developing a remote control system using the ESP32s Bluetooth or WiFi.

Creating a remote control requires a two-way conversation between the users’ browser and the web server created by the ESP32. Traffic back from the browser can take several forms, from simple GET requests on the URL line to AJAX.   The ESP32 returns HTTP traffic to the web browser.

Here is a very simple web-based control for a servo motor. It has one control, a slider, whose purpose is to control the position or angle of the servo shaft.

ESP32 Web Server Hookup

If you have the breadboard still set up from our first experiments you can use it as-is. 

ESP32 Remote Servo Hookup

The only difference with the wiring is that we are no longer using the potentiometer, so you may remove it if you wish.

Make sure you know your WiFi SSID and password, as you’ll be needing it when coding. The ESP32 only supports 2.4GHz WiFi.

ESP32 Web Server Code

One of the best resources for ESP32 information on the web is the Random Nerd Tutorials website.  These folks (Rui and Sara Santos) are so good that Espressif, the company that manufactures the ESP32, refers to them on their blog as a source of quality ESP32 information.

I’ve used their site many times in my own ESP32 research, the following sketch is a blatant copy of one that Rui Santos wrote for Random Nerd Tutorials. I’ve only modified it in two slightly significant ways:

  • I changed the servo library to the ESP32Servo library, as Rui was using a different one.
  • I styled the page a bit differently.  Mine is blue!

The sketch is not only a great example of controlling a servo motor with a web-based interface, it’s a great example of controlling really anything with a web-based interface.  

The sketch starts a web server and creates a webpage that has a slider control. Sliding the control to a different position causes that position to be sent back to the ESP32 using AJAX. The ESP32 then positions the servo motor accordingly.

You could use the same arrangement to send numerical data to control almost anything, and of course you could add more controls using the same technique.

Here is the sketch:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

122

123

124

125

126

127

128

129

130

131

132

133

134

135

136

137

138

139

140

141

142

143

144

145

146

147

148

149

150

151

152

153

154

155

156

157

158

159

160

161

162

163

164

165

166

167

168

169

170

171

172

173

174

175

176

177

178

179

180

181

182

183

184

185

186

/*

  ESP32 Remote WiFi Servo Control

  esp32-web-servo.ino

  Control servo motor from web page

  

  Based upon example from Rui Santos

  Random Nerd Tutorials

  https://randomnerdtutorials.com/esp32-servo-motor-web-server-arduino-ide/

  

 

  DroneBot Workshop 2020

  https://dronebotworkshop.com

*/

 

#include <WiFi.h>

#include <ESP32Servo.h>

 

Servo myservo;  // create servo object to control a servo

 

// Servo GPIO pin

staticconstintservoPin=18;

 

// Network credentials

constchar*ssid     ="YOURSSID";

constchar*password="YOURPW";

 

// Web server on port 80 (http)

WiFiServer server(80);

 

// Variable to store the HTTP request

Stringheader;

 

// Decode HTTP GET value

StringvalueString=String(5);

intpos1=0;

intpos2=0;

 

// Current time

unsignedlongcurrentTime=millis();

// Previous time

unsignedlongpreviousTime=0;

// Define timeout time in milliseconds (example: 2000ms = 2s)

constlongtimeoutTime=2000;

 

voidsetup(){

  

  // Allow allocation of all timers for servo library

  ESP32PWM::allocateTimer(0);

  ESP32PWM::allocateTimer(1);

  ESP32PWM::allocateTimer(2);

  ESP32PWM::allocateTimer(3);

  

  // Set servo PWM frequency to 50Hz

  myservo.setPeriodHertz(50);

  

  // Attach to servo and define minimum and maximum positions

  // Modify as required

  myservo.attach(servoPin,500,2400);

  

  // Start serial

  Serial.begin(115200);

 

 

  // 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();

}

 

voidloop(){

  

  // Listen for incoming clients

  WiFiClient client=server.available();  

  

  // Client Connected

  if(client){                            

    // Set timer references

    currentTime=millis();

    previousTime=currentTime;

    

    // Print to serial port

    Serial.println("New Client.");

    

    // String to hold data from client

    StringcurrentLine="";

    

    // Do while client is cponnected

    while(client.connected()&& currentTime - previousTime <= timeoutTime) {

      currentTime = millis();

      if(client.available()){             // if there's bytes to read from the client,

        charc=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

            client.println("HTTP/1.1 200 OK");

            client.println("Content-type:text/html");

            client.println("Connection: close");

            client.println();

 

            // Display the HTML web page

            

            // HTML Header

            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 - Modify as desired

            client.println("<style>body {text-align:center;font-family:\"TrebuchetMS\",Arial;margin-left:auto;margin-right:auto;}");

            client.println(".slider {-webkit-appearance:none;width:300px;height:25px;border-radius:10px;background:#ffffff;outline:none;  opacity:0.7;-webkit-transition:.2s;  transition:opacity.2s;}");

            client.println("

Sours: https://dronebotworkshop.com/esp32-servo/
3 Creative ideas with Arduino

ServoESP32 Build Status

Generate RC servo signal on a selected pins with ESP32 device and Arduino framework.

Base on servo library for stm32f4 (d2a4a47).

Interface

The interface is similar to Arduino/Servo: https://www.arduino.cc/en/Reference/Servo

But the function is different:

boolattach( int pin, int channel = CHANNEL_NOT_ATTACHED, int minAngle = MIN_ANGLE, int maxAngle = MAX_ANGLE, int minPulseWidth = MIN_PULSE_WIDTH, int maxPulseWidth = MAX_PULSE_WIDTH );

More information in source code documentation.

Example: 04-SimpleServoAngles

PlatformIO

This library is also available at the PlatformIO as ServoESP32.

Arduino IDE

This library is available in Arduino IDE Library Manager as .

Known issues

Problem with build in Arduino IDE 1.8.10

There was an issue with building this library in Arduino IDE 1.8.10. But this issue should be fixed in Arduino IDE 1.8.11.

Sours: https://github.com/RoboticsBrno/ServoESP32

You will also be interested:

.



631 632 633 634 635