Introduction: Tutorial:ESP32 & DC Motors

This is a modification and addition to my instructable.com tutorials on DC Motors, and it also includes some information from my tutorial on the “ESP32 Tutorial: Touch, Hall, I2C, PWM, ADC, & DAC”. The earlier DC motor tutorials were focused on the Arduino UNO, while this tutorial is focused on the ESP32 development board. However, both groups of tutorials include similar, and in some instances identical, information.

Thus, as noted, this tutorial is focused on DC Motors and ESP32 development boards.

DC motors are ubiquitous. They convert electrical/magnetic energy, produced by a wire carrying current in a magnetic field, to motion, and they appear in all sorts of appliances and applications, e.g., they are found in small fans, ceiling fans, air cleaners, solder fume extractors, quadcopters, small helicopters, and other drones, hand-held rotary tools, circular saws, drills, lathes, sanders, cars, robots (where they rotate tires, or move robotic arms, etc.), aquarium air pumps, maker projects, and many other areas.

The most popular motors generally have shafts that are round, or 'D'-shaped (i.e., flattened on one side), flattened on two sides, or geared (i.e., have gears directly cut into the shaft or mounted on the shaft). See photographs for examples of these popular shaft styles. Although motors can run from DC, AC, and in the case of universal motors from both DC and AC, this tutorial only discusses DC motors in detail.

Electric current and magnetism go hand-in-hand as it is impossible to have one without the other. As can be seen in the photographs current through a wire moves a compass needle owing to the magnetic field generated around the wire by the current passing through it. Hans Christian Oersted, the Danish physicist, identified this connection between electricity and magnetism in the early 1800's. [Some interesting but not essential information: The 'Oe' in the name shown here, can be replaced by a single capital Danish O (i.e., Ø) and on occasion one sees his name as Ørsted].

Magnetism produced by current flowing through a single wire is weak. If this wire is wound into a coil the magnetic field becomes stronger. If this coil is then wrapped around a ferrite core its magnetic field becomes even stronger.

The theory of DC motors is not difficult to understand, if we recall that for magnets opposite poles attract and similar poles repeal. A DC motor works by having the poles of a rotor through which current flows, thereby producing a magnetic field, subjected to another magnetic field which attracts the magnetic field of the rotor. It is interesting to learn that the opposite is also true. That is, as a motor rotates the interaction of the magnetic fields produces a voltage. This can be seen in the attached video, where a NEMA-17 stepper motor is turned to produce a voltage and light an LED, i.e., where the motor is used as a generator.

In this tutorial we will discuss several types of DC motors, although there are many other types of motors. However, DC motors are probably the most popular motors used with microcontrollers. Here we use these motors with the ESP32 microcontroller development board.

An ESP32 development board contains an ESP32-WROOM-32 module, made by Espressif Systems of Shangai, China.

The ‘W’ in the name is silent. So, ‘WROOM’ is pronounced as ‘room’. Sadly, many on-line presenters mispronounce this chip's name, pronouncing the 'W', which should be silent. I checked with Espressif to confirm that the 'W' is silent as in the English words wren, write, wrist, wrong, wrest, wrestling, wrinkle, wreck, etc. Espressif confirmed that "WROOM" is correctly pronounced with a silent 'W'.

Motors are devices that can impart motion, i.e., movement, to our projects. You can see two of my prior Instructables where this occurs: “Personal, portable, lightweight, air conditioner: An inexpensive and effective DIY project”, and “Making a Hypnotic disk using an Arduino and small DC motor”. They provide examples of DC motors that were used in Arduino projects, not ESP32 projects, but are none-the-less instructive. Although many Instructables can be found that use one or more motors. Most use Arduino UNO boards to control these motors.

Fortunately, with DC motors used by Makers, we need not be too concerned with voltage (although we need to be sure a motor is designed to work at the voltage we have available). However, current is a different matter as almost all motors take more current than is available, from an ESP32 development board pin. Thus. we need to insure that we can provide an appropriate intermediate device to handle the current needed.

Our main concerns with motors are speed and torque. Speed for motors is measured, unlike it is when we measure the speed of a car in miles per hour or kilometers per hour, in rotations per minute (RPM) or radians/sec, e.g., 3,000 RPM or 450 rad/sec. Note, these are but two examples of how motor speed might be represented. They are not meant to imply that 3,000 RPM is equal to 450 rad/sec; it is not. Fortunately, it is easy to covert from RPM to radians/sec or degrees/sec, and the reverse.

Speed is represented by the Greek letter omega, ω. Sir Isaac Newton's second law of motion is: Force equals mass multiplied by Acceleration, where Force and Acceleration are directional, although mass is not.

Torque is a "twisting/turning force". Force is often measured in Newton's (N) . When we multiply force by length we get torque, e.g., Newton-meters (N-m), Newton-centimeters (N-cm), or ounce-inches (oz-in). In a motor the torque is always tangent to a circle centered on the shaft, i.e., it is at a right angle to a diameter. The symbol designating torque is the lowercase Greek letter tau, τ, and less frequently the English capital letter T. Datasheets for DC motors usually provide speed in both RPM, and radians or degrees/sec.

Torque is often presented in datasheets in several forms (e.g., as peak torque, stall torque (more on this later), and rated torque, etc. DC motor datasheets are usually quite comprehensive and present other motor parameters as well. It should be noted that motors can have the same power capability, but different speed and torque, as it is possible to exchange speed for torque.

Mass and weight are not the same. Although they are often interchanged in informal conversations. For example, on the moon a motor would have the same mass it does on Earth, but its weight would be different.

Supplies

The supplies needed are discussed in each step having a sketch, as it is not necessary to get some supplies if a sketch will not be implemented by the reader.

Step 1: Continuous Motors

There are four main parts to many continuous brushed DC motors. The rotor (the part that rotates) or armature (in engineering speak the armature is the component of an assembly that turns/pivots and that holds the main current carrying coils that produce a magnetic field) in this tutorial the rotor and armature are used interchangeably, i.e., as they are both the turning component in the center.

The stator, as its name might suggest, is stationary. It provides the magnetic field that surrounds the rotor. It is often in two parts. If the stator is made from a permanent magnets, the stator magnets are known as field magnets. Field magnets are reliable, as the magnetic field remains at a constant level, although their fields may diminish with time. Permanent magnets are found in many brushed motors.

If the stator is made from an electromagnet, the coils used to produce this magnetic field are known as field windings or field coils.

The remaining two parts of a typical brushed motor are the commutator, and the brushes/contacts.

Some decades ago DC motors used actual copper "brushes" that were held by springs and pressed against the commutator to shift current to the coils and keep the motors turning. Today DC motors have contacts that "brush" against the commutator, but true brushes are less common. Although actual brushes are not common, these devices are still referred to as brushed motors. Brushed motors are inexpensive, and usually have operational lives that are longer than the devices they are part of.

However, brushless motors are also available today, as noted previously, and they seem to be trending upward in popularity, as brushes/contacts can wear out, and may produce sparking. Brushed motors, as noted, are less expensive to manufacture and are commonly used in Maker projects. However, it is important to learn if their rotors rotate in bushings or ball bearings, as bushings typically have a shorter operational live.

In a simple DC motor the armature connects to a DC power source to produce a magnetic field when current flows. However, when the armature moves to become orthogonal to the stator, i.e., at right angles to the stator's magnetic field, there is almost no torque experienced. The momentum of the rotor usually carries it forward to continue spinning. To overcome this ‘defect’, a second armature coil at right angles to the first is added so that there is always one segment of the armature that is exposed to a magnetic torque, i.e., is receiving power while the rotor is in a portion of the magnetic field of the stator.

In most working DC motors (see attached photographs) there are several armature coils offset from each other.

In general, the more windings a coil has the higher its resistance, and the greater its torque, but the slower its speed. These coils insure that the motor turns smoothly and yields a high torque at all points in its rotation.

The rotor is connected to a commutator, which is a component that allows the rotor coil to change polarity as required to rotate continuously. The commutator is usually just a simple cylinder with contacts that have insulating gaps between them to allow "brush" conductive elements to connect, in turn, to the DC power source (see attached photographs). That is, it provides a simple switch to change the DC input. The commutator is connected to the DC power source by contacts that "brush" against the contacts on the commutator.

Permanent magnet stators are used in many small DC motors, an example of which can be seen in the attached photographs.

In other small DC motors and many larger DC motors the stator is magnetized by the same power source as the rotor. This can occur in one of two ways: parallel (producing a shunt motor) or serial producing a series motor. The stator can be connected to the DC power source in series or in parallel with the armature/rotor. There is a space between the rotor and stator, so as to allow the rotor to turn easily. This space is referred to as the "air gap" between the two.

Most motors are rotary, but there are motors where the rotary motion is converted to linear motion. These devices are known as "linear motors" or "linear actuators (although actuators may get their energy from sources other than DC power)".

Most motors used in Maker projects are fractional horsepower (FHP), as they have a rating less than one horsepower.

See the pictures here of the disassembled small continuous DC motor. The two permanent magnets that make up the stator, the rotor/armature, and the coils can be easily seen in the attached photographs of the motor shown.

Step 2: An ESP32 Development Board and a Continuous DC Motor

A continuous DC motor almost always requires more amperage than is available using an ESP32 development board pin. This restriction is not a problem when using an LED, but is a problem when using a DC motor. To overcome this limitation, a 2N2222 transistor can be used, these can be obtained for less than $0.02 each. They work well as switches, and can be used in ESP32 development with DC motors. The 2N2222 easily switches motor current on and off. A datasheet for this transistor, can be found at e.g.,

https://www.fairchildsemi.com/datasheets/PN/PN222.

The datasheet notes that the maximum voltage between emitter and base should not exceed 6.0 V, So, be sure to keep your voltage below this maximum value, or you risk damaging the transistor.

The first attached picture is of a 2N2222 in the less expensive TO-92 package, rather than what was the original metal TO-18 package. In this configuration the 2N2222 / 2N2222A is also called a P2N2222 or PN2222A.

It is important to review the datasheet for the particular version of this transistor that you use, to ensure that the maximum acceptable voltages and currents from base to emitter, and collector to emitter, are not exceeded.

An alternative, but more expensive, choice would be a MOSFET. We could also use a mechanical device such as a relay. If you need to handle more power then the 2N2222 can safely dissipate, a TIP120, Darlington complementary transistor will work. If properly heat sinked it can handle as much as 5A (see attached photograph).

For still more amperage, a TO-220 packaged N-Channel RFP30N06LE (P30NO6LE, P30N06) MOSFET can handle somewhat over 30 amps when its drain flange is appropriately connected to a metal heat sink. This N-Channel MOSFET can be driven from an ESP32 development board, and is useful for large DC motors.

The higher current flows between the 2N2222’s collector and emitter pins. It is controlled by the current flowing in the base and emitter pins. For this NPN transistor, when the base to emitter is set to turn the transistor on, the transistor switch allows more current to flow between the collector and emitter pins of the 2N2222 than flows between its base and emitter.

A 1N4001 diode should be placed across the two pins of the DC motor, with the line on the diode facing the positive voltage. It is placed in the opposite direction to normal current flow, and so usually has no current passing through it.

The 1N4001 can be used as a flyback diode to offer a path for the energy produced by the collapsing magnetic field of the motor when the power is shutoff. It is hard to place the diode incorrectly without knowing it, as if configured this way, it will shunt the current to the motor, and the motor will not spin.

Although the higher voltage may only occur for a few microseconds, it can be quite high, in the range of 100s of volts, and is enough in some cases to damage the transistor.

All DC motors work in an essentially similar manner. So, when using any of these intermediate devices with an ESP32 development board, i.e., a transistor, BJP, MOSFET, or relay, etc., they can act as a switch that can handle the extra current needed by the motor, also likely to be required is a user-added flyback diode as well.

In the example that follows, we do not use any of the intermediate items discussed above, e.g., a 2N2222, TIP120, RFP30N06LE, or a relay but rather a L9110 fan module. This module has a built-in motor and propeller. So, It is easier to see it in motion than might otherwise be the case.

Step 3: Sketch for the ESP32 Development Board Project Using a Continuous Motor

The supplies needed for the sketch presented below, are:

- A UBS to 5 volt DC adapter (see attached photograph)

- A L9110 fan module

- An LED (a 10mm blue LED is used here, but any size or color LED will also work)

- Four (4) female to male Dupont wires (10 cm wires were used here, but longer wires will work as well)

- Four (4) male to male Dupont wires (10 cm wires were used here, but longer wires will work as well)

- An ESP32 development board

- Any resistor from 220 ohm to 560 ohm should work to reduce the current to the LED

Here an L9110 fan module is used to provide a DC motor with a propeller that shows when the motor is in motion.

A table for this module's motion is attached. As can be seen if INA is LOW and INB HIGH the motor rotates in a clockwise direction. Here we turn the motor On and Off for approximately 5 seconds at a time.

The LED current is reduced by the resistor used here to approximately 2 milliamps. The LED comes On as the motor rotates and is Off when the motor is Off.

The sketch to make this all happen is shown below,

/*
Program written by: R Jordan Kreindler

Date: Oct, 2019

Running a DC motor (L9110 fan module) for delay1 ms On and Off

and turning an LED On/Off in consonance

*/


#define IOPin 23

#define LEDPin 13

#define delay1 5000 // set delay to 5 seconds

void setup() {

pinMode(LEDPin, OUTPUT);

pinMode(IOPin, OUTPUT);

}

void loop() {

digitalWrite(LEDPin, HIGH); // turn the LED On

digitalWrite(IOPin, LOW); // set INA to 0

delay(delay1); // delay delay1 ms

digitalWrite(LEDPin, LOW); // turn the LED Off

digitalWrite(IOPin, HIGH); // set INA to 1

delay(delay1); // wait delay1 ms

}

To set the value HIGH for INB, the female to male Dupont wire is directly connected to the five volt DC power supply from the USB port. The changing signal to INA is connected to IO pin 23 of the ESP32 development board used here.

This sketch as run is provided in the attached txt file.

Step 4: H Bridge

No presentation of DC motors would be complete without a mention of H Bridges. The theory behind an H Bridge is quite simple, and easy to understand. It gets its name from the configuration of its main components: 4 switching elements and a DC motor that can be diagrammed in the configuration of the capital letter ‘H’ (see photograph above).

Its operation is straightforward, if S1 and S4 are closed while S2 and S3 stay open the current flows through the motor in one direction from + to ground. If S2 and S3 are closed while S1 and S4 are open the current flows through the motor in the opposite direction from + to ground. (See attached photograph). The illustration here shows the switching elements as normally open switches, i.e., mechanical devices. Notice that these switches need to be closed in a particular fashion. If for example either switch pairs S1 and S3 or S2 and S4 were closed at the same time this would provide a short circuit path between the positive voltage and ground. Closing S1 and S2 while leaving S3 and S4 open will have no effect as S1 and S2 are connected to the same positive voltage and so no current will flow. The situation is similar if we close S3 and S4 at the same time while leaving S1 and S2 open, in this situation S3 and S4 are both connected to ground. If current is not running through the motor, as when switch S1 and S2 are closed and S3 and S4 are open or vice versa, the motor will stop. The switching elements could just as well be relays, another mechanical element, or solid state devices such as bipolar junction transistors (BJTs), or metal oxide semiconductor field effect transistors (MOSFETs). In most modern H Bridges the switching elements are solid state devices, usually MOSFETS. The advantages of MOSFETs over BJT is that they can switch current to large loads while needing only a small amount of current to switch on. In practice diodes are placed across each switching element, with the lines on the diodes facing the positive voltage. This is done so that when e.g. all switches are open after the motor has been running, the current generated by the motor, due to its collapsing magnetic field, has a path to take. However, rather than use discrete components, e.g., switches, relays, BJTs, or MOSFETs, most H Bridge board makers use integrated circuits (ICs), such as the board based on the L298 IC shown above. If you use an H Bridge module with your own Arduino sketch, it is probably an excellent idea to open all switching elements before changing direction, as this will insure a short circuit is not created even momentarily. H Bridges are found in power inverters, robots, motor controllers, etc. They are frequently used to drive a stepper motor

Step 5: DC Gear Motors

Most continuous DC motors typically run at 1,000s of revolutions per minute (RPMs). Gear motors are often used to reduce RPMs (speeds) to less than 1,000, and one can easily find gear motors with RPMs of less than 100. They use, as the name would imply, an assemblage of gears, a reduction gear train, to obtain this reduced speed. In general, the more the reduction the slower the speed. DC gear motors come in a myriad of speeds, shapes, and sizes. They are hard not to enjoy.

An excellent example of the need for a gear motor is a timepiece, such as an analog wristwatch. The motor in a wristwatch needs to provide rotations at slow speeds. For example, the second-hand rotates at only one RPM. Another example are the tires in a robot car, which also must rotate at relatively slow speeds. While the main motor, in a gear motor, may rotate at over 1,000 RPM, reduction gears allow for a much slower rotation of the output. Gear motors can provide significant torque are low RPMs. In fact, torque increases as speed slows. In general, the higher the current the higher the torque. Gear motors are found in automobiles, clocks, washing machines, drills, kitchen mixers, and in industrial equipment such as cranes, jacks, winches, conveyor belts, etc. They can change direction (just swap the leads to the motor), spin at different speeds, and stop quickly. They are often found in robots, e.g., robot cars. A word of caution: efforts to run a motor above or below its voltage range can damage the motor. If the motor will not turn the voltage is likely too low, and if it feels hot to the touch the voltage is probably too high. Gear motors can often be identified as their rotating shafts are often not aligned with the center of the main motor, to provide room for the gears, but not always (see photographs). As voltage increases the speed of the motor typically increases (see attached video). One of the videos shown here is for a DC gear motor where the voltage ranges from 2-17 volts. The higher the voltage the faster the gear motor's rotation. The voltage first goes from low to high and then back to low. The second video shows the slow speeds possible using a gear motor even with some minor changes in input voltage. The last video is of a 12v gear motor run at less than 12v, so it runs somewhat slower than it would at a full 12v.

Step 6: Vibration Motors

The first video is that of a Brush Robot that is powered by a vibration motor.

As noted in the introduction to this tutorial, DC motors are ubiquitous. They convert electrical/magnetic energy, produced by a wire carrying current in a magnetic field, to motion, and they appear in all sorts of appliances and applications, e.g., they are found in small fans, ceiling fans, air cleaners, solder fume extractors, quadcopters, small helicopters, and other drones, hand-held rotary tools, circular saws, drills, lathes, sanders, cars, robots (where they rotate tires, or move robotic arms, etc.), aquarium air pumps, Maker projects, and many other areas.

This tutorial only discusses DC motors in relation to the ESP32 development board.

The categorization of motors found here is not mutually exclusive, as there is overlap between what may initially seem like entirely different motors. Usually, this is due to the target function of these motors rather than the theory behind them.

As an example, vibration motors are continuous DC motors that have an asymmetric weight on their shaft, so they vibrate when then rotate. (See attached photo).

Step 7: DC Servo Motors

Servo motors used by hobbyists are usually relatively small and lightweight (see photographs), and generally use only the amount of current needed to move to a specific location or provide the needed torque, i.e., the turning force required by the application. Thus, they tend to be energy conservative. They are typically brushless, with from 4 to 12 poles.

Servos always have some type of feedback component, i.e., they use a closed loop system to control position. They usually have a fairly constant torque throughout their range. In general, the higher the acceptable voltage, the higher the torque, and the greater the speed of the servo. They are used in a variety of applications, e.g., robotics, tools, auto focusing cameras, automatic door opening, solar tracking, antenna orientation, home automation, etc. Simply put, they make our lives easier.

The major components of a servo are usually contained inside its housing, and generally include a motor, potentiometer, electronic circuitry, and a gear train.

The important elements of all servo motors are their closed loops which get feedback from an encoder (also known as a shaft encoder or rotary encoder, that generally produces digital output) or a resolver (for measuring angular rotation, an analog component).

Encoders can be categorized as incremental (or quadrature) or absolute, where each location has it own digital code. Servos with absolute encoders may be preferred owing to their greater accuracy compared to servos with incremental encoders.

Servo motors can be brushed or brushless. Although brushless motors tend to be more costly and complex, since their commutation is done electronically rather than mechanically. They typically require less maintenance as they eliminate the need, and cost, to repair "brushes".

The internal motor of a servo spins rapidly, and actually is limited in torque, but the reduction gear train changes that rapid rotation to a slower value. This allows the servo to move at a slower speed but with higher torque. The motor spins the fastest with no load, as can be seen in the attached illustration of a motor torque-speed curve above. The symbol for this no load speed is frequently shown as the lowercase Greek omega followed by an ‘n’ subscript.

In general, the higher the voltage the greater the speed of a motor. There is a tradeoff between speed and torque. The curve (straight line graph) shown here is only for illustration, as an actual torque-speed curve depends on the type of motor, and the changes in electrical input. However, torque-speed curves generally can be approximated by a linear function, as can torque and current.

Power for a motor is defined as torque multiplied by angular velocity. We can see that the maximum power from a motor occurs at the point on the curve (here a line), where the area of a rectangle drawn to a point on the line from both axes is greatest. This can be calculated directly by constructing rectangles from points on the line to the two axes. Then the areas of each of these rectangles will be torque x speed, i.e., motor power. So, the rectangle with the greatest area will identify the point at which a motor has its greatest power. This point should not be confused with the efficiency of a servo motor.

Efficiency is the division of the power obtained from the motor compared to the power put into the motor. It is often represented by the lowercase Greek letter eta, η. This value is always less than one. Motor efficiency typically ranges from 50% to 90%. However, high inefficiency should be avoided as it is not only responsible for power loss, but can result in heat generation. Too much heat can have a deleterious effect on a motor. Servo motors tend to cost a bit more than the other motors discussed here. They typically have a range of motion from 90-180 degrees. Some hobby and robotics servos are not capable of turning beyond 180 degrees. This is often due to a mechanical stop built into one component of the servo’s gear train.

However, some servos are continuous. They can rotate completely, i.e., a full 360 degrees. (See attached video). As another example, the first photograph of this type of servo, weighs 38 gm and runs at any DC voltage from 4.8-6v.

The external component that connects to the servo's “shaft” is called its horn, which is typically a circle, a single arm, a simple cross (four arms), or a component with six equally spaced arms.

The servo turns, typically using an internal pulse width modulator to send PWM signals to its motor, to the position desired. The stalling torque of a servo is, as the name implies, the amount of torque that must be applied against the direction of servo movement to cause the servo to stall, i.e., for the motor's speed to become zero. This is often represented in motor datasheets by the lowercase Greek letter tau sub-zero or tau sub-s. As noted previously, torque is equal to the length times the force. It only takes half the stalling torque to stall a servo motor using an extension from the servo's shaft that is twice the length/distance from the shaft. That is, the nearer we are to the center of the servo motor's shaft the greater the torque required to produce stalling.

Servos are often used in applications requiring fast acceleration and deceleration, and these capabilities result in them frequently being found in industrial automation equipment, and in some of the areas previously mentioned. The first two pictures show the gear train inside one of the popular hobby servo motors, the SG90. This is an inexpensive motor; it contains a plastic gear train, as can be seen, and so is not as durable as, e.g., the MG995 (see photographs), a servo containing metal gears.

Owing to the presence of heavier gears in the MG995, some users have experienced problems with startup speed and accuracy. Fortunately there is now a later/upgraded version of this servo, the MG996R (see photographs), which contains improved electronics and gearing. Although it is slightly heavier, it seems to be more accurate with relatively high torque, and is only very slightly more costly.

If a hobby servo with a plastic gear train is stalled, this can result in some gears in the gear train getting damaged, i.e., becoming stripped. Gears on inexpensive servos are often made of plastic or nylon. More expensive servos, such as those mentioned above, often contain gears made of various metals, including titanium (to produce a lower weight, while still maintaining strength).

There is a "hardened" version of the SG90, the MG90S, which contains metal gears (MGs), but its price is higher than the plastic-geared SG90.

Another alternative to the SG90 is the SG92R. This 9gm servo has carbon fiber glass gears and 2.5kg/cm of torque at 4.8 DC volts, as opposed to the SG90's 1.6kg/cm of torque at the same voltage. The major problem is that, at the time of this article, it was about 75% more expensive. Except for this, it could be considered a replacement for the SG90.

Less expensive servos usually have the rotor turn inside of a bushing rather than a ball bearing mount. For more expensive servos the opposite is usually true. There are, in fact, dual ball bearing servos to provide even more longevity (see e.g., the attached photograph of the DES 677 BB, a dual ball bearing servo). For important projects, based on prior experience, I always use the longest lasting motors I can, i.e., ones with ball bearings.

However, an Instructables reader, GuidoSan, was kind enough to leave a comment for my Arduino and DC motors tutorial, noting that "bushings hold up surprisingly well as long as you don't have side thrust ... [so] don't hesitate to use bushed motors when you don't have side thrust." He suggests.

The inside mechanical components of a servo can wear. So, if a servo starts to become "jittery", it is probably time to replace it.

There are analog and digital servos. A digital servo can generally operate at faster speeds, and can respond more quickly than an analog servo. A digital servo is also smoother and is typically more accurate. (See attached photographs for pictures of digital servos). However, digital servos are more expensive and can take more current than analog servos, but may be the servos of choice if current needs are met and you can afford them.

Some servos are coreless, and these servos would typically be lighter and more responsive. Some examples of these types of servos can be seen in the attached photographs.

The basic operating principle for a DC servo motor is similar to that of other DC motors. Like other motors they can be wired in a series or parallel configuration, or have permanent magnets.

Modern technology has helped strengthen permanent magnet motors. Specifically, the development of Neodymium and other rare earth magnets has led to increases in magnetic strength, possibly on the order of 300% for N52 neodymium magnets. (As an aside, for motors to be operated in very high temperatures, N42 high temperature Neodymium magnets may be a better choice).

Today servos are often found specified with values such as 9 grams, e.g., the common SG90. This gram specification is the weight of the servo, and does not including the weight of the wires to/from the motor. That is, the value in grams is usually the servo's weight, not its torque. One should expect metal gear servos to be constructed more sturdily and to weigh more than their plastic gear cohorts, and that is the case; e.g., the MG995 weighs approximately 48 grams, as can be seen in the attached photographs.

Servos are also available that are linear instead of rotary. These linear "actuators" often contain a worm gear to change their rotary motion to linear motion. (See photographs).

Step 8: Sketch Using an ESP32 Development Board and a Servo Motor

The supplies we need for this project are:

- An SG90 motor (I also used an SG90 servo mount bracket there but that is not necessary)

- a 10K rotary potentiometer (almost any rotary potentiometer will do)

- an MB-102 solder-less breadboard

- an ESP32 development board (the one I used is not a requirement)

- four (4) female to male Dupont wires

- five (5) male to male Dupont wires

- a USB cable from your computer to the ESP32 board

In this project both a potentiometer and SG90 servo motor are connected to an ESP32 development board. The two end wires from the potentiometer are connected to +5 volts and ground. Reading the ‘wiper’ output of the potentiometer, while its knob is being changed, produces output voltages ranging from approximately zero to 5v.

In the sketch the output of the potentiometer’s 'wiper’ is read, using the analogRead() function. The value that is read is converted to a discrete values by one of the analog-to-digital convertors (ADCs) available on any of the ESP32's ADC pins. These discrete values represent voltages between zero and five volts,

The servo motor is positioned using the ‘write()’ function (after mapping to the appropriate angles), which is contained in the code for the servo object. The servo is moved between zero and 180 degrees, depending on the value read from the potentiometer’s ‘wiper’, and converted using the ADC converted value mapped in the sketch.

In this sketch the pot controls the position of the SG90 servo motor. First a servo object is created and then assigned to an ESP32 IOPin. The potentiometer's wiper is assigned to ESP32 IOPin36, as we want to use one of the ADCs available on the ESP32 development board pins. The pot is read and the servo positioned according to that reading.

An ESP32 development board provides 12-bit Analog to Digital Converters (ADCs). It provides this analog to digital conversion with 4096 (0-4095) discrete digital values. This compares to the 10-bit ADC capabilities of the Arduino UNO with 0-2^10th or 1024 (0-1023) discrete values. This is, 0 to 1023 versus 0 to 4095.

According to Espressif documentation "[t]he ADC driver API supports ADC1 (8 channels, attached to GPIOs 32 - 39), and ADC2 (10 channels, attached to GPIOs 0, 2, 4, 12 - 15 and 25 - 27)". However, ADC2 has some limitations due to a number of issues. such as the use of WiFi etc, and so these pins are used only in restricted circumstances for their ADC capabilities.

There are additional functions that can be used with the ADC pins. They are not typically needed, and are not used in the example below.

The ADC integer values can be read with the command,

analogRead(ADC_GPIO);

where ADC_GPIO is one of the pins supporting ADC.

GPIO pins 0, 2, 4, 12, 13, 14, 15, 25, 26, 27 should not be used if WiFi is being used, or you may have a problem getting readings from these pins.

Note the 5 Volt DC pin (sic), which is not a GPIO pin, can be used as a power source as long as the current does not exceed that which can be provided by the computer's USB cable. In my case this 5 Volt (sic) supply provides 4.85 volts DC. However, my current requirement to use the SG90 servo does not exceed the 500 mA available from my desktop computer's USB port, I am not using a laptop computer, so cannot safely say if this would be less if that was used.

I have found no problem with this set-up, although I do not know if it is due to the board I am using. However, I tried the 5v pin on a different ESP32 development board with the same problem-free results, so my conclusion is that it appears the board does not matter (at least for the two boards I tested).

The SG90's positioning pin takes considerably less than one mA.

To see the sketch exactly as written please download the text file.

----------Sketch----------

/*
Program written by: R Jordan Kreindler

Date: Oct 2019 Potentiometer controls the servo position

The angle of the servo is shown on the display monitor

*/

#include // use Servo library for ESP32

// include less than and greater than brackets around ESP32Servo.h

// as this site drops the brackets and text between them

Servo servo1; // create a servo object

#define potWiper 36

#define servoPin 19

#define twoTo12th 4095

#define delay1 150

int intValue;

void setup() {

servo1.attach(servoPin); // attach the servo to servoPin

Serial.begin(9600); // setup display monitor (work at 9600 baud) }

void loop() {

intValue = analogRead(potWiper); // read value at pin potWiper pin

intValue = map(intValue, 0, twoTo12th, 0, 180); // convert value read to value from 0 to 180

servo1.write(intValue); // move the servo to position intValue

Serial.print("Servo Angle = "); // display the

Serial.println(intValue); // servo angle on display monitor

delay(delay1); // allow the servo time to get to position

}

Step 9: Afterwards

If you have come to this point - congratulations. You should now have a basic understanding of some of the capabilities of the ESP32 development board when used with some of the DC motors covered in this tutorial. I hope you found this Instructable interesting and of value. I look forward to covering stepper DC motors in Part 2.

Sadly, the instructables.com "Favorited" counter was down when this article was posted, but according to email I received from instructables, it is now back up.

It should be obvious, that this tutorial, just "scratches the surface" of some DC motors and ESP32 development boards. Each of the DC motors covered here could probably have its own multi-part tutorial. If you have any comments, suggestions, or questions related to this tutorial, please be kind enough to add your comments below. If you have any thoughts or questions, related to ESP32 development boards and motors in general, but not covered in this tutorial, they may be covered in the next Part. However, if you have any suggestions for how I could improve this or would like to contact me, I would be pleased to hear from you. You can contact me at transiintbox@gmail.com. (Please replace the second 'i' with an 'e' to contact me).