Lab: Controlling a Stepper Motor With a Step and Direction Driver

Introduction

In the stepper motor and H-bridge lab, you learned how to control a stepper motor with a dual H-bridge driver, specifically the TB6612FNG. This is not the only driver for controlling a stepper. Step & direction stepper drivers offer a simpler approach, from the microcontroller side. They have just two control pins, one for step and one for direction. They also feature configuration pins that let you set the step pin to move the motor a full step, a half step, or less. This is called microstepping, and you can find stepper drivers that will work as low as 1/256th of a step. This allows finer control over the stepper motor. In this lab you’ll learn how to use a step & direction controller to control a stepper motor.

What You’ll Need to Know

To get the most out of this lab, you should be familiar with the following concepts. You can check how to do so in the links below:

Things You’ll Need

The motor shown in the images here is a 5V Small Reduction Stepper Motor, 32-Step, with 1:16 Gearing. This motor is a useful starter motor for steppers because it can run on the current and voltage supplied by your Arduino without an external power supply. The driver is a STMicro STSPIN220 on a Pololu breakout board. There are a number of other step & direction motor drivers available if the STSPIN220 doesn’t meet your needs. Control for all of them will be similar to what you see below. In fact, Pololu makes a number of carrier boards for different step & direction drivers, all with the same pin layout. The principles in this lab, and the library used, will work with other stepper motors and step & direction drivers as well, though you will have to make some modifications depending in which parts you are using.

Good Safety Practice

When you’re working with motors, you’re often dealing with high voltage, high current, or both. You should be extra careful never to make changes to your circuit while it is powered. If you need to make changes, unplug the power, make your changes, inspect your changes to be sure they are right, and then reconnect power.

It’s also a good idea to disconnect your motor from your circuit before uploading new code to your microcontroller. Often the current draw of the motor will cause the microcontroller to reset, and cause uploading problems. To avoid this, disconnect your motor before uploading, and reconnect it after uploading.

Because motors consume a lot of current when they start up, it’s common to add a decoupling capacitor of 10-100 µF near the voltage input to your driver and/or microcontroller. You’ll see this in the figures below. It will smooth out any voltage changes that occur as a result of the motor’s changing current consumption.

Prepare the breadboard

Connect power and ground on the breadboard to power and ground from the microcontroller. On the Arduino module, use the 5V or 3.3V (depending on your model) and any of the ground connections, as shown in Figures 9 and 10.

An Arduino Uno on the left connected to a solderless breadboard, right.
Figure 9. Breadboard drawing of an Arduino Uno on the left connected to a solderless breadboard on the right

Figure 9 shows an Arduino Uno on the left connected to a solderless breadboard, right. The Uno’s 5V output hole is connected to the red column of holes on the far left side of the breadboard. The Uno’s ground hole is connected to the blue column on the left of the board. The red and blue columns on the left of the breadboard are connected to the red and blue columns on the right side of the breadboard with red and black wires, respectively. These columns on the side of a breadboard are commonly called the buses. The red line is the voltage bus, and the black or blue line is the ground bus.


Arduino Nano on a breadboard.
Figure 10. Breadboard view of an Arduino Nano mounted on a solderless breadboard.

Made with Fritzing

As shown in Figure 10, the Nano is mounted at the top of the breadboard, straddling the center divide, with its USB connector facing up. The top pins of the Nano are in row 1 of the breadboard.

The Nano, like all Dual-Inline Package (DIP) modules, has its physical pins numbered in a U shape, from top left to bottom left, to bottom right to top right. The Nano’s 3.3V pin (physical pin 2) is connected to the left side red column of the breadboard. The Nano’s GND pin (physical pin 14) is connected to the left side black column. These columns on the side of a breadboard are commonly called the buses. The red line is the voltage bus, and the black or blue line is the ground bus. The blue columns (ground buses) are connected together at the bottom of the breadboard with a black wire. The red columns (voltage buses) are connected together at the bottom of the breadboard with a red wire.

How the Stepper Motor Works

A stepper motor is basically two motor coils in one motor, which allows you to turn the motor in steps. For more on this, see this stepper motor page.

The motor shown in this lab, a 5V Small Reduction Stepper Motor, 32-Step, with 1:16 Gearing, is typical of a class of stepper motors you can find using the designation 28BYJ-48. They come in a few varieties. There are 5V and 12V models, and there are versions like the one shown here, that have a gearbox on the top to increase their torque and increase the number of steps per revolution. The un-geared models have as few as 32 steps per revolution. This model has 32 steps per revolution and a 1/16 reduction gear box, giving it 32 * 16, or 512 steps per revolution. You can find models with an even higher reduction as well.

A stepper motor like this one has two coils to control it as shown in Figure 11. Each coil has a center connection as well, and the center connections are joined together, which is what makes this a unipolar stepper. If you don’t connect the center connection, then the motor will work like a bipolar stepper, each coil operating independently. This is how you’ll use it for this exercise. Each coil will connect to one control channel of the motor driver. The pink and orange wires are connected to the first coil. They will connect to one channel of the motor driver, while the yellow and blue wires are the other coil, and will connect to the other channel of the bridge (channel B). In this case, the red wire, pin 1, will not be used.

Schematic drawing of a stepper motor. A circle represents the motor, and two coils to the left and bottom of the circle represent the coils. The ends of the left coil are labeled pink and orange. The ends of the bottom coil are labeled yellow and blue. The middles of both coils are connected together, and labeled red. The red connection will not be used in this example.
Figure 11. Schematic drawing of a stepper motor.

A bipolar stepper motor typically omit the red wire and just have two independent coils. A bipolar model like this 3.9V NEMA-8 stepper from Pololu would also work with this lab.

Check the Motor Coils’ Resistance

The wiring pattern in Figure 11 is typical, for the 28BYJ-48 motors. Nonetheless, it’s a good idea to check the wiring by measuring the coil resistance. The motor shown here has a coil resistance (impedance) of about 42 ohms. For a bipolar motor, each pair of coils (e.g. blue and yellow, orange and pink) would give you the motor’s rated coil resistance. Since this is a unipolar motor, you should read approximately 22-24 ohms across red and each of the other wires, and about 42-45 ohms across each pair (blue-yellow and orange-pink).

The sequence of the wires on the motor’s connector may vary from one manufacturer to another, so it’s a good idea to measure the resistance, then write down the pin order for reference later on.

How The Motor Driver Works

The STSPIN220 can handle a motor  supply voltage from 1.8 to 10V, and  it operates on a logic voltage of 3.3–5V. It can control an output current of 1.1A per coil.

The motor driver has the following pins. The pin numbers shown here are for the Pololu breakout board. The pins are numbered here in a DIP fashion, in a U-shape from top left to bottom left, then bottom right to top right. The list below describes the pins in numeric order.

  1. Enable – enables the driver when you take it LOW  and disables it when you take it HIGH. The breakout board pulls this pin LOW by default, so if you don’t connect it, your motor should work fine.
  2. Mode 1 -Configuration pin for microstepping
  3. Mode 2 – Configuration pin for microstepping
  4. 1 – not connected by default
  5. 2 – not connected by default
  6. Standby – Puts the the driver in a low-power standby mode and disables the motor when you take it LOW.
  7. Step/Mode 3 -When you pulse this pin HIGH then LOW, the motor moves forward one step. Also functions as a configuration pin for microstepping.
  8. Dir/Mode 4 – When you pulse this pin HIGH, the motor in one direction when you pulse the step pin. When you take it LOW, it moves in the other. Also functions as a configuration pin for microstepping.
  9. Ground – ground
  10. Vcc – Logic voltage. Connect this to the Vcc of your microcontroller, for example 5V for an Uno or 3.3V for a Nano 33 IoT
  11. A1 – Motor output coil 1
  12. A2 – Motor output coil 1
  13. B2 – Motor output coil 2
  14. B1 – Motor output coil 2
  15. Ground – ground
  16. VMOT – motor voltage supply input, 1.8-10V.

Connect the Motor Driver and Set the Current Limit

Many step and direction drivers like the STSPIN220 have an adjustable current limit built into the driver. This lets you set the maximum output current to match the current your motor needs. Pololu has a video explaining this process. This is important, because if you don’t set the current limit correctly, you risk damaging the driver and the motor. The details follow here. You have to know your motor’s desired current, then you use a formula to work out the value of a current limiting resistor for the driver.

If you have the motor’s current from the datasheet (110mA for the motor listed above), then you’re all set. If you don’t, you can calculate it from the motor’s voltage and the resistance of its coils. First, measure the resistance of one coil, as explained in the stepper motor lesson. Remember that current, voltage, and resistance are all related using the formula

Voltage = Current * Resistance

For example, if your motor’s coil resistance reads 45.4 ohms, and it runs on 5 volts, then the current = 5 / 45.4, or about 110 mA.

To prepare for this, connect the STSPIN220 board as shown in Figures 12 and 13. Do not connect a motor yet. You’re powering the board up just so you can set the current limit.

The board is mounted straddling the center row of a breadboard, and the following pins on the STSPIN220 are connected:

  • Pin 1, Enable – connected to the ground bus on the left side of the breadboard
  • Pin 9, Ground – connected to the ground bus on the right side of the breadboard
  • Pin 10, Vcc – Logic voltage. Connected to the voltage bus on the right side of the breadboard
  • Pin 15, Ground – connected to the ground bus on the right side of the breadboard
  • Pin 16, VMOT – Connected to the voltage bus on the right side of the breadboard. If you were using an external power supply for a higher voltage stepper motor, you would connect this to the positive terminal of the external supply.
Breadboard view of an SDSPIN220 stepper motor driver on a breadboard, powered by 5V from an Arduino Uno.
Figure 12. Breadboard view of an SDSPIN220 stepper motor driver on a breadboard, powered by 5V from an Arduino Uno. Multimeter leads are touching the trimmer pot of the STSPIN220 and the ground pin, to read the current limiting voltage.
Breadboard view of an SDSPIN220 stepper motor driver on a breadboard, powered by 3.3V from an Arduino Nano 33 IoT.
Figure 13. Breadboard view of an SDSPIN220 stepper motor driver on a breadboard, powered by 3.3V from an Arduino Nano 33 IoT. Multimeter leads are touching the trimmer pot of the STSPIN220 and the ground pin, to read the current limiting voltage.

Pololu makes its step & direction driver boards with a built-in trimmer potentiometer to act as a current limiting resistor. It’s usually at the bottom of the board. Calculating the value of this resistor is explained in detail in section 6 of the STSPIN220 data sheet. Pololu have summarized it in a formula below.

To set the current limit, you power up the driver without a motor attached and measure the voltage between this trimmer pot and ground. Then you turn the trimmer pot until you read the reference voltage for the current limit, or VREF. In Figures 12 and 13 there are multimeter probes shown, used to measure voltage. The red probe (positive) is touching the trimmer pot on the STSPIN220 and the black probe (negative) is touching pin 9, the ground pin. Set your multimeter to read voltage in the range of your Vcc (3.3 to 5V), then touch the leads to the trimmer pot and to ground as shown in figures 12 and 13. You should get a voltage between zero and Vcc. Then turn the pot with a small screwdriver until you read your desired VREF.

For the STSPIN220, the current limit formula is as follows:

Current= VRef * 5

Rearranging that to get the voltage on the trimmer pot:

VRef = Current / 5

So, if your desired current is 110 mA, or 0.11 A, then VREF = 0.11 / 5, or 0.022V. Turn your pot until the voltage reads that value (or whatever you calculated it to be for your motor) and you’re ready to go. The trimmer pot is small and difficult to turn, so try to get in the general range of your VREF. You probably won’t get it exactly. If you find the motor or the driver is excessively hot while running (if you can’t touch it comfortably) then you should re-adjust the trimmer pot to get closer to your proper VREF.

You can now disconnect from your power supply, add the motor, and reconnect to program the microcontroller.

Connect the Motor

This motor nominally runs on 5 volts. It will run as low as 3.3 volts if you give it enough current (about 110 mA). It can run on the current supplied to an Uno or Nano 33 IoT’s USB connection. Ideally, though, you should run it from an external power supply, as described later in the lab.

To finish your stepper motor circuit, connect the motor according to Figures 14 through 16.

Table 1 below describes the pin connections for the circuit. The STSPIN220 is still connected to the breadboard as shown previously in figures 12 and 13, but now the motor’s coils are connected to pins 11 – 14 of the motor driver and the driver’s step and direction pins (pins 7 and 8 respectively) are connected to digital output pins 2 and 3 of the Arduino, respectively. The two mode pins (pins 2 and 3) are connected to ground, and the standby pin (pin 6) is connected to Vcc through a 10-kilohm resistor.

Motor Driver Physical pin numberPin functionCircuit Connection
1EnableGround
2Mode 1Ground
3Mode 2Ground
41not connected
52not connected
6Standby10-kilohm resistor to Vcc
7StepArduino digital pin 2
8DirectionArduino digital pin 3
9GroundGround
10VccArduino Vcc (3.3 or 5V)
11A1Motor coil 1
12A2Motor coil 1
13B2Motor coil 2
14B1Motor coil 2
15GroundGround
16VMOTArduino Vcc if using USB power. Arduino Vin if using an external power supply.
Table 1. STSPIN220 connections to Arduino circuit
Schematic drawing of a stepper motor and STSPIN220 motor driver connected to an Arduino. The connections are described in the body of this page.
Figure 14. Schematic diagram of an STSPIN220 stepper motor driver and stepper motor connected to an Arduino.
Breadboard drawing of a stepper motor and STSPIN220 motor driver connected to an Arduino Uno. The connections are described in the body of this page.
Figure 15. Breadboard diagram of an STSPIN220 stepper motor driver and stepper motor connected to an Arduino Uno.
Breadboard drawing of a stepper motor and STSPIN220 motor driver connected to an Arduino Nano 33 IoT. The connections are described in the body of this page.
Figure 16. Breadboard diagram of an STSPIN220 stepper motor driver and stepper motor connected to an Arduino Nano 33 IoT.

Made with Fritzing

Once you have the motor and the driver connected, you’re ready to program the microcontroller.

Program the microcontroller

You don’t need a library for a step and direction controller, though there are several out there, to do things like ramp the speed up and down, ease in and out, and so forth. All you need to do to move the motor is to set the direction pin, and to pulse the motor high then return to low. A 3-millisecond pulse will do the job reliably. If you need more speed, you can try reducing this down to 2 or even 1ms, once you know the motor’s working properly.

Regardless of what motor driver you are using, the first thing you should do after wiring up a stepper motor is to write two test programs, one to test if it’s stepping, and one to test if it can rotate one revolution in both directions.

For your first program, it’s a good idea to run the stepper one step at a time, to see that all the wires are connected correctly. If they are, the stepper will step one step forward at a time, every half second, using the code below.

const int stepPin = 2;
const int dirPin = 3;

void setup() {
  pinMode(stepPin, OUTPUT);
  pinMode(dirPin, OUTPUT);
}

void loop() {
  // motor  direction: 
  digitalWrite(dirPin, HIGH);
  // step the motor one step:
  digitalWrite(stepPin, HIGH);
  delay(3);
  digitalWrite(stepPin, LOW);
  // wait half a second:
  delay(500);
}

Once you’ve got that working, try making the stepper move one whole revolution at a time using the code below:

const int stepPin = 2;
const int dirPin = 3;
const int stepsPerRevolution = 512;
bool direction = HIGH;

void setup() {
  pinMode(stepPin, OUTPUT);
  pinMode(dirPin, OUTPUT);
}

void loop() {
  // motor  direction:
  digitalWrite(dirPin, direction);
  // move one revolution :
  for (int step = 0; step < stepsPerRevolution; step++) {
    // step the motor one step:
    digitalWrite(stepPin, HIGH);
    delay(3);
    digitalWrite(stepPin, LOW);
    delay(1);
  }
  // wait half a second:
  delay(500);
  // change direction:
    direction = !direction;
}

When you run this code, you should see the motor turn one revolution, wait half a second, then turn one revolution in the other direction.

My motor’s only going one direction!

If you find that the motor only turns in one direction, you probably have the pin connections wrong. It could be that you got the order wrong. Try rearranging the order of the pins. Disconnect power each time you try changing your connections. First, try swapping the two pins on each coil (e.g. blue and yellow, pink and orange) and run it again. If that fails, swap one wire from one coil for one wire from the other coil. Keep trying variations until your motor goes around in one direction, then goes around in the opposite direction.

Unipolar Stepper Control

The steps above showed you how to control your motor as a bipolar stepper, but the motor shown is actually a unipolar motor. Remember the red wire you didn’t connect? That wire connects the two coils and can act as a common power source or ground wire. To use the motor as a unipolar motor, try connecting that wire (wire 1) of the motor to the Vin power supply from the DC power jack. You should see that there’s not a lot of difference.

Attach Something to the Stepper

If you want to mount an arm or pointer to the stepper motor, you need to make a hole for the pointer that fits the shaft perfectly. You could measure this with a caliper. There are also collars and shaft couplers that you can buy for various stepper motors that will allow you to attach things to your stepper. ServoCity has a number of examples, as does Pololu. To pick a good shaft adapter, you need to know what you’re going to do with the stepper, and what the size and shape of the shaft is.

Using an External Power Supply

Although the example shown above used a motor that can run on the voltage and current supplied to the Arduino via USB, this is not the norm for stepper motors. Most of the time you need to use an external power supply. You should match your supply to your motor. Keep in mind that if you have, say, a 12-Volt power supply and a 5-volt motor, you can add a 5-volt voltage regulator, as shown in the breadboard lab. Figures 17 through 19 show a few different options for powering different stepper motors.

Figures 17 and 18 show how you might power a 9V stepper motor from an Uno or Nano, respectively. Figures 17 and 18 show a NEMA-17 stepper motor. Figure 19 shows how you could power a 5V stepper from a Nano, using a 9-12V DC power supply for the Nano and a 5V voltage regulator for the motor and motor driver.

The STSPIN220 can run motors from 1.8-10V. If you need to run a motor at a voltage greater than 10V, there are several other step and direction motor drivers that can do the job. For example, the A4988 is similar to the STSPI220, but has a motor voltage range of 8-35V. Many of them come with the same or similar pin arrangements as well. For a comparison, see the Step & Direction Drivers compared table in the Controlling Stepper Motors page of this site.

It’s worth noting that when the Nano 33 IoT is powered from its Vin pin, the USB connection no longer powers the Nano. Instead, the Vin powers the Nano. You can still get 3.3V from the 3.3V out pin (pin 2), however.

The exact voltage and amperage requirements for a stepper motor circuit will depend on the motor you are using. These images show a few options that can work, but you should adapt them depending on the particular electrical characteristics of your motor.

Breadboard view of an STSPIN220 running a 9V stepper motor from an Arduino Uno.
Figure 17. Breadboard view of an STSPIN220 running a 9V NEMA-style stepper motor from an Arduino Uno. The circuit is similar to Figure 15 above, but in this image the STSPIN220’s VMOT pin (pin 16) is connected to the Uno’s Vin pin. The whole circuit would be powered by a 9V DC power supply connected to the Uno’s power jack.
Breadboard view of an STSPIN220 running a 9V stepper motor from an Arduino Nano 33 IoT.
Figure 18. Breadboard view of an STSPIN220 running a 9V NEMA-style stepper motor from an Arduino Nano 33 IoT. The circuit is similar to Figure 16 above, but in this image an external power jack is connected to the Nano’s Vin pin (pin 15) and grounded to its ground pin (pin 14). The STSPIN220’s VMOT pin (pin 16) is connected to the Nano 33 IoT’s Vin pin (pin 15) and the positive terminal of the power jack. The Nano would then need to be powered by a 9V DC power supply connected to the power jack.
Breadboard view of an STSPIN220 running a 5V stepper motor from an Arduino Nano 33 IoT with an external voltage regulator
Figure 19. Breadboard view of an STSPIN220 running a 5V stepper motor from an Arduino Nano 33 IoT with an external voltage regulator. The circuit is similar to Figures 16 and 18 above, but in this image an external power jack is connected to the Nano’s Vin pin (pin 15) and grounded to its ground pin (pin 14). A 7805 5V voltage regulator has been added to the breadboard in three rows just above the STSPIN220 on the right side of the breadboard. The regulator’s input pin is closest to the top of the board, and is connected to the Nano’s Vin pin and the positive terminal of the power jack. Its ground is in the middle, and is connected to the right side ground bus of the breadboard. Its output is closest to the bottom and is connected to the STSPIN220’s VMOT pin (pin 16). The whole circuit could be powered by a 9-12V DC power supply connected to the power jack. The regulator would ensure that the motor and the STSPI220 always get 5V and up to 1A.

Advanced Features: Speed Control, Microstepping, and G-code

This lab has covered the basics of step & direction drivers. These drivers are capable of much more control, depending on how you wire them and how you program the microcontroller to control them.

Controlling the speed of a motor is managed by changing the timing between steps. You can manage this in your own code by changing the delay after each step pulse, or you can use a library like accelStepper which has options for speed control.

Microstepping allows you to control a stepper in 1/2, 1/4, 1/8, or as low as 1/256 step increments. The number of microsteps depends on the driver you are using. You set the microstep increment using the mode pins. Pololu’s documentation for the STSPIN220 covers the details of this for this board (see the section titled Step (and microstep) Size). Other step & direction boards will have similar instructions.

Step and direction motor controllers are often used in DNC machines like 3D printers and 3D mills. These machines have a communication format called G-code which describes how the machine should move to print or carve a shape. The GRBL library for Arduino translates G-code into a series of stepper motor movements. There are many sites which explain this in more depth, like the one at this link.

Applications

Stepper motors have lots of applications. One of the most common is to make a tw0- or three-axis gantry for CNC plotters, printers, and mills. A gantry is a structure on which you mount motors and the equipment that they are moving in order to achieve a task. Evil Mad Science’s AxiDraw is a good two-axis example. You can also use steppers to create animation in art projects, as seen in Nuntinee Tansrisakul’s Shadow through Time. Heidi Neilson’s Moon Arrow is another example that uses stepper motors and geolocation tools to make an arrow that always points at the moon.

Lab: Controlling a Stepper Motor With an H-Bridge

This lab shows you how to set up a unipolar stepper motor using an H-Bridge.

Introduction

Stepper motors are motors that have multiple coils in them, so that they can be moved in small increments or steps. The common feature to all stepper motors is that they have two coils in the motor rather than one. You control the stepper by energizing one coil, then reversing its polarity, then doing the same to the other coil. To do this, you can use a dual H-bridge driver like the TB6612FNG that you used in the DC motors and H-bridge lab. This lab shows you how to set up stepper motor using an H-Bridge.

What You’ll Need to Know

To get the most out of this lab, you should be familiar with the following concepts. You can check how to do so in the links below:

Things You’ll Need

The motor shown in the images here is a 5V Small Reduction Stepper Motor, 32-Step, with 1:16 Gearing. The driver is a Toshiba TB6612FNG. There’s a  Sparkfun breakout board, an Adafruit breakout board, and a Pololu breakout board for this part as well. The principles in this lab, and the library used, will work with other stepper motors and dual H-bridge drivers as well, though you will have to make some modifications depending in which parts you are using.

Good Safety Practice

When you’re working with motors, you’re often dealing with high voltage, high current, or both. You should be extra careful never to make changes to your circuit while it is powered. If you need to make changes, unplug the power, make your changes, inspect your changes to be sure they are right, and then reconnect power.

It’s also a good idea to disconnect your motor from your circuit before uploading new code to your microcontroller. Often the current draw of the motor will cause the microcontroller to reset, and cause uploading problems. To avoid this, disconnect your motor before uploading, and reconnect it after uploading.

Because motors consume a lot of current when they start up, it’s common to add a decoupling capacitor of 10-100 µF near the voltage input to your driver and/or microcontroller. You’ll see this in the figures below. It will smooth out any voltage changes that occur as a result of the motor’s changing current consumption.

Prepare the breadboard

Connect power and ground on the breadboard to power and ground from the microcontroller. On the Arduino module, use the 5V or 3.3V (depending on your model) and any of the ground connections, as shown in Figures 9 and 10.

An Arduino Uno on the left connected to a solderless breadboard, right.
Figure 9. Breadboard drawing of an Arduino Uno on the left connected to a solderless breadboard on the right

Figure 9 shows an Arduino Uno on the left connected to a solderless breadboard, right. The Uno’s 5V output hole is connected to the red column of holes on the far left side of the breadboard. The Uno’s ground hole is connected to the blue column on the left of the board. The red and blue columns on the left of the breadboard are connected to the red and blue columns on the right side of the breadboard with red and black wires, respectively. These columns on the side of a breadboard are commonly called the buses. The red line is the voltage bus, and the black or blue line is the ground bus.


Arduino Nano on a breadboard.
Figure 10. Breadboard view of an Arduino Nano mounted on a solderless breadboard.

As shown in Figure 10, the Nano is mounted at the top of the breadboard, straddling the center divide, with its USB connector facing up. The top pins of the Nano are in row 1 of the breadboard.

The Nano, like all Dual-Inline Package (DIP) modules, has its physical pins numbered in a U shape, from top left to bottom left, to bottom right to top right. The Nano’s 3.3V pin (physical pin 2) is connected to the left side red column of the breadboard. The Nano’s GND pin (physical pin 14) is connected to the left side black column. These columns on the side of a breadboard are commonly called the buses. The red line is the voltage bus, and the black or blue line is the ground bus. The blue columns (ground buses) are connected together at the bottom of the breadboard with a black wire. The red columns (voltage buses) are connected together at the bottom of the breadboard with a red wire.

Made with Fritzing

How the Stepper Motor Works

A stepper motor is basically two motor coils in one motor, which allows you to turn the motor in steps. For more on this, see this stepper motor page.

The motor shown in this lab, a 5V Small Reduction Stepper Motor, 32-Step, with 1:16 Gearing, is typical of a class of stepper motors you can find using the designation 28BYJ-48. They come in a few varieties. There are 5V and 12V models, and there are versions like the one shown here, that have a gearbox on the top to increase their torque and increase the number of steps per revolution. The un-geared models have as few as 32 steps per revolution. This model has 32 steps per revolution and a 1/16 reduction gear box, giving it 32 * 16, or 512 steps per revolution. You can find models with an even higher reduction as well.

A stepper motor like this one has two coils to control it as shown in Figure 11. Each coil has a center connection as well, and the center connections are joined together, which is what makes this a unipolar stepper. If you don’t connect the center connection, then the motor will work like a bipolar stepper, each coil operating independently. This is how you’ll use it for this exercise. Each coil will connect to one control channel of the motor driver. The pink and orange wires are connected to the first coil. They will connect to one channel of the motor driver, while the yellow and blue wires are the other coil, and will connect to the other channel of the bridge (channel B). In this case, the red wire, pin 1, will not be used.

Schematic drawing of a stepper motor. A circle represents the motor, and two coils to the left and bottom of the circle represent the coils. The ends of the left coil are labeled pink and orange. The ends of the bottom coil are labeled yellow and blue. The middles of both coils are connected together, and labeled red. The red connection will not be used in this example.
Figure 11. Schematic drawing of a stepper motor.

A bipolar stepper motor typically omit the red wire and just have two independent coils. A bipolar model like this 3.9V NEMA-8 stepper from Pololu would also work with this lab.

Check the Motor Coils’ Resistance

The wiring pattern in Figure 11 is typical, for the 28BYJ-48 motors. Nonetheless, it’s a good idea to check the wiring by measuring the coil resistance. The motor shown here has a coil resistance (impedance) of about 42 ohms. For a bipolar motor, each pair of coils (e.g. blue and yellow, orange and pink) would give you the motor’s rated coil resistance. Since this is a unipolar motor, you should read approximately 22-24 ohms across red and each of the other wires, and about 42-45 ohms across each pair (blue-yellow and orange-pink).

The sequence of the wires on the motor’s connector may vary from one manufacturer to another, so it’s a good idea to measure the resistance, then write down the pin order for reference later on.

How The Motor Driver Works

The TB6612FNG motor driver can handle a motor  supply voltage up to 15V, and  it operates on a logic voltage of 2.7–5.5V. It can control an output current of 1.2A. It has two motor driver circuits, each with two logic inputs and two motor outputs. Each motor driver has a PWM input, because they are expected to be used for speed control for the motor by pulse width modulating this pin. You won’t be using the PWM pins for this exercise though. There’s also a Standby pin that you have to connect to voltage through a 10-kilohm pullup resistor to activate the driver circuits.

The motor driver has the following pins. The pin numbers shown here are for the Sparkfun breakout board. The order of the pins will be different for the Adafruit and Pololu boards. The pins are numbered here in a DIP fashion, in a U-shape from top left to bottom left, then bottom right to top right. The list below describes the pins in numeric order.

  1. VMOT – motor voltage supply input, up to 15V.
  2. Vcc – logic voltage supply  input, 2.7-5.5V
  3. Gnd – ground
  4. AO1 – A channel output 1. This is the first motor terminal for the first motor driver
  5. AO2 – A channel output 2.  This is the second motor terminal for the first motor driver
  6. BO2 – B channel output 2.  This is the second motor terminal for the second motor driver
  7. BO1 – B channel output 1.  This is the first motor terminal for the second motor driver
  8. Gnd – ground
  9. Gnd – ground
  10. PWMB – B Channel PWM Enable. This pin controls the speed for channel B, regardless of the channel’s direction
  11. BI2 – B channel input 2.  This controls B channel output 2. To control that pin, take this pin HIGH or LOW.
  12. BI1 – B channel input 1.  This controls B channel output 1. To control that pin, take this pin HIGH or LOW.
  13. Stdby – enables both drivers when you take it HIGH  and disables them when you take it LOW
  14. AI1 – A channel input 1.  This controls A channel output 1. To control that pin, take this pin HIGH or LOW.
  15. AI2 – A channel input 2.  This controls A channel output 2. To control that pin, take this pin HIGH or LOW.
  16. PWMA – A Channel PWM Enable. This pin controls the speed for channel A, regardless of the channel’s direction

Figure 12 shows the Sparkfun board, and Figures 13 and 14 show the Pololu board front and back. The Pololu board is labeled on the back. You can see that both boards have the same pins, even though the layouts are different. Click on any of the images to see them larger.

Photo of a Motor Driver (H-bridge), model TB6612FNG
Figure 12. Motor Driver (H-bridge), model TB6612FNG

Photo of a motor driver, Pololu's TB6612FNG Dual Motor Driver Carrier (front view of the board)
Figure 13. Pololu’s TB6612FNG Dual Motor Driver Carrier (front view of the board)
Photo of a motor driver, Pololu's TB6612FNG Dual Motor Driver Carrier (back of the board)
Figure 14. Pololu’s TB6612FNG Dual Motor Driver Carrier (back of the board)

You can change the direction and speed of the motor using the motor driver. The truth table below shows how the motor driver works.

AI1AI2PWMAB1B2PWMBCoil 1Coil 2
HLHLDirection 1Off
LHHLDirection 2Off
LLLOffOff
HHLOffOff
LHLHOffDirection 1
LLHHOffDirection 2
LHHHOffOff
LLLHOffOff
Table 1. States of the TB6612FNG and the coil states

For this lab, the PWMA and PWMB pins connect to Vcc so that the driver circuits stay fully energized. The motor logic pins are also connected to designated digital pins on your Arduino so you can set them HIGH and LOW to turn the motor in one direction, or LOW and HIGH to turn it in the other direction. The motor supply voltage connects to the voltage source for the motor, which is usually an external power supply.

Connect the H-bridge and Motor

This motor nominally runs on 5 volts. It will run as low as 3.3 volts if you give it enough current (about 110 mA). It can run on the current supplied to an Uno or Nano 33 IoT’s USB connection. Ideally, though, you should run it from an external power supply, as described later in the lab. Table 2 below details the pin connections in the circuit. Figures 15 through 17 show how to connect the circuit.

Motor Driver Physical pin numberPin functionCircuit Connection
1VMOT, motor powerArduino Vcc if using USB power. Arduino Vin if using an external power supply.
2Vcc5V (Uno) or 3.3V (Nano 33 IoT)
3GroundGround
4AOUT1motor coil 1 pin 1
5AOUT2motor coil 1 pin 2
6BOUT2motor coil 2 pin 1
7BOUT1motor coil 2 pin 2
8GroundGround
9GroundGround
10PWMB5V (Uno) or 3.3V (Nano 33 IoT)
11BIN2Arduino digital pin 8
12BIN1Arduino digital pin 9
13Standby10-kilohm resistor to 5V (Uno) or 3.3V (Nano 33 IoT)
14AIN1Arduino digital pin 10
15AIN2Arduino digital pin 11
16PWMA5V (Uno) or 3.3V (Nano 33 IoT)
Table 2. TB6612FNG connections to Arduino circuit
Schematic drawing of an Arduino attached to a TB6612FNG stepper motor driver and a stepper motor.  Pin connections are detailed in Table 2.
Figure 15. Schematic view of an h-bridge connected to an Arduino for driving a stepper motor.
Breadboard drawing of an Arduino Uno attached to a TB6612FNG stepper motor driver and a stepper motor.
Figure 16. Breadboard diagram of an H-bridge and an Arduino Uno wired for control of a stepper.
Figure 17. Breadboard diagram of an H-bridge and an Arduino Nano 33 IoT wired for control of a stepper.
Figure 17. Breadboard diagram of an H-bridge and an Arduino Nano 33 IoT wired for control of a stepper.

Made with Fritzing

Once you have the motor and the driver connected, you’re ready to program the microcontroller.

Program the microcontroller

The Arduino Stepper library is written to work with H-bridge and transistor array stepper motor drivers. You initialize the library by telling it how many steps per revolution your motor turns, and what the pin numbers are that are controlling the coils, as follows:

Stepper myStepper(stepsPerRevolution, coil1Pin1, coil1Pin2, coil2Pin1, coil2Pin2);

After that, you move it one direction or the other by calling myStepper.step(steps); If you step it a positive number, it moves one direction; a negative number moves it the opposite direction.

You can install the Stepper library using the Library Manager of the Arduino IDE, if it’s not already installed. Once you’ve done so, there will be examples for it available in the File -> Examples menu.

Regardless of what motor driver you are using, the first thing you should do after wiring up a stepper motor is to write two test programs, one to test if it’s stepping, and one to test if it can rotate one revolution in both directions. The Arduino Stepper library includes these two programs as examples.

The first example to start with is the stepper_oneStepAtATime example. For your first program, it’s a good idea to run the stepper one step at a time, to see that all the wires are connected correctly. If they are, the stepper will step one step forward at a time, every half second, using the code below. Make sure to change the number of steps per revolution and pin numbers if needed, to match your stepper. The number of steps per revolution will depend on your individual stepper, so check the data sheet for the number of steps per revolution:

#include "Stepper.h"

const int stepsPerRevolution = 512;

// initialize the stepper library on pins 8 through 11:
Stepper myStepper(stepsPerRevolution, 8,9,10,11);            

int stepCount = 0;       // number of steps the motor has taken

void setup() {
  // initialize the serial port:
  Serial.begin(9600);
}

void loop() {
  // step one step:
  myStepper.step(1);
  Serial.print("steps:" );
  Serial.println(stepCount);
  stepCount++;
  delay(500);
}

If your circuit is connected correctly, the stepper will step one step forward at a time, every half second.

Once you’ve got that working, try making the stepper move one whole revolution at a time using the stepper_oneRevolution example:

#include "Stepper.h"

const int stepsPerRevolution = 512;  

// initialize the stepper library on pins 8 through 11:
Stepper myStepper(stepsPerRevolution, 8,9,10,11);            

void setup() {
  // set the speed at 60 rpm:
  myStepper.setSpeed(10);
  // initialize the serial port:
  Serial.begin(9600);
}

void loop() {
  // step one revolution  in one direction:
   Serial.println("clockwise");
  myStepper.step(stepsPerRevolution);
  delay(500);

   // step one revolution in the other direction:
  Serial.println("counterclockwise");
  myStepper.step(-stepsPerRevolution);
  delay(500);
}

When you run this code, you should see the motor turn one revolution, wait half a second, then turn one revolution in the other direction.

With a high-step-count stepper, you may want to change the speed using myStepper.setSpeed(). If the motor steps are run too fast, the motor coils don’t have a chance to energize and de-energize in order to step the motor. You don’t have to use the speed command; you can control the speed in your own code by changing the delay between steps and the number of steps you take per step() command.

My motor’s only going one direction!

If you find that the motor only turns in one direction, you probably have the pin connections wrong. It could be that you got the order wrong. Try rearranging the order of the pins. Disconnect power each time you try changing your connections. First, try swapping the two pins on each coil (e.g. blue and yellow, pink and orange) and run it again. If that fails, swap one wire from one coil for one wire from the other coil. Keep trying variations until your motor goes around in one direction, then goes around in the opposite direction.

Unipolar Stepper Control

The steps above showed you how to control a bipolar stepper, but the motor shown was actually a unipolar motor. Remember the red wire you didn’t connect? That wire connects the two coils and can act as a common power source or ground wire. To use the motor as a unipolar motor, try connecting that wire (wire 1) of the motor to the Vin power supply from the DC power jack. You should see that there’s not a lot of difference.

Attach something to the stepper

If you want to mount an arm or pointer to the stepper motor, you need to make a hole for the pointer that fits the shaft perfectly. You could measure this with a caliper. There are also collars and shaft couplers that you can buy for various stepper motors that will allow you to attach things to your stepper. ServoCity has a number of examples, as does Pololu. To pick a good shaft adapter, you need to know what you’re going to do with the stepper, and what the size and shape of the shaft is.

Using an External Power Supply

Although the examples shown above used a motor that can run on the voltage and current supplied to the Arduino via USB, this is not the norm for stepper motors. Most of the time you need to use an external power supply. You should match your supply to your motor. Keep in mind that if you have, say, a 12-Volt power supply and a 5-volt motor, you can add a 5-volt voltage regulator, as shown in the breadboard lab. Figures 18 through 20 show a few different options for powering different stepper motors.

Figures 18 and 19 show how you might power a 9V stepper motor from an Uno or Nano, respectively. Figures 18 and 19 show a NEMA-17 stepper motor. Figure 20 shows how you could power a 5V stepper from a Nano, using a 9-12V DC power supply for the Nano and a 5V voltage regulator for the motor and motor driver.

It’s worth noting that when the Nano 33 IoT is powered from its Vin pin, the USB connection no longer powers the Nano. Instead, the Vin powers the Nano. You can still get 3.3V from the 3.3V out pin (pin 2), however.

The exact voltage and amperage requirements for a stepper motor circuit will depend on the motor you are using. These images show a few options that can work, but you should adapt them depending on the particular electrical characteristics of your motor.

Breadboard drawing of an Arduino Uno attached to a TB6612FNG stepper motor driver and a stepper motor. The caption explains the pin connections.
Figure 18. Breadboard view of TP6612FNG running a 9V NEMA-style stepper motor from an Arduino Uno. The circuit is similar to Figure 16 above, but in this image the TB6612FNG’s VMOT pin (pin 1) is connected to the Uno’s Vin pin. The whole circuit would be powered by a 9V DC power supply connected to the Uno’s power jack.
Figure 19. Breadboard view of an TB6612FNG running a 9V NEMA-style stepper motor from an Arduino Nano 33 IoT. The circuit is similar to Figure 17 above, but in this image an external power jack is connected to the Nano's Vin pin (pin 15) and grounded to its ground pin (pin 14). The TB6612FNG's VMOT pin (pin 1) is connected to the Nano 33 IoT's Vin pin (pin 15) and the positive terminal of the power jack. The Nano would then need to be powered by a 9V DC power supply connected to the power jack
Figure 19. Breadboard view of an TB6612FNG running a 9V NEMA-style stepper motor from an Arduino Nano 33 IoT. The circuit is similar to Figure 17 above, but in this image an external power jack is connected to the Nano’s Vin pin (pin 15) and grounded to its ground pin (pin 14). The TB6612FNG’s VMOT pin (pin 1) is connected to the Nano 33 IoT’s Vin pin (pin 15) and the positive terminal of the power jack. The Nano would then need to be powered by a 9V DC power supply connected to the power jack.
Figure 20. Breadboard view of an TB6612FNG running a 5V stepper motor from an Arduino Nano 33 IoT with an external voltage regulator. The circuit is similar to Figures 17 and 19 above, but in this image an external power jack is connected to the Nano's Vin pin (pin 15) and grounded to its ground pin (pin 14). A 7805 5V voltage regulator has been added to the breadboard in three rows just above the TB6612FNG on the left side of the breadboard. The regulator's input pin is closest to the top of the board, and is connected to the Nano's Vin pin and the positive terminal of the power jack. Its ground is in the middle, and is connected to the left side ground bus of the breadboard. Its output is closest to the bottom and is connected to the TB6612FNG's VMOT pin (pin 1). The whole circuit could be powered by a 9-12V DC power supply connected to the power jack. The regulator would ensure that the motor and the STSPI220 always get 5V and up to 1A.
Figure 20. Breadboard view of an TB6612FNG running a 5V stepper motor from an Arduino Nano 33 IoT with an external voltage regulator. The circuit is similar to Figures 17 and 19 above, but in this image an external power jack is connected to the Nano’s Vin pin (pin 15) and grounded to its ground pin (pin 14). A 7805 5V voltage regulator has been added to the breadboard in three rows just above the TB6612FNG on the left side of the breadboard. The regulator’s input pin is closest to the top of the board, and is connected to the Nano’s Vin pin and the positive terminal of the power jack. Its ground is in the middle, and is connected to the left side ground bus of the breadboard. Its output is closest to the bottom and is connected to the TB6612FNG’s VMOT pin (pin 1). The whole circuit could be powered by a 9-12V DC power supply connected to the power jack. The regulator would ensure that the motor and the STSPI220 always get 5V and up to 1A.

Applications

Stepper motors have lots of applications. One of the most common is to make a tw0- or three-axis gantry for CNC plotters, printers, and mills. A gantry is a structure on which you mount motors and the equipment that they are moving in order to achieve a task. Evil Mad Science’s AxiDraw is a good two-axis example. You can also use steppers to create animation in art projects, as seen in Nuntinee Tansrisakul’s Shadow through Time. Heidi Neilson’s Moon Arrow is another example that uses stepper motors and geolocation tools to make an arrow that always points at the moon.

Transistors, Relays, and Controlling High-Current Loads

Introduction

Related video: High Current Loads

When you’re using microcontrollers, you frequently need to control devices that need more electrical current than a microcontroller can supply. Common examples include:

  • Controlling a DC motor
  • Controlling low-voltage (12-24V) lights
  • Controlling addressable LEDs

For all of these applications, you’ll need a high-current power supply. For some applications where the load operates at a voltage higher than your microcontroller but less than your power supply, you’ll need a voltage regulator and to set up your circuit to power the microcontroller and the load through it. For many of these applications, you’ll also need an electrical relay or transistor to control the load. These notes explain relays and transistors as they’re used for this purpose. In order to get the most out of these notes, you should know something about how electricity works, and you should know the basics of how a microcontroller works as well.

Relays

Related video: Relays

Digital output from a microcontroller is typically a low-amperage signal. For example, when you set a pin HIGH, the voltage coming on that pin is typically +3.3V or +5V, and the amperage that it can source is around 10 milliamps. This is fine if you’re controlling an LED, whose required amperage is tiny. However, most devices you’d want to control need more current than that to operate. You need a component in between your microcontroller and the device that can be controlled with this small voltage and amperage. Relays and transistors are most often used for this purpose. A relay is a switch that’s controlled by a small electric current. Relays take advantage of  the fact that when you pass an electric current through a wire, a magnetic field is generated surrounding the wire as well.  This is called induction. When you place two pieces of ferrous metal near a coil of wire and pass current through the wire, the magnetic field can move the two pieces of metal towards each other. Those pieces of metal can form a switch, which can be turned on and off by putting current through the coil, as shown in Figure 1, 2 and 3.

Two relays, one whole and the other with the switch removed. The blue and white tube is the coil, and the green tinted glass vial contains the internal switch
Figure 1. Two relays, one whole and the other with the switch removed. The blue and white tube in each relay is the coil, and the glass vial, which is normally inside the tube, contains the switch
Detail of the switch inside the relay, magnified 20x
Figure 2. Detail of the switch inside the relay, magnified 20x
Relay connection pins
Figure 3. Relay connection pins In this image the four pins are visible. The two on the long end of the relay tube are the switch connections. The two pins on one end of the tube, on an axis perpendicular to the tube, are the coil connections.
Diagram of Relay wired to a microcontroller and a lamp with a + 9 volt battery
Figure 4. Diagram of Relay wired to a microcontroller and a lamp with a + 9 volt battery/ The switch terminals are connected to one terminal of a lamp and to the negative terminal of a 9V battery, respectively. The other terminal of the lamp is connected to the positive terminal of the battery. One of the coil terminals is connected to the output pin of a microcontroller, and the other is connected to the microcontroller’s ground. There is no electrical connection between the microcontroller circuit and the lamp circuit.

In Figure 4, you can see that there’s no electrical connection between the microcontroller circuit that’s controlling the coil of the relay and the lamp circuit. This is one advantage that relays offer. Figure 5, a schematic of the relay circuit is the same as Figure 4, but shown with traditional schematic symbols for the relay, the battery, and the lamp:

Schematic of a relay wired to an arduino and a lamp with a + 9 volt battery
Figure 5. Schematic of a relay wired to an arduino and a lamp with a + 9 volt battery

The current needed to move the shaft in the coil is very low (less than 10 milliamps) so the coil can be energized by an output pin of your microcontroller. The current that can flow through the switch, however, is much higher. The lamp circuit is separate from the microcontroller. It uses a separate power source, with the amperage and voltage needed to turn on the lamp. The power source, the lamp, and the switch side of the relay are all placed in series. When the coil is energized, the leaves of the switch are physically moved by the magnetic force created, the lamp circuit is completed, and the lamp turns on.

Because there is no electrical connection between the switch and the coil, relays can also control AC loads as well as DC loads. You can’t use a relay to dim a lamp or control the speed of a motor, however. The switching speed of relays is too slow to pulsewidth modulate them.

Transistors

Related videos: Transistor Schematics, NPN Transistors, PNP Transistors, Darlingtons and MOSFETs

Because a relay is a mechanical switch, it can be somewhat slow. Relays take a few milliseconds to close, so they aren’t very effective when you want to turn them on and off rapidly. Sometimes you need to switch a high current circuit rapidly. In this case you would use a switching transistor. A transistor is an electronic device that can work as a switch. It allows control of a large current by a smaller current as does a relay. Unlike a relay, however, a transistor is not mechanical, and can operate much faster than a relay. There are several types of transistors and they come in two major classes: bipolar transistors, and field-effect transistors, or FETs. All transistors have some similar properties though. They all have three connections, referred to as the base, the collector, and the emitter (on FET transistors, the three connections are the gate, the drain and the source).When you apply a small voltage and current between the base of a transistor and the emitter (or the gate and the drain on a FET), you allow a larger current to flow from the collector to the emitter (or the drain and the source).

Among bipolar transistors, which are the older class of transistors, there are two types: NPN transistors, and PNP transistors. When you apply positive voltage to the base of an NPN transistor,  it turns on the collector-emitter connection  and allows current to flow from collector to emitter (Figure 6).  The equivalent MOSFET is called an N-channel MOSFET. When you apply voltage to the base of a PNP transistor, by contrast, the collector-emitter connection turns off, and  no current can flow from collector to emitter. The MOSFET equivalent is a P-channel MOSFET. One of the main differences between MOSFETS and bipolar transistors is that MOSFETS require negligible current on the base in order to activate. For the purposes of switching a load on and off, they are an excellent choice.

Chart comparing Bi-polar transistors and MOSFETS. NPN Transistors behave similarly to N-Channel MOSFETS. PNP Transistors are comparable to P-Channel MOSFETS
Figure 6. Chart comparing Bi-polar transistors and MOSFETS. NPN Transistors behave similarly to N-Channel MOSFETS. PNP Transistors are comparable to P-Channel MOSFETS

Among the bipolar transistors, there’s one type commonly used to switch high-current loads, the Darlington transistor. Darlington transistors are actually two transistors in one, combined with a diode that protects the transistors from damage in case the load’s current runs in reverse. In many of the labs on this site, you’ll see reference to one the TIP120 Darlington transistor.

Darlington transistors aren’t the only good transistors for high-current loads, though. You could use an N-Channel MOSFET with a protection diode in place of the darlington transistor. The IRF520 MOSFET is a good equivalent if you’re using a 5-volt microcontroller like the Uno. The FQP30N06L MOSFET works well for both 5V microcontrollers and 3.3V microcontrollers like the Nano 33 IoT.

Figure 7 shows the basic circuit for using a transistor to control a high-current load. You connect a DC power source to one terminal of the load, then connect the second terminal of the load to the collector of the transistor (or drain, for a MOSFET) of the transistor. The emitter (or source) is then connected to ground, and the base (or gate) is connected to the output of your microcontroller. When you take the output pin of the microcontroller high, the voltage difference between the base (or gate) and the emitter  (or source) allows current to flow through the load, through the collector  (or drain) to the emitter (or source) and to ground.

Two similar microcontroller and motor schematics. The first schematic uses a Darlington Transistor. The second uses an N-Channel MOSFET.
Figure 7. Two similar microcontroller and motor schematics. The first schematic uses a Darlington Transistor. The second uses an N-Channel MOSFET.

Note how similar this schematic is to the relay schematic. The transistor here is serving the same function as the relay. However, it can switch much faster than the relay. In addition, because there are no mechanical parts, it will reliably function for more switching operations than the relay. However, current can only flow in one direction through a transistor. If the voltage on the collector (or drain) is lower than that on the emitter (or source), you can damage the transistor. The same is not true with a relay.

There are three differences between this transistor circuit and the relay circuit above. The first is that you’re using a motor as the load, rather than an incandescent light bulb. Because motors are inductive loads (they work because of induction; for more, see the DC motor notes), they can create a reverse voltage when spinning down after you turn them off. Because of this, the second difference is the protection diode in parallel with the transistor. The protection diode routes any reverse voltage around the transistor, thereby protecting it. Most transistors designed for controlling motors have a protection diode built-in. The TIP120, the IRF520, and the FQP30N06L all have built-in protection diodes. The third difference is that the microcontroller attached to the base (or gate) and the transistor’s emitter (or source) must have a common ground. If not, then the circuit will not work.

If you are switching DC motors, solenoids, or other high-current DC devices which create motion, it’s better to use a switching transistor than a relay. The ideal way to control a motor is with an H-bridge, which is an array of transistors that lets you control not only speed but also direction. There’s more on that in the motor control notes.

Videos: Relays, Transistors, and Motors

ITP Videos by Jeff Feddersen on Vimeo.

Intro to High Current Loads

Relays

Transistors

Motors

Meet the Motors

Analog Output – Motor Control

H-Bridges

Stepper Motors

Types of Stepper Motors

Controlling a Unipolar Stepper

Controlling a Bipolar Stepper with an H-Bridge

Dedicated Stepper Motor Drives

Labs: Motors and Transistors

The following labs are about controlling DC motors and other high-current loads with transistor and H-Bridges.

Lab: Servo Motor Control with an Arduino

In this tutorial, you’ll learn how to control a servomotor’s position from a microcontroller using the value returned from an analog sensor.

In this tutorial, you’ll learn how to control a servomotor’s position from a microcontroller using the value returned from an analog sensor.

Introduction

Servos are the easiest way to start making motion with a microcontroller. Servos can turn through a range of 180 degrees and you can use them to create all sorts of periodic or reciprocating motions. Check out some of the mechanisms at Rob Ive’s site for ideas on how to make levers, cams, and other simple machines for making motion. The resources section of this site has links to other sites on construction, mechanics, and kinetics as well.

What You’ll Need to Know

To get the most out of this lab, you should be familiar with the following concepts. You can check how to do so in the links below:

Things You’ll Need

Prepare the breadboard

Connect power and ground on the breadboard to power and ground from the microcontroller. On the Arduino module, use the 5V or 3.3V (depending on your model) and any of the ground connections, as shown in Figures 9 and 10.

An Arduino Uno on the left connected to a solderless breadboard, right. The Uno's 5V output hole is connected to the red column of holes on the far left side of the breadboard. The Uno's ground hole is connected to the blue column on the left of the board. The red and blue columns on the left of the breadboard are connected to the red and blue columns on the right side of the breadboard with red and black wires, respectively. These columns on the side of a breadboard are commonly called the buses. The red line is the voltage bus, and the black or blue line is the ground bus.
Figure 9 Breadboard view of an Arduino Uno on the left connected to a solderless breadboard, right.

Figure 9. An Arduino Uno on the left connected to a solderless breadboard, right. The Uno’s 5V output hole is connected to the red column of holes on the far left side of the breadboard. The Uno’s ground hole is connected to the blue column on the left of the board. The red and blue columns on the left of the breadboard are connected to the red and blue columns on the right side of the breadboard with red and black wires, respectively. These columns on the side of a breadboard are commonly called the buses. The red line is the voltage bus, and the black or blue line is the ground bus.


Arduino Nano on a breadboard.
Figure 10. An Arduino Nano mounted on a solderless breadboard. The Nano is mounted at the top of the breadboard, straddling the center divide, with its USB connector facing up. The top pins of the Nano are in row 1 of the breadboard.

The Nano, like all Dual-Inline Package (DIP) modules, has its physical pins numbered in a U shape, from top left to bottom left, to bottom right to top right. The Nano’s 3.3V pin (physical pin 2) is connected to the left side red column of the breadboard. The Nano’s GND pin (physical pin 14) is connected to the left side black column. These columns on the side of a breadboard are commonly called the buses. The red line is the voltage bus, and the black or blue line is the ground bus. The blue columns (ground buses) are connected together at the bottom of the breadboard with a black wire. The red columns (voltage buses) are connected together at the bottom of the breadboard with a red wire.

Images made with Fritzing

Connect an Analog Input Sensor and a Servo

Connect an analog input to analog pin 0 as you did in the Analog Input Lab covered previously. A force-sensing resistor is shown in Figure 11-14 below, but you can also use a potentiometer, phototransistor, or any analog input you prefer. Then connect an RC servomotor to digital pin 9. The yellow wire of the servo goes to the pin, and the red and black wires go to +5V and ground, respectively.

Most RC servomotors are rated for 4-6 volt power input. When you’re using a 3.3V microcontroller like the Nano 33 IoT, you can use the Vin pin to power the motor if you’re running off USB power, or off a 5V source connected to the Vin.

Related video:Intro to Servo Motors

Safety Warning! Not all servos have the same wiring colors. For example, the Hextronik servos that come with Adafruit’s ARDX kit use red for +5V, brown for ground, and mustard yellow for control. Check the specifications on your particular servomotor to be sure.

Schematic view of an Arduino Uno connected to a voltage divider input circuit on analog in pin 0 and a servomotor on digital pin 9. On the left, a fixed 10-kilohm resistor is attached to analog in pin 0 and to ground on the Arduino. A variable resistor is attached to analog in pin 0 and to +5 volts. On the right, a servomotor's control wire is attached to digital pin D3. The motor's voltage input is attached to +5 volts, and its ground is attached to ground on the Arduino. A 10-microfarad capacitor is mounted across the +5V and ground buses close to where the motor voltage and ground wires are connected.
Figure 11. Schematic view of a servomotor and an analog input attached to an Arduino Uno.
Breadboard view of a servomotor and an analog input attached to an Arduino Uno. The +5 volts and ground pins of the Arduino are connected by red and black wires, respectively, to the left side rows of the breadboard. +5 volts is connected to the left outer side row (the voltage bus) and ground is connected to the left inner side row (the ground bus). The side rows on the left are connected to the side rows on the right using red and black wires, respectively, creating a voltage bus and a ground bus on both sides of the board. A force-sensing resistor, or FSR, is mounted in rows 18 and 19 of the left center section of the breadboard. a 10-kilohm resistor connects one leg of the FSR to the left side ground bus. A blue wire connects the row that connects these two to analog in 0 on the Arduino. A red wire connects the other pin to the left side voltage bus. A servomotor's voltage and ground connections are connected to the voltage and ground buses on the left side of the breadboard. the servomotor's control wire is connected to pin D9 of the Arduino. A 10-microfarad capacitor is mounted across the +5V and ground buses close to where the motor voltage and ground wires are connected.
Figure 12. Breadboard view of a servomotor and an analog input attached to an Arduino Uno.
Schematic view of an Arduino Nano 33 IoT connected to a voltage divider input circuit on analog in pin 0 and a servomotor on digital pin 9. On the left, a fixed 10-kilohm resistor is attached to analog in pin 0 and to ground on the Arduino. A variable resistor is attached to analog in pin 0 and to Vin pin (+5 volts). On the right, a servomotor's control wire is attached to digital pin D3. The motor's voltage input is attached to Vin, and its ground is attached to ground on the Arduino. A 10-microfarad capacitor is mounted across the 3.3V and ground buses.
Figure 13. Schematic view of a servomotor and an analog input attached to an Arduino Nano 33 IoT.
Breadboard view of an Arduino Nano 33 IoT connected to a voltage divider input circuit on analog in pin 0 and a servomotor on digital pin 9. A fixed 10-kilohm resistor is attached to analog in pin 0 and to ground on the Arduino. A variable resistor is attached to analog in pin 0 and to Vin pin (+5 volts). A servomotor's control wire is attached to digital pin D3. The motor's voltage input is attached to Vin, and its ground is attached to ground on the Arduino. A 10-microfarad capacitor is mounted across the 3.3V and ground buses.
Figure 14. Breadboard view of a servomotor and an analog input attached to an Arduino Nano 33 IoT.

When you attach the servo, you’ll need a row of three male headers to attach it to a breadboard. You may find that the pins don’t stay in the servo’s connector holes. Put the pins in the servo’s connector, then push them down on a table gently. They will slide up inside their plastic sheaths, and fit better in your servo’s connector.

Different RC servomotors will have different current requirements. The Tower SG5010 model servo sold by Adafruit draws more current than the HiTec HS311 and HS318 sold by ServoCity, for example. The Tower Pro servo draws 100-300 mA with no load attached, while the HiTec servos draw 160-180mA. The decoupling capacitor in the circuit will smooth out any voltage dips that occur when the servo turns on, but you will need an external 5V supply if you are using more than one servomotor.

Related video: Connect the Servo

Figures 15-17 show steps of this in action.

Photo of a servomotor connector with three header pins next to it. The header pins appear too short to connect properly to the servomotor connector.
Figure 15. Attaching header pins to a servomotor connector. If your header pins are too short, as shown here, you can lengthen them.
Photo of a hand holding a servomotor connector with header pins pushed partway into the holes. The pins are being braced against a tabletop.
Figure 16. Push the short ends of the header pins into the servomotor connector’s holes and then brace the long ends against a tabletop while you push down on the connector. Do this gently and the header pins will move in their plastic mount.
Photo of a servomotor connector with three header pins next to it. The header pins are now longer on top and shorter on bottom than they were in the first picture.
Figure 17. Now your header pins will be longer on top and shorter on bottom, and will stay firmly in the servomotor connector.

Program the Microcontroller

First, find out the range of your sensor by using analogRead() to read the sensor and printing out the results.

void setup() {
  Serial.begin(9600);       // initialize serial communications
} 

void loop()
{
  int analogValue = analogRead(A0); // read the analog input
  Serial.println(analogValue);      // print it
}

Now, map the result of the analog reading to a range from 0 to 179, which is the range of the sensor in degrees. Store the mapped value in a local variable called servoAngle.

void setup() {
  Serial.begin(9600);       // initialize serial communications
} 

void loop()
{
  int analogValue = analogRead(A0); // read the analog input
  Serial.println(analogValue);      // print it

  // if your sensor's range is less than 0 to 1023, you'll need to
  // modify the map() function to use the values you discovered:
  int servoAngle = map(analogValue, 0, 1023, 0, 179);
}

Finally, add the servo library at the beginning of your code, then make a variable to hold an instance of the library, and a variable for the servo’s output pin. In the setup(), initialize your servo using servo.attach(). Then in your main loop, use servoAngle to set the servo’s position.

#include "Servo.h"      // include the servo library

Servo servoMotor;       // creates an instance of the servo object to control a servo
int servoPin = 9;       // Control pin for servo motor
// time when the servo was last updated, in ms
long lastMoveTime = 0;  

void setup() {
  Serial.begin(9600);       // initialize serial communications
  servoMotor.attach(servoPin);  // attaches the servo on pin 9 to the servo object
} 

void loop() {
  int analogValue = analogRead(A0); // read the analog input
  Serial.println(analogValue);      // print it

  // if your sensor's range is less than 0 to 1023, you'll need to
  // modify the map() function to use the values you discovered:
  int servoAngle = map(analogValue, 0, 1023, 0, 179);

  // move the servo using the angle from the sensor every 20 ms:
  if (millis() - lastMoveTime > 20) {
    servoMotor.write(servoAngle);
    lastMoveTime = millis();
  }
}

Related video: Code for the Servo & Turn the Servo

Get Creative

Servo motors give you the power to do all kinds of things.

They can be used to push a remote control button, in a pinch, as shown in Figure 18.

Photo of a remote control mounted in a wooden cradle. A servomotor mounted on the side of the cradle is positioned such that when it moves, its horn presses down on the power button of the remote control.
Figure 18. A servomotor can press remote control buttons The remote control is mounted in a wooden frame, and the servo is mounted on the side of the frame. The servo horn moves down to press the power button.

You can play music with found objects like in this Project by Nick Yulman. You can build a frisking machine like in this project by Sam Lavigne and Fletcher Bach. If you’ve got 800 or so of them and a lot of time, you can build a wooden mirror like this Project by Daniel Rozin.

Controlling Stepper Motors

Introduction

Stepper motors are useful for when you need to rotate a full 360 degrees, but need to position your motor at a particular angle. What follows is a more detailed introduction to unipolar and bipolar stepper motors and how to control them from a microcontroller.  In order to get the most out of these notes, you should know something about how electricity works, and you should know the basics of how a microcontroller works as well. You should also understand how transistors are used to control high-current loads. You should also understand how DC motors work.

As you learned in the introduction to motors,  stepper motor is a motor controlled by a pair of electromagnetic coils. The center shaft has a series of magnets mounted on it, and the coils surrounding the shaft are alternately given current or not, creating magnetic fields which repulse or attract the magnets on the shaft, causing the motor to rotate.

Related Videos

There are two basic types of stepper motors, bipolar steppers and unipolar steppers. A bipolar is the simpler kind of stepper motor; it’s simply two coils, and has four wires. Depending on which coil you put power through, and which direction you send the power in, you step the motor one step forward or back. A unipolar stepper is slightly more complex. It also has two coils, but the centers of the coils are joined in a single junction. This effectively creates four coils, depending on how you put electrical energy through it.

If you’re looking for sources of stepper motors and stepper motor drivers, you’ll find many motors and drivers at Pololu, Adafruit, Sparkfun, and the other usual hobbyist electronics retailers. Octopart will also give you wide variety of retailers for steppers.

Bipolar stepper motors

A bipolar stepper motor usually has four wires coming out of it. It has two independent coils. Figure 1 shows a typical bipolar stepper with four wires. In the center is the motor’s shaft, which has a cog-like rotor on it. Each tooth of the cog is magnetized, and every cog’s magnetic polarity is opposite the one next to it.When you put voltage and current through one coil, it turns the central rotor a few degrees, because the magnets on the rotor are attracted to the magnetic field generated by the coil. When you turn that coil off and the other one on, the motor moves a few degrees more.

Schematic drawing of a bipolar stepper motor. It has two coils facing each other. The ends of the coils are numbered 1 and 2 (coil 1) 3 and 4 coil 2). The central motor shaft and rotor appears in the middle as cog.
Figure 1. Wiring for a bipolar stepper motor.

To use a bipolar stepper, you need to know which wire is connected to which coil. You can determine this by measuring the resistance between pairs of wires. When you’ve got the leads of your meter connected to two wires on opposite coils, you should see infinite resistance, or no continuity. When your meter leads are on the same coil, you’ll be able to read the coil’s resistance. The two coils should have the same resistance.

Some bipolar steppers have a center connection on each coil. This allows for finer control over the motor, by treating each half coil as its own coil, as shown in Figure 2. These center connections can be joined to turn a 6-wire bipolar stepper into a unipolar stepper as well. Figure 3 shows the inside of a typical bipolar stepper motor.

Schematic drawing of a six-wire bipolar stepper motor. It has two coils facing each other. The ends of the coils are numbered 1 and 2 (coil 1) 3 and 4 coil 2). The central motor shaft and rotor appears in the middle as cog.  The center wires of each coil are marked 5 (for coil 1) and 6 (for coil 2).
Figure 2. a six-wire bipolar stepper
Photo of three stepper motors. The center one is opened up to show the coils inside.
Figure 3. Inside a Stepper motor. In this photograph, you can see the inside of a bipolar stepper. The two coils are actually divided into eight sub-coils for finer control. You can see the cog in the center as well. Each tooth on the cog is a tiny magnet.

Like other motors, stepper motors require more power than a microcontroller can give them, so you’ll need a separate power supply for them. Ideally you’ll know the voltage and load current from the manufacturer. If not, get a variable DC power supply, apply the minimum voltage (hopefully 3V or so), apply voltage across two wires of one coil (e.g. 1 to 2 or 3 to 4) and slowly raise the voltage until the motor is difficult to turn. It is possible to damage a motor this way, so don’t go too far. Typical voltages for a stepper might be 5V, 9V, 12V, 24V. Higher than 24V is less common for small steppers, and frankly, above that level it’s best not to guess.

Unipolar Stepper Motors

Unipolar steppers motor have five or six wires. The five-wire version has four coils which are all connected on one pole. Six-wire motors are actually bipolar steppers with two coils divided by center connections on each coil, as described above. The center connections of the coils are tied together as shown in Figure 4 and sometimes used as the power connection.

Drawing of the wiring for a unipolar stepper motor, showing two variations. In the drawing on the left side of the frame, labeled "5-wire unipolar stepper", four coils of wire radiate out from a central connection labeled "center wire. The other ends of the four coils are labeled "coil 1" through "coil 4". In the drawing on the right, labeled "6-wire unipolar stepper" there are two coils side by side, labeled "coil 1" and "coil 2". There is a connection in the center of each coil as well, and those center wires are joined together.
Figure 4. The wiring for unipolar stepper motors. The center wires for the two coils are tied together in a unipolar stepper.

Common Stepper Motor Types

There are two common families of stepper motor that you’ll encounter: NEMA motors and can-stack or tin-can steppers. The labs on this site can work with either. NEMA motors are designed according to a standard set by the US National Electrical Manufacturers Association. These are high-quality motors, and usually the more expensive that you’ll find. The number in a NEMA motor’s designation indicates the motor’s size. A NEMA-11 motor, for example, has a mounting face that’s 1.1 inches square; NEMA-23 is 23 step motor is 2.3 inches square and so forth. Electromate.com has a detailed explanation of NEMA motors if you ‘d like more detail.

Can-stack steppers are typically smaller and more cheaply made, mounted in a simple can, often with gears on top to increase torque and steps per revolution, and decrease speed. They’re often used in disk drives, motorized lens optics, and other industrial applications. The first number in the spec for these indicates the can’s diameter in millimeters. A 28BYJ-48 motor has a 28mm diameter can. A 24BYJ-48 has a 24mm can size, and so forth. Melissa Zheng has a good explanation of can-stack stepper motor specs.

Figure 5 shows a variety of NEMA-style steppers. Figure 6 shows a 28BYJ-48 can-stack stepper.

Photo of several NEMA-style stepper motors. These motors all share s solid metal casing and mounting holes on the top by their shafts. They come in various sizes.
Figure 5. A range of NEMA stepper motors. Image from Pololu.com
Photo of a stepper motor. This motor is approximately 2 inches (5cm) on diameter, with an off-center shaft at the top, and wires protruding from the bottom. You can tell a stepper motor from a DC motor because steppers have at least four wires, while regular DC motors have two.
Figure 6. a can-stack stepper motor

Control of Stepper Motors

To control the stepper, apply voltage to each of the coils in a specific sequence. Both types of stepper motor can be controlled with a motor driver (related video).  The sequence would go like this:

StepWire 1Wire 2Wire 3Wire 4
1highlowhighlow
2lowhighhighlow
3lowhigh lowhigh
4high low lowhigh
Table 1. Sequential states of the voltage on the four control pins of a stepper motor.

To step the motor, you change the pins in the order shown in Table 1. With each step, the motor will move forward or backward one increment. Once you have the motor stepping in one direction, stepping in the other direction is a matter of doing the steps in reverse order.

It’s good practice when you wire a stepper up for the first time to write a program to step it slowly, one step at a time, using the steps above. That way you can see if you got the wiring right. If you did, the stepper should turn step by step in one direction. If you didn’t, it may step in unpredictable ways.

A stepper motor’s position is not absolute. You have to know where the motor started (usually measured with an external sensor) and how many degrees per step. Then you count the steps and multiply by that many degrees. So for examples, if you have a 1.8-degree stepper, and it’s turned 200 steps, then it’s turned 1.8 x 200 degrees, or 360 degrees, or one full revolution.

The circuits for controlling a unipolar stepper or a bipolar stepper are very similar. In both cases, you have four ends of coils that go to the four outputs of the driver. The difference is that for the unipolar, you also have a common center wire. That wire can be attached to the same motor voltage supply that feeds the driver, or it can be left disconnected. If you do the latter, you’re treating the unipolar motor as if it had two separate coils — in other words, as if it were a bipolar stepper.

H-bridge Stepper Drivers

There are a couple of different types of stepper motor drivers. The oldest use four transistors, treating each wire as if it were a motor itself. If you take wire 1 high and wire 2 low, coil turns one direction. Take wire 1 low, and wire 2 high, and the coil turns the other direction. The same principle applies to the other coil. This can be done with individual Darlington transistors or MOSFETs, or it can be done with a transistor array like the ULN2004.

The four-transistor approach is essentially an H-bridge, and you could use two H-bridges to control a stepper. The TB6612FNG dual motor driver that you saw in the H-bridge lab is a dual H-bridge designed for this purpose. You’ll see it in action in the H-bridge stepper motor lab. There is an older H-bridge that only operates on 5V, the L293D, which you will encounter from time to time. This driver does not work with the Arduino Nano 33 IoT and other 3.3V boards, but it’s common enough that it’s useful to know that it can be replaced with a TB6612FNG.

With an H-bridge style driver, you know what you’re getting: take the input 1 HIGH and input 2 LOW, and you create a voltage difference between outputs 1 and 2. It’s conceptually easy, but requires more thinking and planning when you are programming the stepper. Fortunately, there is a Stepper library for Arduino that simplifies this somewhat.

Step & Direction Stepper Drivers

More modern stepper drivers have just two control pins, one for step and one for direction. They also feature configuration pins that let you set the step pin to move the motor a full step, a half step, or less. This is called microstepping, and you can find stepper drivers that will work as low as 1/256th of a step. This allows finer control over the stepper motor.

Step & direction drivers simplify control of a stepper because they only require two signals from a microcontroller: take the direction pin high or low to turn the motor’s direction one way or the other. Then pulse the step pin. With each pulse, the motor should step in the direction set by the direction pin. You can run these kinds of steppers without a library. You’ll see these drivers in the step & direction stepper driver lab.

There are a number of step & direction motor drivers available. For example, ther STSPIN220 from ST microelectronics works in the 1.8-10V range. the A4988 handles motors in the 8-35V range. Trinamic’s drivers, also sold on breakout boards by Watterott as SilentStepStick boards, control a wide range of voltages and are designed to reduce noise. Allegro’s A4988 and Monolithic’s MP6500 and Texas Instruments’ DRV88xx line are also good driver lines to look at. Here’s a comparison chart for many of these lines, on breakout boards from Pololu. Table 2 is a summary of a few other step & direction drivers.

In picking a step & direction driver, the first questions to ask are:

  • Is my motor’s rated voltage in the driver’s Motor Voltage range?
  • Is my motor’s rated current less than the driver’s Max. Motor Current range?
  • Is my microcontroller’s operating voltage in the driver’s Control Voltage range?
DriverTypeMotor VoltageMax. Motor CurrentControl VoltageMicrostepsPrice (as of Jun. 2022)
A4988 Black EditionStep & direction8-35V1.1A3-5.5V1/16$13.95
STSPIN220Step & direction1.8-10V1.1A1.8-5.5V1/256$7.45
TMC2130Step & direction, SPI5.5-45V1.2A3.3-5V1/256$10.68
TMC2209Step & Direction, UART 4.75-28V 1.4A3.3-5V1/256$16.03
TMC2208Step & Direction, UART4.75-36V1.2A4.6-5.25V1/256$9.58
TMC2100Step & Direction5.5-45V1.2A3.3-5V1/256$9.28
TB6612FNGDual H-Bridge15V1.2A2.7–5.5V$5.50
EasyDriverStep & Direction6-30V 700mA3-5.5V1/8$16.95
Table 2. Step & Direction drivers compared

DC Motors: The Basics

These notes are heavily indebted to Gordon McComb’s Robot Builder’s Bonanza, second edition, which includes some excellent chapters on motors and motor use.

Introduction

Related video: Meet the Motors

When trying to move things with microcontrollers, you’re likely to use one of three kinds of motors: DC motors, RC servomotors, and stepper motors. Following is a brief introduction to these three. In order to get the most out of these notes, you should know something about how electricity works, and you should know the basics of how a microcontroller works as well. You should also understand how transistors are used to control high-current loads.

Motors convert electrical energy into mechanical energy so that you can move things in the physical world.  They are based on the electrical principle of induction. When you put electric current through a wire, it generates a magnetic field around the wire as shown in Figure 1. The direction of the magnetic field is related to the direction of the electrical current. It’s often described as the right-hand rule. If you hold your right hand up and put your thumb perpendicular to your index finger, then put your middle finger perpendicular on the other axis, can see the directions of current flow (your index finger); magnetic force (your thumb); and the magnetic field line (your middle finger). The higher the current, the greater the magnetic field, and therefore the greater the attraction or repulsion.

Drawing of a right hand with thumb pointing up (magnetic force), index finger pointing left (current) and middle finger pointing toward the reader (magnetic field direction)
Figure 1. The relationship between current, magnetic force, and magnetic field direction.

Similarly, if there’s a magnet near a wire, its field will interact with the wire’s magnetic field and generate a current in the wire. If you mount magnets on a spinning shaft surrounded by the wire, you have a motor. In Figure 2, the wire is arranged in two coils. As the magnets are alternately attracted to one coil and repulsed by the other, it spins from one to the other, and you get circular motion. Figure 2 illustrates the basic mechanism of a DC motor.

Drawing of the mechanism of a DC motor. At the center of the drawing are two semi-circular magnets, labeled North and South, arranged to make a circle around a spinning shaft. Two coils of wire stand to the left and right of the magnets. The coils are joined together by a wire. The free end of the left coil is labeled +V and the free end of the right coil is labeled with an electrical ground symbol.
Figure 2. The basic mechanism of a DC motor.

All inductive loads (like motors, electromagnets, and solenoids) work on this same principle: induce a magnetic field by putting current through a wire, use it to attract or repulse a magnetic body. However, the principle works in reverse as well. When you spin a wire in an existing magnetic field, the field induces a current in the wire. So if you’ve got a motor spinning, and you turn it off, the fact that the motor’s coil is spinning in a magnetic field will generate a current in the wire while it’s spinning. You can test this by attaching an LED to the two leads of a DC motor and spinning the motor by hand. Spun in one direction, the LED will light. Spin in the other, the LED won’t light.

This generated current comes back in the reverse direction of the current flow you generated to run the motor. When the motor isn’t attached to another source of electricity, you’d call this a generator as in the LED experiment, because the motor is now generating voltage. When the motor is connected to another power source, it’s called back voltage, and it can cause damage to your electronics. Usually it’s stopped by putting a diode in parallel with your motor to route the back voltage through the diode.

Motor Characteristics

There are a few characteristics common to all motors that you should keep in mind when looking for motors:

Voltage

The rated voltage of a motor is the voltage at which it operates at peak efficiency. Most DC motors can be operated somewhat above or below their range, but it’s best to plan to operate them at their rated voltage. Dropping below rated voltage reduces the motor’s power, and operating above the rated voltage may burn the motor out. Plan on the motor’s top speed being at rated voltage, and slowest speed at no more than 50% less than the rated voltage.

Current

Motors draw current depending on the load they’re pulling. Usually more load means more current. Every motor has a stall current, which is the current it draws when it’s stopped by an opposing force. This stall current is generally much greater than the running current, or current that the motor draws under no load. Your power supply for a motor should be able to supply the stall current with extra amperage to spare. Motors will draw the stall current for a brief period of time when starting up, to overcome their inertia.

Speed

Motor speed is given in revolutions per minute (RPMs). At the rated voltage, your motor should be turning at the rated speed.

Torque

Torque is the measure of a motor’s turning force. It’s the force a motor can pull when the opposing force is attached to a shaft attached to its center rod. If the shaft sticks out a foot from the motor’s center, and the motor can pull one pound on that shaft, the motor’s torque is one foot-pound. Figure 3 illustrates this with a motor that supplies 1g*cm. Related video: Torque and Gearboxes

Drawing of the principle of torque. A motor is shown with its main axis drawn horizontally. There is a rod mounted on the motor's shaft, perpendicular to the main axis. THis rod will rotate when the motor is energized. The distance from the center of the shaft to the end of the rod is labeled as 1cm. A cube, labeled 1 gram, hangs off the end of the rod. An arrow indicates that the weight will be lifted when the motor rotates.
Figure 3. Torque illustrated. This motor can lift a 1 gram weight at a distance of 1 centimeter out from the center of rotation. Therefore, it can supply 1g*cm of torque.

Resistance

Often you’ll see a motor rated in ohms. This just gives you the resistance that the motor’s coil offers. Using Ohm’s Law (voltage = current x resistance), you can calculate the motor’s current draw if you know the rated voltage and the coil resistance.

Types of Motors

DC Motor

The DC Motor is the simplest of the motors discussed here. Figure 4 shows a photo of a small DC motor. It works on exactly the principle discussed above. There are two terminals, and when you apply direct current to one terminal and ground the other, the motor spins in one direction. When you apply current to the other terminal and ground the first terminal, the motor spins in the opposite direction. By switching the polarity of the terminals, you reverse the direction of the motor. By varying the current supplied to the motor, you vary the speed of the motor. Specific techniques for doing these tasks are discussed below. Related video: Power to a DC Motor

DC motors are usually very fast, often spinning at several thousand revolutions per minute (RPM). The DC motor in Figure 4 is common to many toy and hobby projects.

DC toy motor, hobby size. This motor is a metal tube with flattened sides, approximately 2 in. (5cm) long. a thin shaft at one end spins when the motor is on. Two small metal tabs or wires protrude from the other end to connect the motor to your circuit.
Figure 4. Small DC motor, 130 size

For more on DC motor control, see this lab for single-direction control, or this lab for controlling a motor in two directions with an H-Bridge.

Gearhead Motor

Gearhead motors are a subset of DC motors. Figure 7 is a drawing of a gearhead motor. They have a box on the top of the motors containing a series of gears that slow the rotational speed of the motor down and increase the torque. They are useful when you don’t need a lot of speed, but you do need power. They are controlled exactly the same as regular DC motors.

Photorealistic drawing of a gearhead motor. It is a normal DC motor, but with a gearbox attached over the shaft. The image shows a cutaway view of the gears, indicating how the sequence of gears steps down the speed of the motor to increase torque.
Figure 7. Gearhead motor with the gears shown. Image from designworldonline

In Figure 8, you can see a gearmotor that uses this size motor. You can see the full specifications at this link. Table 1 has a summary of the specs. You can see that the no-load current is 190mA and the stall current is 250mA. and the rated voltage is 6V. Using this information, you could work out that the coil resistance is probably between 24 and 32 ohms. You can also see that the no-load speed is 230RPM and the stall torque is 0.8 kg-cm. These are the values for the motor with the gearbox attached.

Photo of a DC Gearmotor.  This motor is a metal tube with flattened sides, approximately 2 in. (5cm) long. a gearbox at one end, approx. 3 in (7.5cm) long contains gears that slow the motor and increase the torque. Two shafts stick out from the gearbox, perpendicular to the motor's axis. Two wires protrude from the other end to connect the motor to your circuit.
Figure 8. DC Gearmotor
Voltage (Nominal)6VDC
No-Load Speed @ 6VDC230RPM
No-Load Current @ 6VDC190mA
Stall Current @ 6VDC250mA
Stall Torque @ 6VDC11.11 oz-in (0.8 kg-cm)
Gear Ratio48:1
Table 1. Abbreviated specs on a gearmotor.

DC Motor Control

There are two easily controllable parameters of a DC motor, direction and speed. To control the direction, you reverse the direction of the voltage through the motor. To control the speed, you pulse width modulate it.

Direction

To control a DC motor from a microcontroller, you use switching arrangement known as an H-bridge, consisting of four switches with the motor in the center. Figure 9 is the schematic for a typical H-bridge:

Schematic drawing of an H-bridge. At the top is a vertical line labeled +V. It branches horizontally to feed four switches, two in series with each other on each branch. A motor is connected to the junction where each pair of switches meets. The four switches form the vertical sides of the letter H, and the motor forms the crossbar. At the bottom of the diagram, the ends of the bottom switches are joined, and connected to ground. The switches are labeled, clockwise from top left, 1,3,4,2.
Figure 9. An H-bridge, at its simplest, is composed of four switches with a load at the center of them.

When switches 1 and 4 are closed and 2 and 3 are open, voltage flows from the supply to 1 to the motor to 4 to ground. When 2 and 3 are closed and 1 and 4 are open, polarity is reversed, and voltage flows from the supply to 3 to the motor to 2 to ground. Related video: H-Bridge

An H-bridge can be built from transistors, so that a microcontroller can switch the motor, like this in Figure 10:

Schematic drawing of an H-bridge made with transistors. The drawing is similar to the previous schematic, but the switches have been replaced with transistors. They are labeled, clockwise from top left, Q1, Q3,Q4, Q2. Q1 (top left) and Q3 (top right) are P-channel MOSFET transistors. Q2 and Q4 are N-channel MOSFET transistors. The source of Q1 and Q3 are connected to +V, and their drains are connected to the motor and to the sources of Q2 and Q4, respectively. The drains of Q2 and Q4 are connected to ground. The gates of transistors Q1 and Q2 are connected to each other, and the gates of transistors Q3 and Q4 are connected to each other.
Figure 10. An H-bridge made of transistors.

This schematic uses MOSFETs, which are good for controlling motors. The top two transistors above are P-channel, meaning that they allow current to pass when the gate voltage is low rather than high. The bottom two are N-channel, so that the proper two transistors always switch together. When the left control pin is high, transistor 1 (labeled Q1) turns off because it’s a P-channel and Q2 turns on because it’s an N-channel.  The same happens with Q3 and Q4. If you were using this circuit, you’d want to make sure that the control pins are always reversed; when one is high, the other is low. Related video: MOSFET Transistor

Although you can make your own H-bridges, it’s usually easier to use a controller manufactured specifically for the job. A pre-manufactured H-bridge chip will include diodes to protect the transistors from back voltage, sometimes a current sensing pin to sense the current the motor is drawing, and much more. There are many motor drivers available from various electronics suppliers. Look around to find one that suits your needs and price range.

Speed

A DC motor’s speed is proportional to the supplied voltage. If the voltage drops too far, the motor won’t get enough power to turn, but within a certain range, usually 50% of the rated voltage, the motor will run at varying speeds. The most effective way to adjust the speed is by using pulsewidth modulation. This means that you pulse the motor on and off at varying rates, to simulate a voltage. Related video: Why use PWM on DC Motors?

RC Servomotor

Servo motors are a variation on the gearhead motor coupled with a potentiometer to give feedback on the motor’s position. Figure 11 shows a photo of a small servomotor. The gears of the gearbox on a servo are attached to a potentiometer inside the case, and the pot is turned by the turning of the motor. The pot is connected to a capacitor in a resistor-capacitor circuit (R-C), and by pulsing this R-C circuit, you give the motor power to turn. When the motor turns, it changes the resistance of the R-C circuit, which in turn feeds the motor again. By pulsing the R-C circuit, you set the motor’s position in a range from 0 to 180 degrees. Related video: Meet the motors – servomotor

RC servomotor shown with different horns for attaching the motor to mechanisms
Figure 11. a small RC Servomotor

Servos have three wires to them, unlike most DC and gearhead motors, which have two. The first two in a servo are power and ground, and the third is a digital control line. This third line is used to set the position of a servo. Unlike other DC motors, you do not have to reverse the polarity of a servo’s power connections to reverse its direction.

Hobby servos, the kind most often used in small physical computing projects, usually take a pulse of between 1-2 ms every 18-20 ms. They rotate 0 to 180 degrees depending on the pulsewidth. A pulse of 1 ms will turn the motor to 0 degrees; 2 ms will turn it to 180 degrees. A servo needs to see a pulse every 18-20 ms even when it is not turning, to keep it in its current position, so once you’ve moved the motor to a new position, it’s essential to keep pulsing it with the same pulsewidth to keep it there.

For more on Servo motor control, see this lab: Servo Motor Control with an Arduino, and this video: Analog Output – Servo

Stepper Motor

Stepper motors are different than regular DC motors in that they don’t turn continuously, but move in a series of steps. A stepper motor is a motor that has multiple coils, not just one. By energizing each coil in sequence, you attract the shaft magnets to each coil in the sequence, and you can turn the motor in precise steps, rather than simply rotating continually. Figure 12 shows photos of stepper motors in varying sizes.

Photo of three stepper motors. The center one is opened up to show the coils inside.
Figure 12. Stepper motors

This design allows for very precise control of the motor: by proper pulsing, it can be turned in very accurate steps of set degree increments (for example, two-degree increments, half-degree increments, etc.). They are used in printers, disk drives, and other devices where precise positioning of the motor is necessary. Steppers usually move much slower than DC motors, since there is an upper limit to how fast you can step them (5-600 pulses per second, typically. However, unlike DC motors, steppers often provide more torque at lower speeds. They can be very useful for moving a precise distance. Furthermore, stepper motors have very high torque when stopped, since the motor windings are holding the motor in place like a brake.

To control a stepper, you use stepper driver that will energize the coils in the right order to make the motor move forward. There are plenty of libraries and driver modules and ICs that simplify the process. What follows is a low-level explanation of how steppers work.

Stepper Motor Control

There are two types of stepper motors, called unipolar and bipolar. The difference is in their wiring. Unipolar steppers have all of their coils joined by a center wire. Bipolar steppers have two coils, which are not joined. Unipolar motors typically have five wires, while bipolars have four or six wires. Unipolar stepper motor’s wiring works as shown in Figure 13:

Drawing of the wiring for a unipolar stepper motor, showing two variations. In the drawing on the left side of the frame, labeled "5-wire unipolar stepper", four coils of wire radiate out from a central connection labeled "center wire. The other ends of the four coils are labeled "coil 1" through "coil 4". In the drawing on the right, labeled "6-wire unipolar stepper" there are two coils side by side, labeled "coil 1" and "coil 2". There is a connection in the center of each coil as well, and those center wires are joined together.
Figure 13. The wiring for unipolar stepper motors. The center wires for the two coils are tied together in a unipolar stepper.

The extra two wires in a 6-wire bipolar stepper allow you to use it as a 4-coil motor instead of a 2-coil, by using the center wire on each coil as a common supply or ground. In addition, you can turn a 6-wire bipolar into a 5-wire unipolar by joining the two center wires as shown in Figure 14:

Drawing of the wiring for bipolar stepper motors, showing two variations. In the drawing on the left side of the frame, labeled "4-wire bipolar stepper", there are two coils next to each other, labeled "coil 1" and "coil 2". In the drawing on the right, labeled "6-wire bipolar stepper" there are two coils side by side, labeled "coil 1" and "coil 2". There is a connection in the center of each coil as well, but unlike the previous unipolar drawing, these two center connections are not connected to each other.
Figure 14. Wiring for bipolar stepper motors.

To determine which wire is which, measure the resistance of the coils. In a bipolar motor, the two coils will have the same resistance, and they are not connected to each other. So if you see infinite resistance, you have two wires on separate coils. When you find two pairs that have the same resistance, you’ve found the two coils of your bipolar stepper. In a six-wire bipolar motor, the resistance between the outside wires of a coil will be twice what it is between the center wire and either outer wire. In a unipolar stepper, the resistance between the center wire and any of the other four will be the same, and the resistance between any two outer wires will be twice what it is from the center wire to any of the outer wires, as shown in Figure 15 and Figure 16:

Schematic drawing of a unipolar stepper motor. Four coils radiate out from a common center point. They are all joined at the common center, labeled 5. The free ends of the coils are labeled, clockwise from the top, coil 1, coil 2, coil 3, coil 4. If the resistance between 5 and any of the others is X ohms, then the resistance between any of the other pairs (e.g. 2 to 4, 3 to 4, etc.) is 2X ohms.
Figure 15. Schematic drawing of a unipolar stepper motor. If the resistance between 5 and any of the others is X ohms, then the resistance between any of the other pairs (e.g. 2 to 4, 3 to 4, etc.) is 2X ohms.
Schematic drawing for two bipolar stepper motors. The one on the left has two coils side by side, with four wires. The wires are labeled, clockwise from top left, 1, 3, 4, 2. The one on the right has two coils shown side by side, and each has a center connection in addition to the end connections, for a total of six wires. The wires are labeled, clockwise from top left, 1,3,6,3,2,5. In both cases, if the resistance between the ends of either coils is X ohms (for example, 1 to 2, 3 to 4), then the resistance between either end and the middle of a coil is 0.5X ohms (for example, 1 to 5, 2, to 5, 3 to 6, 4 to 6).
Figure 16. Schematic drawing for two bipolar stepper motors. In both cases, if the resistance between the ends of either coils is X ohms, then the resistance between either end and the middle of a coil is 0.5X ohms.

Like other motors, the stepper requires more power than a microcontroller can give it, so you’ll need a separate power supply for it. Ideally you’ll know the voltage from the manufacturer, but if not, get a variable DC power supply, apply the minimum voltage that the supply can generate voltage across two wires of a coil (e.g. 1 to 2 or 3 to 4) and slowly raise the voltage until the motor is difficult to turn. It is possible to damage a motor this way, so don’t go too far. Typical voltages for a stepper might be 5V, 9V, 12V, 24V. Higher than 24V is less common, and frankly, above that it’s best not to guess. Related video: Connect 12V Power Supply

To power each coil, you supply voltage one side of the coil while grounding the other side. Typically, you drive a stepper motor with an H-bridge or an array of power transistors or MOSFETS.

To move the stepper, you apply voltage to each of the coils in a specific sequence. Typical phasing could go as shown in Table 2

StepWire 1Wire 2Wire 3Wire 4
1highlowhighlow
2lowhighhighlow
3lowhigh lowhigh
4high low lowhigh
Table 2. Stepper motor wire stepping sequence

Once you have the motor stepping in one direction, stepping in the other direction is simply a matter of doing the steps in reverse order. Knowing the position is a matter of knowing how many degrees per step, and counting the steps and multiplying by that many degrees. So for examples, if you have a 2-degree stepper, and it’s turned 180 steps, then it’s turned 2 x 180 degrees, or 360 degrees, or one full revolution.

For more on stepper control, see the notes on stepper motor control and this lab: Controlling a Stepper Motor With an H-Bridge.

For a more technical discussion of stepper motor control, see Control Of Stepping Motors, a tutorial, by Douglas W. Jones.

Analog Output

Introduction

This is an introduction to basic analog output on a microcontroller. In order to get the most out of it, you should know something about the following concepts.  You can check how to do so in the links below:

The following video links will help in understanding analog output:

Analog Output

Just as with input, there are times when you want greater control over  a microcontroller’s output than a digital output affords. You might want to control the brightness of a lamp, for example, or the turn of a pointer on a dial, or the speed of a motor. In these cases, you need  an analog output. The most likely things that you might want to vary directly from a microcontroller are lights, sound devices, or things controlled by motors. For many of these, there will be some other controller in between your microcontroller and the final output device. There are lighting dimmers, motor controllers, and so forth, most of which can be controlled using some form of serial digital communication. What’s covered here are simple electrical devices that can be controlled by a changing voltage. The Arduino and other digital microcontrollers generally can’t produce a varying voltage, they can only produce a high voltage or low voltage. Instead, you “fake” an analog voltage by producing a series of voltage pulses at regular intervals, and varying the width of the pulses. This is called pulse width modulation (PWM). The resulting average voltage is sometimes called a pseudo-analog voltage. The graph in Figure 1 shows how PWM works. You pulse the pin high for the same length of time that you pulse it low. The time the pin is high (called the pulsewidth) is about half the total time it takes to go from low to high to low again. This ratio is called the duty cycle and the total time from off through on to off again is the period. The duty cycle in this case 50%, and the effective voltage is half the total voltage.

Related video: Pseudo-Analog Explained

Graph of pulse-width-modulation (PWM) with a 50% duty cycle
Figure 1. PWM with a 50% duty cycle has an effective voltage of 50% of the maximum output voltage. Over time, the voltage is on half the time and off half the time.

If you make the duty cycle less than 50% by pulsing for a shorter amount of time than you pause, you get a lower effective voltage as shown in Figure 2:

Graph of pulse-width-modulation (PWM) with a 33% duty cycle. Effective voltage is a third of the maximum voltage
Figure 2. Graph of pulse-width-modulation (PWM) with a 33% duty cycle. Effective voltage is a third of the maximum voltage. Over time, the voltage is on one third the time and off two thirds of the time.

Related video: PWM graphed and see it on the scope

The period is usually a very small time, on the order of a few microseconds or milliseconds at most. The Arduino boards have a few pins which can generate a continuous PWM signal. On the Arduino Nano 33 IoT. they’re pins 2, 3, 5, 6, 9, 10, 11, 12, A2, A3, and A5. On the Arduino Uno, they’re pins 3, 5, 6, 9, 10, and 11. To control them, you use the analogWrite() command like so:

analogWrite(pin, duty);
  • pin refers to the pin you’re going to pulse
  • duty is a value from 0 – 255. 0 corresponds to 0 volts, and 255 corresponds to 5 volts. Every change of one point changes the pseudo-analog output voltage by 5/255, or  0.0196 volts.

Applications of Pulse Width Modulation

LED dimming

The simplest application of analogWrite() is to change the brightness of an LED. Connect the LED as you did for a digital output, as shown in Figure 3, then use analogWrite() to change its brightness. You’ll notice that it doesn’t change on a linear scale, however.

Related video: See the effect of PWM on the LED

Digital output schematic. A 220-ohm resistor is connected to an output from a microcontroller. The other end of the resistor is connected in series with the anode of an LED. The cathode of the LED is connected to ground.
Figure 3. You can dim an LED with the same circuit as you used for digital output. Just use analogWrite() on the pin to which the LED is connected.

DC Motor Speed Control

You can vary the speed of a DC motor using the analogWrite() command as well. The schematic is in Figure 4. You use the same transistor circuit as you would to turn on and off the motor, shown in Figure 4, but instead of setting the output pin of the microcontroller high or low, you use the analogWrite() on it. The transistor turns on and off at a rate faster than the motor can stop and start, so the result is that the motor appears to smoothly speed up and slow down.

For more on DC motor control, see the following links:

Schematic of motor control with an Arduino, using a MOSFET. One terminal of the motor is connected to +5 volts. The other side is connected to the source pin of a MOSFET transistor. The gate of the transistor is connected to a microcontroller's output pin. The drain pin of the MOSFEt is connected to ground. There is a diode connected in parallel with the transistor. its anode is connected to the drain, and its cathode is connected to the source.
Figure 4. Schematic of motor control with an Arduino, using a MOSFET. One terminal of the motor is connected to a high-current power supply and the other is connected to the MOSFET’s drain pin. The MOSFET’s source pin is connected to ground and its gate is connected to a microcontroller output pin. A protection diode’s cathode is attached to the source of the MOSFET, and the anode is connected to the drain.
Note: Filter circuits

Filter circuits are circuits which allow voltage changes of only a certain frequency range to pass. For example, a low-pass filter would block frequencies above a certain range. This means that if the voltage is changing more than a certain number of times per second, these changes would not make it past the filter, and only an average voltage would be seen. Imagine, for example, that your PWM is operating at 1000 cycles per second, or 1000 Hertz (Hz).  If you had a filter circuit that blocked frequencies above 1000 Hz, you would see only an average voltage on the other side of the filter, instead of the pulses. A basic low-pass filter consists of a resistor and a capacitor, connected as shown in Figure 5:

Schematic drawing of a low-pass filter for an LED. The LED's anode is connected to +5 volts. Its cathode connects to a resistor. The resistor's other end connects to the PWM output of a microcontroller. The junction where the cathode of the LED and the resistor meet is also connected to a capacitor. The other terminal of the capacitor is connected to ground.
Figure 5. Schematic: A basic low-pass filter. An LED’s anode is connected to voltage and its cathode is attached to one terminal of a capacitor. The capacitor’s other terminal is connected to ground. A resistor connects to the junction where the the LED and the capacitor meet. The other end of the resistor is connected to a microcontroller’s output pin.

The relationship between frequency blocked and the values of the capacitor and resistor is as follows:

frequency = 1/ (2π *resistance * capacitance)

A 1.5-kilohm resistor and a 0.1-microfarad capacitor will cut off frequencies above around 1061 Hz. If you’re interested in filters, experiment with different values from there to see what works best.

Servomotors

Perhaps the most exciting thing you can do as analog output is to control the movement of something. One simple way to do this is to use a servomotor. Servomotors are motors with a combination of gears and an embedded potentiometer (variable resistor) that allows you to set their position fairly precisely within a 180-degree range. They’re very common in toys and other small mechanical devices. They have three wires:

  • power (usually +5V)
  • ground
  • control

Connect the +5V directly to a 5V power source (the Arduino’s 5V or 3.3V output will work for one servo, but not for multiple servos). Ground it to the same ground as the microcontroller. Attach the control pin to any output pin on the microcontroller. Then you need to send a series of pulses to the control pin to set the angle. The longer the pulse, the greater the angle.

To pulse the servo, you generally give it a 5-volt, positive pulse between 1 and 2 milliseconds (ms) long, repeated about 50 times per second (i.e. 20 milliseconds between pulses). The width of the pulse determines the position of the servo. Since servos’ travel can vary, there isn’t a definite correspondence between a given pulse width and a particular servo angle, but most servos will move to the center of their travel when receiving 1.5-ms pulses. This is a special case of pulse width modulation, in that you’re modifying the pulse, but the period remains fixed at 20 milliseconds. You could write your own program to do this, but Arduino has a library for controlling servos. See the Servo lab for more on this.

Related video: Analog Output – Servo

Changing Frequency

Pulse width modulation can generate a pseudo-analog voltage for dimming and motor control, but can you use it to generate pitches on a speaker? Remember that you’re changing the duty cycle but not the period of the signal, so the frequency doesn’t change. If you were to connect a speaker to a pin that’s generating a PWM signal, you’d hear one steady pitch.

If you want to generate a changing tone on an Arduino microcontroller, however, there is a tone() command that will do this for you:

tone(pin, frequency);

This command turns the selected pin on and off at a frequency that you set. With this command, you can generate tones reasonably well. For more on this, see the Tone Output lab.

Related video: Analog Output – Tone

Ranges of Values

As a summary, Table 1 below shows the ranges of values for digital input/output and analog input/output, which have been discussed in Digital Input & Output, Analog Input, and this page.

DigitalInput (Digital Pins)0 [LOW] or 1 [HIGH] (2^0) 0V or 3.3V (newer microcontrollers) 0V or 5V (older microcontrollers)
Output (Digital Pins)0 [LOW] or 1 [HIGH] (2^0) 0V or 3.3V (newer microcontrollers) 0V or 5V (older microcontrollers)
AnalogInput (Analog Input Pins)0 ~ 1023 (<210)3.3 / 210
Output (Digital PWM Pins)0 ~ 255 (<28)3.3 / 28
Table 1. The Ranges of Values for Digital/Analog Input/Output

 

Videos: Digital and Analog Input and Output

ITP Videos by Jeff Feddersen on Vimeo.

Digital Input and Output

The Fixed Resistor is Necessary!

Ohm Part 2 from ITP_NYU on Vimeo.

Digital input with internal pull-up resistors

Analog Input

Analog Output

Pseudo-analog output:

Tone Output

Servo Control using Pulse Width Modulation

Analog Output: Motor Control

Multiple Inputs or Outputs

Multiplexers

Jeff explains how a multiplexer allows you to connect multiple analog or digital input circuits to a single microcontroller input.

Shift Registers

Jeff and Tom explain how to use shift registers to control multiple digital outputs.

Binary Coded Decimal (BCD) controller

Jeff shows you how to control multiple LEDs on a 7-segment numerical LED display using a Binary Coded Decimal (BCD) controller