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.

1
2
3
4
5
6
7
8
9
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.

1
2
3
4
5
6
7
8
9
10
11
12
13
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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#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.

Lab: Analog In with an Arduino

In this lab, you’ll learn how to connect a variable resistor to a microcontroller and read it as an analog input. You’ll be able to read changing conditions from the physical world and convert them to changing variables in a program.

Introduction

In this lab, you’ll learn how to connect a variable resistor to a microcontroller and read it as an analog input. You’ll be able to read changing conditions from the physical world and convert them to changing variables in a program.

Many of the most useful sensors you might connect to a microcontroller are analog input sensors. They deliver a variable voltage, which you read on the analog input pins using the analogRead() command.

What You’ll Need to Know

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

Things You’ll Need

Figures 1-12 show the parts you’ll need for this exercise. Click on any image for a larger view.

Set Up 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. Figures 13 and 14 show how to do this for an Arduino Uno and an Arduino Nano 33 IoT.

As shown in Figure 13, 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.


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 13. An Arduino Uno on the left connected to a solderless breadboard, right.
Arduino Nano on a breadboard.
Figure 14. Breadboard view of an Arduino Nano mounted on a breadboard

Images made with Fritzing

In Figure 14, 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.

Add a Potentiometer and LED

Connect the wiper of a potentiometer to analog in pin 0 of the module and its outer connections to voltage and ground. Connect a 220-ohm resistor to digital pin 9. You can replace the LED with a speaker if you prefer audible output. Connect the anode of an LED to the other side of the resistor, and the cathode to ground as shown below. See Figure 15 and Figure 16 to learn how to do this with an Arduino Uno. Figure 17 shows a breadboard view of an Arduino Nano for the same circuit.

Related Video: Potentiometer schematic

Figure 15. Schematic view of a potentiometer connected to analog in 0 of an Arduino and an LED connected to digital pin 9. Connect the voltage lead of the potentiometer to 5V for Uno, 3.3V for Nano 33 IoT.
Breadboard drawing of a potentiometer connected to analog in 0 of an Arduino and an LED connected to digital pin 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. On the breadboard, a potentiometer is connected to pins 21 through 23 in the left center section of the board. A red wire connects row 21 in the left center section to the voltage bus on the left side. A black wire connects row 23 in the left center section to the ground bus on the left side. A blue wire connects row 22 to the Arduino's analog in pin 0. A 220-ohm resistor straddles the center divide of the breadboard, connecting to row 17 on both sides. In the left center section of the breadboard, a blue wire connects row 17 to pin D9 of the Arduino. In the right center section, the anode of an LED is connected to row 17. The cathode of the LED is in row 16. A black wire connects row 16 to the ground bus on the right side of the board.
Figure 16. Breadboard view of a potentiometer connected to analog in 0 of an Arduino and an LED connected to digital pin 9.

Breadboard view of Arduino Nano with an analog input and LED output.
Figure 17. Breadboard view of Arduino Nano with an analog input and LED output.

Figure 17 shows the breadboard view of an Arduino Nano connected to a potentiometer and an LED. The +3.3 volts and ground pins of the Arduino are connected by red and black wires, respectively, to the left side rows of the breadboard. +3.3 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. The potentiometer is mounted  in the left center section of the solderless breadboard. Its outside pins are connected to the voltage and ground buses, respectively  There is a wire connecting to analog in 0 of the nano (physical  pin 4) to the the center pin of the potentiometer. An LED is mounted in the right center section of the board, with a 220-ohm resistor attached to its anode (long leg). The other end of the resistor connects to the Nano’s digital pin 9 (physical pin 27). The cathode of the LED (short leg) connects to ground. If you’re using a speaker instead of the LED, connect it to the same connections as the LED.


Program the Module

Now that you have the board wired correctly, program your Arduino as follows:

Related Video

First, establish some global variables: one to hold the value returned by the potentiometer, and another to hold the brightness value. Make a global constant to give the LED’s pin number a name.

1
2
3
const int ledPin = 9;       // pin that the LED is attached to
int analogValue = 0;        // value read from the pot
int brightness = 0;         // PWM pin that the LED is on.

In the setup() method, initialize serial communications at 9600 bits per second, and set the LED’s pin to be an output.

1
2
3
4
5
  // initialize serial communications at 9600 bps:
    Serial.begin(9600);
    // declare the led pin as an output:
    pinMode(ledPin, OUTPUT);
}

In the main loop, read the analog value using analogRead() and put the result into the variable that holds the analog value. Then divide the analog value by 4 to get it into a range from 0 to 255. Then use the analogWrite() command to face the LED. Then print out the brightness value. An alternate loop function for the speaker follows right after the first one.

1
2
3
4
5
6
void loop() {
    analogValue = analogRead(A0);    // read the pot value
    brightness = analogValue /4;       //divide by 4 to fit in a byte
    analogWrite(ledPin, brightness);   // PWM the LED with the brightness value
    Serial.println(brightness);        // print the brightness value back to the serial monitor
}

If you’re replacing the LED with a speaker, here’s an alternate loop function that will play a changing tone on the speaker:

1
2
3
4
5
6
void loop() {
    analogValue = analogRead(A0);      // read the pot value
    frequency = (analogValue /4) * 10; // divide by 4 to fit in a byte, multiply by 10 for a good tonal range
    tone(pinNumber, frequency);        // make a changing tone on the speaker
    Serial.println(brightness);        // print the brightness value back to the serial monitor
}

When you run this code, the LED should dim up and down as you turn the pot, and the brightness value should show up in the serial monitor.

Other variable resistors

You can use many different types of variable resistors for analog input. For example, the pink monkey in the photo below has his arms wired with flex sensors. These sensors change their resistance as they are flexed. When the monkey’s arms move up and down, the values of the flex sensors change the brightness of two LEDs. The same values could be used to control servo motors, change the frequency on a speaker, or move servo motors.

Related Video: Wiring an FSR (force sensitive resistor)
Related Video: Wiring a photocell to measure light

Photo of a stuffed pink monkey with flex sensors attached to its arms. The flex sensors are attached with tie-wraps at the shoulder and wrist of the monkey. The wired ends of the sensors are behind the monkey's neck. The wires lead away from the monkey's back discreetly.
Figure 18. A stuffed pink monkey with flex sensors attached

Note on Soldering Sensor Leads

Flex sensors and force-sensing resistors melt easily, so unless you are very quick with a soldering iron, it’s risky to solder directly to their leads. See Figure 19-21 to learn about three better solutions:

Photo of the metal ends of a force-sensing resistor with wire-wrapped wiring. Very thin single-strand wire is wrapped tightly around each of the two metal connections of the sensor, making a tight connection with no soldering.
Figure 19. Wire-wrapped connections of a force-sensing resistor
Photo of the metal ends of a force-sensing resistor mounted in a screw terminal. The screw terminal has three headers, and the force-sensing resistor is connected to two of them. a 10-kilohm resistor (with brown, black, orange, and gold bands) is connected to one of the two terminals with the FSR. The other end of the resistor is screwed into the third terminal.
Figure 20. Screw terminal connection for force sensing resistor
Photo of the metal ends of a force-sensing resistor mounted in breakaway socket headers. The socket headers, separated by 0.1 inches (2.5mm) have wires soldered to their metal ends. This way, the soldering happens to the socket pins. The socket headers are cheaper than the sensor, so the cost of damaging them by soldering is less than soldering the sensors.
Figure 21. Force sensing resistor connected to breakaway socket headers

Adafruit has a good FSR tutorial as well.

If you’d like to read a changing light level, you can use a phototransistor for the job. Phototransistors are not variable resistors like photoresistors (which are shown in this video), but they perform similarly are made from less toxic materials. They are actually transistors in which the light falling on the sensor acts as the transistor’s base. Like photoresistors, they are sensitive to changes in light, and they work well in the same voltage divider circuit. Figure 22 shows how to connect a phototransistor and a 10-kilohm resistor as an analog input:

Figure 22. Breadboard view of an Arduino Nano connected to a phototransistor as an analog input. The long leg of the phototransistor connects to voltage, and the long leg connects to the input pin. The 10-kilohm fixed resistor then connects from the input pin to ground.

Different phototransistors will have different sensitivities to light. For example, this model from Everlight, which has a clear top, is most sensitive to 390 – 700 nm light range, with a peak at 630nm (orange-red). This model from Excelitas has a colored top to block IR light, and has a range from 450 -700nm, with a peak at 585nm (yellow). For the frequencies of the visible light spectrum, see this chart from Wikipedia.


Figure 23 and 24 shows an example circuit much like the pink monkey circuit (Figure 18) above, but with force-sensing resistors instead of flex sensors.

On the breadboard, two force-sensing resistors are mounted in rows 16 and 17 and 24 and 25, respectively, in the left center section of the board. Two red wires connects rows 16 and 24 in the left center section to the voltage bus on the left side. Two 10-kilohm resistors (orange, black, brown, and gold bands) connect rows 17 and 25 to the ground bus on the left hand side. Two blue wires connect from rows 17 and 25 to analog in pins 0 and 1 of the Arduino, respectively. Two 220-ohm resistors straddle the center divide of the breadboard, connecting to row 7 on both sides and 11 on both sides, respectively. In the left center section of the breadboard, two blue wires connect rows 7 and 11 to pins D10 and D9 of the Arduino, respectively. In the right center section, the anodes of two LEDs are connected to rows 7 and 11, respectively. The cathodes of the LED are in rows 6 and 10, respectively. Two black wire connects row 6 and 10 to the ground bus on the right side of the board.

Schematic drawing of two force-sensing resistors and two LEDs attached to an Arduino. The Arduino is represented by a rectangle in the middle with lines on each side representing the pin connections. On the left side of the rectangle, two variable resistor are connected to analog in pins 0 and 1, respectively. The other ends of the variable resistors are connected to the 5-volt pin on the Arduino, shown at the top of the rectangle. Two fixed 10-kilohm resistors are connected to analog in pins 0 and 1 as well. The other ends of the fixed resistors are connected to ground, shown on the bottom of the rectangle. On the right side, two 220-ohm resistors are connected to pins D9 and D10, respectively. The other connections of the resistors are connected to the anodes of two LEDs. The cathodes of the LEDs are connected to the ground pin of the Arduino.
Figure 23. Schematic view of two force-sensing resistors and two LEDs attached to an Arduino.
On the breadboard, two force-sensing resistors are mounted in rows 16 and 17 and 24 and 25, respectively, in the left center section of the board. Two red wires connects rows 16 and 24 in the left center section to the voltage bus on the left side. Two 10-kilohm resistors (orange, black, brown, and gold bands) connect rows 17 and 25 to the ground bus on the left hand side. Two blue wires connect from rows 17 and 25 to analog in pins 0 and 1 of the Arduino, respectively. Two 220-ohm resistors straddle the center divide of the breadboard, connecting to row 7 on both sides and 11 on both sides, respectively. In the left center section of the breadboard, two blue wires connect rows 7 and 11 to pins D10 and D9 of the Arduino, respectively. In the right center section, the anodes of two LEDs are connected to rows 7 and 11, respectively. The cathodes of the LED are in rows 6 and 10, respectively. Two black wire connects row 6 and 10 to the ground bus on the right side of the board.
Figure 24. Breadboard view of two force-sensing resistors and two LEDs attached to an Arduino.

The circuit above works for any variable resistor. You could replace the force-sensing resistors with flex sensors to use the monkey toy above with this circuit. Two resistors placed in series like this are called a voltage divider. There are two voltage dividers in the circuit shown, one on analog in 0 and one on analog in 1. The fixed resistor in each circuit should have the same order of magnitude as the variable resistor’s range. For example, if you’re using a flex sensor with a range of 50 – 100 kilohms, you might use a 47-kilohm or a 100-kilohm fixed resistor. If you’re using a force sensing resistor that goes from infinity ohms to 10 ohms, but most of its range is between 10 kilohms and 10 ohms, you might use a 10-kilohm fixed resistor.

The code above assumed you were using a potentiometer, which always gives the full range of analog input, which is 0 to 1023. Dividing by 4 gives you a range of 0 to 255, which is the full output range of the analogWrite() command. The voltage divider circuit, on the other hand, can’t give you the full range. The fixed resistor in the circuit limits the range. You’ll need to modify the code or the resistor if you want a different range.

Finding Your Sensor Range

Related Video: Use map() to detect the sensor’s state

To find out your range, open the serial monitor and watch the printout as you press the FSR or flex the flex sensor. Note the maximum value and the minimum value. Then you can map the range that the sensor actually gives as input to the range that the LED needs as output.

For example, if your photocell gives a range from 400 to 900, you’d do this:

1
2
3
// map the sensor value from the input range (400 - 900, for example) to the output range (0-255):
int brightness = map(sensorValue, 400, 900, 0, 255);
analogWrite(ledPin, brightness);

You know that the maximum input range of any analog input is from 0 to 5 volts. So if you wanted to know the voltage on an analog input pin at any point, you could do some math to extrapolate it in your loop() like so:

1
2
3
4
5
6
7
8
9
10
void loop() {
  // read the sensor on analog pin 0:
  int sensorValue = analogRead(A0);
  // Convert the analog reading (which goes from 0 - 1023) to a voltage (0 - 5V):
  float voltage = sensorValue * (5.0 / 1023.0);
  // for 0-3.3V use the line below:
  // voltage = sensorValue * (3.3 / 1023.0);
  // print out the value you read:
  Serial.println(voltage);
}

Now write a sketch to control the red LED with the first sensor (we’ll call it the right hand sensor) and the green LED with the second sensor (we’ll call it the left hand sensor). First, make two constants for the LED pin numbers, and two variables for the left and right sensor values.

1
2
3
4
const int redLED = 10;     // pin that the red LED is on
const int greenLED = 11;   // pin that the green LED is on
int rightSensorValue = 0// value read from the right analog sensor
int leftSensorValue = 0;   // value read from the left analog sensor

In the setup(), initialize serial communication at 9600 bits per second, and make the LED pins outputs.

1
2
3
4
5
6
7
void setup() {
  // initialize serial communications at 9600 bps:
  Serial.begin(9600);
  // declare the led pins as outputs:
  pinMode(redLED, OUTPUT);
  pinMode(greenLED, OUTPUT);
}

Start the main loop by reading the right sensor using analogRead(). Map it to a range from 0 to 255. Then use analogWrite() to set the brightness of the LED from the mapped value. Print the sensor value out as well.

1
2
3
4
5
6
7
8
void loop() {
  rightSensorValue = analogRead(A0); // read the pot value
  // map the sensor value from the input range (400 - 900, for example)
  // to the output range (0-255). Change the values 400 and 900 below
  // to match the range your analog input gives:
  int brightness = map(rightSensorValue, 400, 900, 0, 255);
  analogWrite(redLED, brightness);  // set the LED brightness with the result
  Serial.println(rightSensorValue);   // print the sensor value back to the serial monitor

Finish the main loop by doing the same thing with the left sensor and the green LED.

1
2
3
4
5
6
7
8
// now do the same for the other sensor and LED:
  leftSensorValue = analogRead(A1); // read the pot value
  // map the sensor value to the brightness again. No need to
  // declare the variable again, since you did so above:
  brightness = map(leftSensorValue, 400, 900, 0, 255);
  analogWrite(greenLED, brightness);  // set the LED brightness with the result
  Serial.println(leftSensorValue);   // print the sensor value back to the serial monitor
}

Mapping works for audible tones as well. Human hearing is in a range from 20Hz to 20 kHz, with 100 – 10000 Hz being a reasonable middle ground so if your input is in a range from 0 to 255, you can quickly get audible tones by mapping like so:

int pitch = map(input, 0, 255, 100, 10000);

When you run this, you should see the LEDs changing in brightness, or hear the speaker changing in pitch, as you press the sensors. This is the central function of analog sensors on a microcontroller: to allow for a variable range of input to control a variable range out output. Whether your sensor is read through an analog sensor like this, or through synchronous serial interfaces as you’ll see in the SPI and I2C labs, you always need to find out how the range of action from the user relates to the range of values that the sensor produces. Once you’re comfortable with this concept, get to know how to read the change in a sensor’s readings as well.

Lab: Digital Input and Output with an Arduino

In this lab, you’ll connect a digital input circuit and a digital output circuit to a microcontroller. Though this is written for the Arduino microcontroller module, the principles apply to any microcontroller.

Introduction

In this lab, you’ll connect a digital input circuit and a digital output circuit to a microcontroller. Though this is written for the Arduino microcontroller module, the principles apply to any microcontroller.

Digital input and output are the most fundamental physical connections for any microcontroller. The pins to which you connect the circuits shown here are called General Purpose Input-Output, or GPIO, pins. Even if a given project doesn’t use digital in and out, you’ll often use LEDs and pushbuttons or switches during the development for testing whether everything’s working.

What You’ll Need to Know

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

Things You’ll Need

Figures 1-8 show the parts you’ll need for this exercise. Click on any image for a larger view.

Photo of an Arduino Nano 33 IoT module. The USB connector is at the top of the image, and the physical pins are numbered in a U-shape from top left to bottom left, then from bottom right to top right.
Figure 1. Arduino Nano 33 IoT
Photo of flexible jumper wires
Figure 2. Jumper wires.  You can also use pre-cut solid-core jumper wires.
Photo of a solderless breadboard
Figure 3. A solderless breadboard
Photo of an 8 ohm speaker
Figure 4. An 8 ohm speaker (optional).This is a good alternate to the LED if you prefer audible output.

Photo of a handful of LEDs
Figure 5. LEDs. The long leg goes to voltage and the short leg goes to ground
Photo of a handful of 220-ohm resistors.
Figure 6. 220-ohm resistors. These ones are 4-band resistors. They are colored red, red, brown and gold, which signifies 2, 2 (red, red), times 10 (brown), with a 5% tolerance (gold).
Photo of a handful of 10-kilohm resistors
Figure 7. 10-kilohm resistors. These ones are 5-band resistors. They are colored brown, black, black, red, brown, which signifies 1 (brown), 0, 0 (black, black), times 100 (red), with a 1% tolerance (brown). Four-band 10-kilohm resistors are colored brown, black, orange (1, 0, times 1000), gold (5% tolerance).
Photo of four breadboard-mounted pushbuttons
Figure 8. A pushbutton. Any switch will do the job as well.

The video Video: Digital Output covers the material in this lab.

Prepare the breadboard

If you’re using a brand new breadboard, you might want to check out these videos before you get started, to prep your board and care for your microcontroller.

Connect power and ground on the breadboard to power and ground from the microcontroller. On the Arduino Uno, use the 5V or 3.3V (depending on your model) and any of the ground connections. Figures 9 and 10 show how to do this for an Arduino Uno and for an Arduino Nano 33 IoT.

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.

As shown in Figure 9, 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.


Images made with Fritzing

Related video: Overview of the Arduino microcontroller

Related video: Connect Power and Ground using wires

Add a Digital Input (a Pushbutton)

Connect a pushbutton to digital input 2 on the Arduino. Figures 11 and 12 show the schematic and breadboard views of this for an Arduino Uno, and Figure 13 shows the breadboard view for an Arduino 33 IoT. The pushbutton shown below is a store-bought momentary pushbutton, but you can use any pushbutton. Try making your own with a couple of pieces of metal as shown in the Switches lab.

Related video: Connect a pushbutton to a digital pin

What Are The Input and Output Pins?

If you’re not sure what pins are the inputs and outputs of your board, check the Microcontroller Pin Functions page for more information. The reference page on the  standard breadboard layouts for the Uno, Nano series, and MKR series might be useful as well.

Schematic view of an Arduino connected to a pushbutton. One side of the pushbutton is connected to digital pin 2 of the Arduino. A 10-kilohm resistor is connected from digital pin 2 to ground as well. The other side of the pushbutton is attached to +5V.
Figure 11. Schematic view of an Arduino connected to a pushbutton.
Breadboard view of an Arduino connected to a pushbutton. 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. The pushbutton is mounted across the middle divide of the solderless breadboard. A 10-kilohm resistor connects from the same row as pushbutton's bottom left pin to the ground bus on the breadboard. There is a wire connecting to digital pin 2 from the same row that connects the resistor and the pushbutton. The top left pin of the pushbutton is connected to +5V.
Figure 12. Breadboard view of an Arduino connected to a pushbutton.

Breadboard view of an Arduino Nano connected to a pushbutton. 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. The pushbutton is mounted across the middle divide of the solderless breadboard. A 10-kilohm resistor connects from the same row as pushbutton's bottom left pin to the ground bus on the breadboard. There is a wire connecting to digital pin 2 from the same row that connects the resistor and the pushbutton. The top left pin of the pushbutton is connected to +3.3V.
Figure 13. Breadboard view of an Arduino Nano connected to a pushbutton.

Figure 13 shows the breadboard view of an Arduino Nano connected to a pushbutton. The +3.3 volts and ground pins of the Arduino are connected by red and black wires, respectively, to the left side rows of the breadboard. +3.3 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. The pushbutton is mounted across the middle divide of the solderless breadboard. A 10-kilohm resistor connects from the same row as pushbutton’s bottom left pin to the ground bus on the breadboard. There is a wire connecting to digital pin 2 from the same row that connects the resistor and the pushbutton. The top left pin of the pushbutton is connected to +3.3V.


Note on The Pulldown Resistor

What happens if you don’t include the resistor connecting the pushbutton to ground? The resistor connecting the pushbutton is a pulldown resistor. It provides the digital input pin with a connection to ground. Without it, the input will behave unreliably.

If you don’t have a 10-kilohm resistor for the pushbutton, you can use any reasonably high value. 4.7K, 22K, and even 1 Megohm resistors have all been tested with this circuit and they work fine.  See the digital input and output notes for more about the digital input circuit.

If you’re not sure about the resistor color codes, use a multimeter to measure the resistance of your resistors in ohms, and check this resistor color code calculator.

Add Digital Outputs (LEDs)

Connect a 220-ohm resistor and an LED in series to digital pin 3 and another to digital pin 4 of the Arduino. Figures 14,  15, and 16 below show the schematic view as well as the breadboard view for both the Uno and the Nano. If you prefer an audible tone over a blinking LED, you can replace the LEDs with speakers or buzzers. The 220-ohm resistor will work with LED, speaker, or buzzer.

Arduino connected to pushbutton and two LEDs, Schematic view. The pushbutton is connected as described in the image above. Digital pins 3 and 4 are connected to 22-ohm resistors. The other sides of the resistors are connected to the anodes (long legs) of two LEDs. The cathodes of the LEDs are both connected to ground.
Figure 14. Arduino connected to pushbutton and two LEDs, Schematic view.
Arduino Nano connected to pushbutton and two LEDs, Breadboard view. The pushbutton is connected as described in the image above. Digital pins 3 and 4 are connected to 22-ohm resistors. The resistors are mounted across the center divide of the breadboard, each in its own row. The other sides of the resistors are connected to the anodes (long legs) of two LEDs. The cathodes of the LEDs are both connected to ground.
Figure 15. Arduino Uno connected to pushbutton and two LEDs, Breadboard view.

Arduino Nano connected to pushbutton and two LEDs, Breadboard view. The pushbutton is connected as described in the image above. Digital pins 3 and 4 are connected to 22-ohm resistors. The resistors are mounted across the center divide of the breadboard, each in its own row. The other sides of the resistors are connected to the anodes (long legs) of two LEDs. The cathodes of the LEDs are both connected to ground.
Figure 16. Arduino Nano connected to pushbutton and two LEDs, Breadboard view.

Note on LED Resistor Values

For the resistor on the LED, the higher the resistor value, the dimmer your LED will be. So 220-ohm resistors give you a nice bright LED, 1-kilohm will make it dimmer, and 10K or higher will likely make it too dim to see. Similarly, higher resistor values attenuate the sound on a speaker, so a resistor value above 220-ohm will make the sound from your speaker or buzzer quieter.

Related video: Resistors for an LED

Program the Arduino

Make sure you’re using the Arduino IDE version 1.8.19 or later. If you’ve never used the type of Arduino module that you’re using here (for example, a Nano 33 IoT), you may need to install the board definitions. Go to the Tools Menu –> Board submenu –> Board Manager. A new window will pop up. Search for your board’s name (for example, Nano 33 IoT), and the Boards manager will filter for the correct board. Click install and it will install the board definition.

Connect the microcontroller to your computer via USB. When you plug the Arduino into your computer, you’ll find a new serial port in the Tools–>Port menu (for details on installing the software, and USB-to-serial drivers for older Arduino models on Windows, see the Arduino Getting Started Guide). In the MacOS, the name look like this: /dev/tty.usbmodem-XXXX (Board Type) where XXXX are part of the board’s unique serial number and Board Type is the board type (for example, Arduino Uno, Nano 33 IoT, MKRZero, etc.)  In Windows it will be called COM and a number. Figure 17 shows the tools men and its Port submenu.

Screenshot of the Arduino Tools menu showing the Ports submenu
Figure 17. The Arduino Tools menu showing the Ports submenu

Now it’s time to write a program that reads the digital input on pin 2. When the pushbutton is pressed, turn the yellow LED on and the red one off. When the pushbutton is released, turn the red LED on and the yellow LED off.

In your setup() method, you need to set the three pins you’re using as inputs or outputs, appropriately.

1
2
3
4
5
void setup() {
  pinMode(2, INPUT);    // set the pushbutton pin to be an input
  pinMode(3, OUTPUT);   // set the yellow LED pin to be an output
  pinMode(4, OUTPUT);   // set the red LED pin to be an output
}

In the main loop, first you need an if-then-else statement to read the pushbutton. If you’re replacing the LED with a buzzer, the code below will work as is. If you’re using a speaker, there’s an alternative main loop just below the first one:

1
2
3
4
5
6
7
8
9
10
11
12
13
void loop() {
   // read the pushbutton input:
   if (digitalRead(2) == HIGH) {
     // if the pushbutton is closed:
     digitalWrite(3, HIGH);    // turn on the yellow LED
     digitalWrite(4, LOW);     // turn off the red LED
   }
   else {
     // if the switch is open:
     digitalWrite(3, LOW);     // turn off the yellow LED
     digitalWrite(4, HIGH);    // turn on the red LED
   }
 }

Here’s an alternate loop function for an audible output on two speakers. If you want to use only one speaker, try alternating the tone frequency from 440Hz (middle A) to 392Hz (middle G):

1
2
3
4
5
6
7
8
9
10
11
12
13
void loop() {
   // read the pushbutton input:
   if (digitalRead(2) == HIGH) {
     // if the pushbutton is closed:
     tone(3, 440);    // turn on the first speaker to 440 Hz
     noTone(4);     // turn off the second speaker
   }
   else {
     // if the switch is open:
     noTone(3);     // turn off the first speaker
     tone(4, 440);    // turn on the second speaker to 440 Hz
   }
 }

Once you’re done with that, you’re ready to compile your sketch and upload it. Click the Verify button to compile your code. Then click the Upload button to upload the program to the module. After a few seconds, the following message will appear in the message pane to tell you the program was uploaded successfully. Related video: Upload the code to the Arduino

Binary sketch size: 5522 bytes (of a 7168 byte maximum)

Press the pushbutton and watch the LEDs change until you get bored. That’s all there is to basic digital input and output!

The Uno vs Newer Boards

If you’ve used an Uno r3 board before (the “classic Uno”), and are migrating to the Nano or a newer board, you may notice that the serial connection behaves differently. When you reset the MKR, Nano, Uno R4, or Leonardo boards,  or upload code to them, the serial port seems to disappear and re-appear. Here’s why:

There is a difference between the Uno R3 and most of the newer boards like the MKR boards, the Nano 33 IoT and BLE, the Leonardo and the Uno R4: the Uno R3 has a USB-to-serial chip on the board which is separate from the microcontroller that you’re programming. The Uno R3’s processor, an ATMega328, cannot communicate natively via USB, so it needs the separate processor. That USB-to-serial chip is not reset when you upload a new sketch, so the port appears to be there all the time, even when your Uno R3 is being reset.

The newer boards can communicate natively using USB. They don’t need a separate USB-to-serial chip. Because of this, they can be programmed to operate as a mouse, as a keyboard, or as a USB MIDI device.  Since they are USB-native, their USB connection gets reset when you upload new code or reset the processor. That’s normal behavior for them; it’s as if you turned off the device, then turned it back on. Once it’s reset, it will let your computer’s operating system know that it’s ready for action, and your serial port will reappear. This takes a few seconds. It means you can’t reset the board, and then open the serial port in the next second. You have to wait those few seconds until the Arduino board has made itself visible to the computer’s operating system again.

If you have problems with the UBS-native boards’ serial connection, tap the reset button once, then wait a few seconds, then see if the port shows up again once the board has reset itself. You can also double-tap the reset on the MKR and Nano boards to cause the processor to reset and go into a sleep mode. In this mode, the USB connection will reset itself, but your sketch won’t start running. The built-in LED will glow softly. Then upload a blank sketch. From there, you can start as if your board was brand new.

Related video: Digital Output

Applications

Many projects can be made with just digital input and output. For example, a combination lock is just a series of pushbuttons that have been pushed in a particular sequence. Consider the cymbal-playing monkey in Figures 18-20:

A mechanical toy monkey that plays cymbals. The cymbals are covered with aluminum foil. The foil is connected to wires, and the wires are connected to an Arduino and breaboard. The two wires from the cymbals act as a switch when they are hit together.
Figure 18. A mechanical toy monkey that plays cymbals. The cymbals are covered with aluminum foil. The foil is connected to wires, and the wires are connected to an Arduino and breadboard. The two wires from the cymbals act as a switch when they are hit together.

The monkey’s cymbals can be turned into a switch by lining them with tin foil and screwing wires to them:

Detail of the cymbal monkey's cymbal. It is covered with tin foil, as described above.
Figure 19. Detail of the cymbal monkey’s cymbal. It is covered with aluminum foil, as described above.
Detail of the other cymbal. This one is also covered with aluminum foil.
Figure 20. Detail of the other cymbal. This one is also covered with aluminum foil.

Those wires can be run to a breadboard and used as a switch. Then the microcontroller could be programmed to listen for pattern of cymbal crashes, and if it sees that pattern, to open a lock by turning on a digital output.

Consider the project ideas from Project 1 for more applications you can do with simple input and output.

Lab: Switches and Pushbuttons

In this lab you will learn about different types of switches and their terminology

Introduction

In this lab you will learn about different types of switches and their terminology. You’ll use switches and pushbuttons frequently in physical computing projects, as shown in Figure 1, and it’s helpful to be aware of the terminology used in describing them when shopping for them or trying to understand tutorials that use them.

An assortment of switches and pushbuttons. This image includes an arcade-style pushbutton; an old typewriter key; a round toggle switch; a small; rocker switch; a whisker switch, which is a thin wire attached to a spring wrapped around a metal post; a magnet switch, and a magnet that closes the switch when you bring it close; a tilt switch; a two-way knife switch.
Figure 1. Switches and pushbuttons. There are countless types of switches and pushbuttons for every purpose.

Switch Terminology

As shown in Figure 2, there are two common types of digital inputs: switches and pushbuttons. A switch is a mechanism that brings two pieces of metal together using some form of lever action. Think of everyday household light switches.  A pushbutton brings two pieces of metal together when you push down on it. Think of elevator buttons.

Drawing of a switch, left, and a pushbutton, right. The switch has two lines separated by a gap, with a hinged third line almost connecting them, indicating that it is the switch between the two contacts. The pushbutton has two lines separated by a gap and a third line parallel to them, indicating that, it would close the connection between the first two lines when pressed against them.
Figure 2. Schematic drawing of a switch and a pushbutton

Switches and pushbuttons can be normally open, meaning that when the switch is in its normal position (not being touched by a person) the contacts are not touching. Normally closed means that when the switch or pushbutton is in its normal position, the contacts are touching, or closed.

As shown in Figure 3, a single switch can control more than one set of contacts. A Single throw switch has only two contacts. The switch is open or closed. Dual Throw switches have three contacts, and switching the switch moves a center contact from one outer contact to  the other outer contact.

Drawing of two switch types. The top drawing has two lines separated by a gap, with a hinged third line almost connecting them, indicating that it is the switch between the two contacts. The bottom drawing has one line on the left, and two parallel lines on the right. A hinged fourth line almost connects the left line and the top right line, and indicates that it can be switched to connect the left line to the bottom right line instead.
Figure 3. Single throw switch, top, and dual throw switch, bottom.

Switches can have multiple poles as well. A Single pole switch has only one set of contacts that it closes or opens when it moves. Dual Pole switches, as shown in Figure 4,  have two sets of contacts being controlled by the same mechanism. With a dual pole switch, you can switch two separate circuits with the same mechanism. In a dual pole switch, the mechanism connecting the contacts is an insulator, so that the poles don’t connect. The knife switch in the image below is a dual pole, dual throw switch.

Photo of a dual-pole, dual-throw switch. The switch has a metal lever with two legs connected by a crossbar mounted at its center. On either side of the crossbar are two sets of metal contacts. When the lever is pushed to one side or the other, it will close the connection between the two metal contacts on the side toward which it is pushed. This kind of switch is sometimes called a knife switch.
Figure 4. Dual-pole, dual-throw switch.

Related video: Switches

Pushbuttons(Figure 5) or momentary switches stay closed only as long as you hold them closed. Roller switches(Figure 6) are pushbuttons with a lever and a roller attached. They’re useful when you need something to push against the switch gently to close it.

Photo of a small round button, approximately 0.5 in (2-3cm) in diameter. The button has two legs on either side. Pushing the button closes the connection between the two legs on each side.
Figure 5. A pushbutton
Photo of a rocker switch. A rectangular component approx. 1 in (2-3cm) wide by 0.25 in (0.5cm) thick. A lever is mounted on one side, and three metal contacts on the other. Under the lever is a small plastic protrusion that is pushed down when the lever is pressed.
Figure 6. A roller switch. Even though this is commonly called a switch, this is really a pushbutton. The small black protrusion under the lever is pressed down by the lever arm.

Tactile Switches are pushbuttons that have a tactile click to them (Figure 7). They are usually designed to be soldered to a circuit board, and they fit into a breadboard nicely as well. They are perhaps the most common switches you’ll use in physical computing. You can get them in a variety of colors and sizes.  They generally have four pins, arranged in a rectangle. If you hold the switch so that the wide side of the rectangle of pins is horizontal, then the top two pins are generally connected to each other, and the bottom two are connected to each other. The switch is between the two wide sides. The schematic in Figure 8 shows how they are wired.

Photo of a variety of different tactile switches.
Figure 7. A variety of different tactile switches. These all have different sizes and cap shapes, but they all have the same functionality and feel. Some tactile switches, like the one at the top left, have extra long caps.
Schematic of a typical tactile switch
Figure 8. Schematic of a typical tactile switch. The two top pins are connected to one side of the switching mechanism inside, and the two bottom pins are connected to the other side of the mechanism.

Arcade buttons (Figure 9) are popular game consoles because they are big and robust. They often have a built-in LED that you can control independently of the switch. In this way they are similar to other illuminated switches and pushbuttons.

Photo of several arcade buttons
Figure 9. Arcade buttons come in many different sizes and shapes. They are designed to be panel-mounted. Many are illuminated with an internal LED as well.

Toggle switches (Figure 10) stay closed in one physical position and open in the other. Slide switches (Figure 11) are similar to toggle switches.

Photo of a toggle switch. A component approx. 1.5cm wide by 0.5cm thick. There are three metal legs on one side, and a metal lever at the top center that can move from one side to the other. Moving the lever switches the center leg's connection from one side leg to the other.
Figure 10. Toggle switch. Moving the lever switches the center leg’s connection from one side leg to the other.
Photo of a slide switch. A component approx. 1.5cm wide by 0.5cm thick. There are three metal legs on one side, and a plastic handle at the top that can slide from one side to the other. Sliding the handle switches the center leg's connection from one side leg to the other.
Figure 11. Slide switch. Sliding the handle switches the center leg’s connection from one side leg to the other.
Photo of a magnet switch. A small plastic tube has one flat end and two wires protruding from the other end. Another tube of the same size contains a magnet. When the magnet tube's flat end is brought close to the switch tube's flat end, the connection is closed between the two wires.
Figure 12. Magnet switch.
Photo of magnet snaps. Two metal discs approx 1 inch (2.54cm) in diameter. One has a metal protrusion in the center, and the other has a depression that can fit the other's protrusion. Wires can be connected to the two snaps so that when they are snapped together, the wires are connected.
Figure 13. Magnet snaps. Used for clothing, wires can be connected to the two snaps so that when they are snapped together, the wires are connected. In this way, a garment fastener becomes a switch.

Magnetic switches (Figure 12) have two metal leaves in the end that are pulled together when a magnet is brought close to them. They’re useful when you can’t have wires on both sides of the switch mechanism. Magnetic snaps (Figure 13) are useful when you’re making a soft circuit and need a fastener on the garment to close a switch.

Photo of a whisker switch. A metal spring a few millimeters in diameter is connected to a long, thin, spring steel wire. The spring is mounted on a rubber insulation that partially covers a center post that's slightly thinner than the spring's diameter.
Figure 14. Whisker switch

Whisker switches (Figure 14) are made from a piece of spring steel or piano wire, and a center post. An insulator such as a piece of electrical tape or shrink-wrap holds the two separate. When the wire is touched, the spring bends and touches the metal post, and closes the switch.

Tilt switch. This is a small tube with metal contacts at one end and a ball inside. When the ball is tilted towards the two metal contacts, it closes the switch.
Figure 15. Tilt switch

Tilt switches (Figure 15) contain a metal ball and two wires at one end. Some tilt switches have one wire contact at each end instead. When you tilt the switch, the ball touches both contacts, and closes the switch. There are also mercury switches that do the same, but with a ball of mercury inside. Avoid these, since mercury is very poisonous.

Get Creative With Switches

A switch is nothing more than a mechanism to bring two pieces of conductive material together and separate them. You can make a switch from any two conductors and a little creativity.

Photo of a roll of grey fabric made of conductive threads.
Figure 16. Conductive fabric
Photo of copper mesh wire, approximately 4 inches (10cm) square. The mesh has holes slightly smaller than 1mm.
Figure 17. Copper mesh
Photo of a roll of copper tape, approximately 1cm thick. This tape is made of thin copper and has an adhesive backing.
Figure 18. Copper tape

All you need to do is arrange the two conductors in such a way that they can touch or not touch. Sometimes a spacer layered between the two conductors helps. For example, in figure 19 you see three pieces of conductive material. Two of the pieces have non-conductive layers on top of them. When the non-conductive part is sandwiched between the conductive layers, you’ve got a switch that’s pressed by touching. The conductive parts touch when they’re pressed through the holes in the non-conductive part. These two switches would have different sensitivities because the hole-to-material ratio of the non-conductive layer is different.

Photo of three pieces of conductive fabric. Two of the pieces have non-conductive layers on top of them.
Figure 19. Soft switch

Make your own switch. Find a way to turn a closing door into a switch, for example, or to close a switch when a person sits down. Or figure out how to turn a hat into a switch, or a cane, or a zipper. Or perhaps the pieces of a puzzle can be switches. Come up with an everyday activity to which you can add three or four custom switches that, when combined, turn on a light. For example, maybe the light comes on when you close the door, sit down, and open a book. Or when you walk upstairs, put your keys on a side table, and remove your hat. Combine your creativity with switches with what you learned in the electronics lab and breadboard lab to make this happen. For more ideas on materials, check out How to Get What You Want. They have an excellent list of conductive materials and instructions.

Here’s mustache switch by Tak Cheung:

Arrangements of switches

Consider what happens when you arrange switches in different ways. For example, try the following circuits.

Project 1: Three switches in parallel

Three switches in parallel, as shown in Figure 20-21. Any one of the three will turn on the LED.

Drawing of three parallel switches. At the top left of the drawing there is a power supply. The positive line from the power supply connects to a 7805 5-volt voltage regulator's input. The power supply's ground is connected to the regulator's ground. The output of the regulator connects to a 220-ohm resistor. The other side of the resistor connects to one side of a switch. That side is connected to two other switches below it. The other sides of all three switches are connected to each other, and then to the anode (positive side) of an LED. The cathode (negative side) of the LED is connected to the ground of the voltage regulator.
Figure 20. Schematic view of three parallel switches connected to an LED.
Breadboard drawing of three parallel switches. At the top of the drawing,there is a DC power jack. Red and black wires from the jack connect to a 7805 5-volt voltage regulator mounted in the top right three rows of the breadboard with its tab facing to the right. input. The power supply's red wire is connected to the regulator's top pin row, the input pin. The power supply's black wire is connected to the regulator's middle pin, or ground. Another black wire connects the regulator's middle pin, ground, to the inner left side row of the board. This is the ground bus on the left side. A red wire connects the regulator's bottom pin, the output pin, to the outer left side row of the board. This is the voltage bus on the left side. At the bottom of the breadboard, a red wire connects the left side voltage bus to the inner row on the right side. This is the right side voltage bus. Similarly, a black wire connects the left side ground bus to the outer row on the right side. This is the right side ground bus. A 220-ohm resistor connects the the left side voltage bus to row 8 in the left center section of the board. A pushbutton is mounted across the center divide of the breadboard with its pins in rows 8 and 10. Another pushbutton is mounted across the center in rows 13 and 15, and a third in rows 18 and 20. In the left center section of the board, four short wires connect the top row connection of each pushbutton to the top row of the next pushbutton. Specifically: row 8 connects to row 13. Row 13 connects to row 18. Row 10 connects to row 15. Row 15 connects to row 20. In the right center section of the board, an LED's anode (long leg) is connected to row 20. The LED's cathode is connected to row 21, and a black wire connects from that row to the right side ground bus.
Figure 21. Switches in parallel, breadboard view.

Project 2: Three switches in series

Three switches in series, as shown in Figure 22-23. All three must be on to turn on the LED.

Drawing of three switches in series. At the top left of the drawing there is a power supply. The positive line from the power supply connects to a 7805 5-volt voltage regulator's input. The power supply's ground is connected to the regulator's ground. The output of the regulator connects to a 220-ohm resistor. The other side of the resistor connects to one side of a switch. The other side of the switch connects to a second switch. The other side of that switch connects to a third switch. The other side of the third switch connects to the anode (positive side) of an LED. The cathode (negative side) of the LED is connected to the ground of the voltage regulator.
Figure 22. Schematic view of three switches in series connected to an LED.
Breadboard drawing of three switches in series connected to an LED. At the top of the drawing, there is a DC power jack. Red and black wires from the jack connect to a 7805 5-volt voltage regulator mounted in the top right three rows of the breadboard with its tab facing to the right. input. The power supply's red wire is connected to the regulator's top pin row, the input pin. The power supply's black wire is connected to the regulator's middle pin, or ground. Another black wire connects the regulator's middle pin, ground, to the inner left side row of the board. This is the ground bus on the left side. A red wire connects the regulator's bottom pin, the output pin, to the outer left side row of the board. This is the voltage bus on the left side. At the bottom of the breadboard, a red wire connects the left side voltage bus to the inner row on the right side. This is the right side voltage bus. Similarly, a black wire connects the left side ground bus to the outer row on the right side. This is the right side ground bus. A 220-ohm resistor connects the the left side voltage bus to row 8 in the left center section of the board. A pushbutton is mounted across the center divide of the breadboard with its pins in rows 8 and 10. Another pushbutton is mounted across the center in rows 13 and 15, and a third in rows 18 and 20. In the left center section of the board, two short wires connect one side of each pushbutton to the other side of the next pushbutton. Specifically: row 10 connects to row 13. Row 15 connects to row 18. In the right center section of the board, an LED's anode (long leg) is connected to row 20. The LED's cathode is connected to row 21. A black wire connects row 21 to the right side ground bus.
Figure 23. Breadboard view of three switches in series connected to an LED.

Through a combination of series and parallel switches, you can come up with a variety of combinations that make the light turn on. Depending on where you add the LEDs, you can even have the same switches turn on different LEDs in different combinations. Try a few combinations and see what happens.

Project 3: Switching a DC motor

In a simple circuit, a DC motor* is no different than an LED as a load. You can switch it as well, as shown in Figure 24-25. Make sure your power supply can supply the current and amperage that your motor requires and you are good to go.

* DC Motor converts direct current (DC) electrical energy into mechanical energy. Check the parts and tools guide for where to get a motor. You’ll learn more about DC motors and other motors in later labs.

Drawing of a dual-pole switch controlling a motor and an LED. At the top left of the drawing there is a power supply. The positive line from the power supply connects to a 7805 5-volt voltage regulator's input. The power supply's ground is connected to the regulator's ground. The output of the regulator connects to one side of a switch. The other side of the switch connects to a DC motor. The other side of the motor connects to ground.
Figure 24. Schematic view of a DC motor switched by a pushbutton.
Breadboard drawing of a pushbutton controlling a motor. At the top of the drawing, there is a DC power jack. Red and black wires from the jack connect to a 7805 5-volt voltage regulator mounted in the top right three rows of the breadboard with its tab facing to the right. The power supply's red wire is connected to the regulator's top pin row, the input pin. The power supply's black wire is connected to the regulator's middle pin, or ground. Another black wire connects the regulator's middle pin, ground, to the inner left side row of the board. This is the ground bus on the left side. A red wire connects the regulator's bottom pin, the output pin, to the outer left side row of the board. This is the voltage bus on the left side. At the bottom of the breadboard, a red wire connects the left side voltage bus to the inner row on the right side. This is the right side voltage bus. Similarly, a black wire connects the left side ground bus to the outer row on the right side. This is the right side ground bus. A red wire connects the the left side voltage bus to row 13 in the left center section of the board. A pushbutton is mounted across the center divide of the breadboard with its pins in rows 13 and 15. A DC motor is connected to row 15 in the left center section of the board. The other wire from the motor is attached to the voltage bus on the left side of the board.
Figure 25. Breadboard view of a DC motor connected to a switch.

With a dual pole switch, you could control both a DC motor and an LED. The small square pushbuttons that come with many kits for Arduino are dual pole switches. The left side of the switch and the right side of the switch can switch different loads, like shown in Figure 26-27:

Drawing of a dual-pole switch controlling a motor and an LED. At the top left of the drawing there is a power supply. The positive line from the power supply connects to a 7805 5-volt voltage regulator's input. The power supply's ground is connected to the regulator's ground. The output of the regulator connects to one side of a switch. The other side of the switch connects to a DC motor and to a 220-ohm resistor in parallel. The other side of the motor connects to ground. The other side of the resistor connects to the anode of an LED. The other side of the LED connects to ground.
Figure 26. Schematic view of a DC motor and an LED switched by a dual-pole pushbutton (switch).
Breadboard drawing of a dual-pole pushbutton (switch) controlling a motor and an LED. At the top of the drawing, there is a DC power jack. Red and black wires from the jack connect to a 7805 5-volt voltage regulator mounted in the top right three rows of the breadboard with its tab facing to the right. input. The power supply's red wire is connected to the regulator's top pin row, the input pin. The power supply's black wire is connected to the regulator's middle pin, or ground. Another black wire connects the regulator's middle pin, ground, to the inner left side row of the board. This is the ground bus on the left side. A red wire connects the regulator's bottom pin, the output pin, to the outer left side row of the board. This is the voltage bus on the left side. At the bottom of the breadboard, a red wire connects the left side voltage bus to the inner row on the right side. This is the right side voltage bus. Similarly, a black wire connects the left side ground bus to the outer row on the right side. This is the right side ground bus. A red wire connects the the left side voltage bus to row 13 in the left center section of the board. A pushbutton is mounted across the center divide of the breadboard with its pins in rows 13 and 15. A DC motor is connected to row 15 in the left center section of the board. The other wire from the motor is attached to the voltage bus on the left side of the board. In the right center section of the board, a 220-ohm resistor is connected to row 15. The other side of the resistor is connected to row 19. The anode (long leg) of an LED is connected to row 19 as well. The cathode (short leg) of the LED is connected to row 20. A black wire connects row 20 to the right side ground bus.
Figure 27. Breadboard view of a dual-pole pushbutton (switch) controlling a DC motor and an LED.

You’ll learn more about controlling motors from a microcontroller in later labs.

Lab: Setting Up A Breadboard

This lab shows how to set up a breadboard with an independent power supply (9-12V) through a 5V Voltage Regulator (7805).

Introduction

The easiest way to get started building electronic circuits is by using a solderless breadboard. A breadboard is a tool for holding the components of your circuit, and connecting them together. It’s got holes that are the right size for hookup wires and the ends of most components, so you can push wires and components in and pull them out without much trouble. This lab shows how to set up a breadboard, both with an Arduino and with an independent power supply (9-12V) through a 5V Voltage Regulator (7805). By the time you finish the lab, you should have an understanding of how the holes in a solderless breadboard are connected, and how to configure your breadboard for different microcontroller projects, and even for projects without a microcontroller.

You won’t always need a voltage regulator. For most microcontroller circuits, you’ll get power from your computer’s USB port, regulated through your microcontroller, to power sensors and LEDs. But for higher current projects or higher voltage projects involving components like motors or larger light sources, it’s good to know what a voltage regulator is and how to use it.

Video: Connecting Power Supply to Breadboard with Regulator

If you’re using a brand new breadboard, you might want to check out these videos as well before you get started, to prep your board and care for your microcontroller.

What You’ll Need to Know

To get the most out of this lab, you should be familiar with the following concepts beforehand. If you’re not, review the links below:

  • What is a Voltage Regulator
  • Batteries and Power Supplies
  • All about DC Power supplies – this page will introduce you to DC power supplies. You probably have several in your house already, and this lesson will tell you more about how they work and how you can use them.

Safety Warning: When inserting components on or removing components from a breadboard always unplug power supply first! You are likely to damage your components if you are changing your circuit while it is still powered.

Things You’ll Need

A short solderless breadboard with two rows of holes along each side. There are no components mounted on the board.
Figure 1. A short solderless breadboard.
Three 22AWG solid core hookup wires. Each is about 6cm long. The top one is black; the middle one is red; the bottom one is blue. All three have stripped ends, approximately 4 to 5mm on each end.
Figure 2. 22AWG solid core hookup wires.
A DC power jack. It pairs with a plug with a 2.1mm inside diameter, 5.5mm outside diameter plug, and has screw terminals on the back so that you can attach wires to it.
Figure 4. A DC Power Jack
5-volt regulator, model 7805. This component has three legs and a tab at the top with a hole in it. If you hold the component with the tab at the top and the bulging side of the component facing you, the legs will be arranged, from left to right, voltage input, ground, and voltage output.
Figure 5. 5-volt voltage regulator, model 7805
Wire strippers. The jaws of this wire stripper have multiple hole sizes so that it can strip wires of variable sizes.
Figure 6. Wire stripper tool
Multimeter tool. This tool has a dial to set the function, and three holes into which to plug the testing leads. The leads are currently plugged into the center hole and the right hand hole.
Figure 7. Multimeter tool
LEDs. Shown here are four LEDs. The one on the right is an RGB LED. You can tell this because it has four legs, while the others have only two legs.
Figure 8. LEDs. Shown here are four LEDs. The one on the right is an RGB LED. You can tell this because it has four legs, while the others have only two legs.
Photo of an Arduino Nano 33 IoT module. The USB connector is at the top of the image, and the physical pins are numbered in a U-shape from top left to bottom left, then from bottom right to top right.
Figure 9. Arduino Nano 33 IoT. You could use any model of Arduino instead, for this lab.

Setting up the Breadboard

A solderless breadboard with a 7805 5-Volt voltage regulator mounted on it. There are several rows of holes for components. The holes on the breadboard are separated by 0.1-inch spaces, and are organized in many short rows in the center, and in two long rows down each side of the board. The short horizontal rows in the middle are separated by a center divider. The side rows are usually marked red, for voltage, and blue or black, for ground. On this breadboard, the side rows on the left side are connected to their counterparts on the right side with wires. The voltage regulator is mounted in the top three short rows on the right side of the board. The regulator faces to the left. The row holding the regulator's center pin is connected to the blue or black side row on the right side. The row holding the regulator's bottom pin is connected to the red side row on the right side.
Figure 10. Solderless breadboard with a 7805 voltage regulator mounted on it.

Figure 10 shows a typical breadboard with a 7805 5-Volt voltage regulator mounted on it. There are several rows of holes for components. The holes on the breadboard are separated by 0.1-inch spaces, and are organized in many short rows in the center, and in two long rows down each side of the board. The short horizontal rows in the middle are separated by a center divider. The pattern varies from model to model; some breadboards have only one strip down each side, others have multiple side rows, and some have no side rows at all.

Related Video: Introduction to breadboards

On each side of the board are two long rows of holes, with a black or a red line next to each row (on many boards, you’ll see a blue row instead of black).  All the holes in each of these lines are connected together with a strip of metal in the back. In the center are several short rows of holes separated by a central divider. All of the five holes in each row in the center are connected with a metal strip as well. This allows you to use the holes in any given row to connect components together. To see which holes are connected to which, take a multimeter and a couple of wires, set the multimeter to measure continuity, stick the two wires in two holes, and measure them with the multimeter. If the meter indicates continuity, then the two holes in question are connected.

What’s Inside A Breadboard?

The image below (Figure 11) of the back of a breadboard may help to clear up how the holes on the front of the board are connected. The backing of the board has been removed (don’t remove the backing on your own board! It will make the board useless) to expose the metal strips connecting the holes. You can clearly see the short horizontal strips in the center separated by the divider, and the long strips vertically down the side. The detailed photo in Figure 12  illustrates how the holes and strips are related. Each of the holes connected to the horizontal strips are connected, and each of the holes connected to each long vertical side strips are connected to each other.

The back of a breadboard with the adhesive backing removed, showing the metal strips underneath. Each long row down the side has a continuous metal strip underneath, running vertically down the board. The metal strip connects all the holes in its row. The holes of the short rows are connected with short metal strips running perpendicular to the long strips on the side. There is a break in the middle of the board, so that there is no connection between the right side and the left side.
Figure 11. The back of a breadboard, shown with the backing removed.
A close-up picture of the front of the breadboard. The green lines indicate which holes are connected by a metal strip behind. Each short horizontal group of five holes is connected, and each long vertical group of holes is connected. The vertical groups are not connected to each other or to the horizontal groups, however.
Figure 12. A close-up picture of the front of the breadboard. The green lines indicate which holes are connected by a metal strip behind.

The reason for the center divider is so that you can mount integrated circuit chips, like a microprocessor, on the breadboard. IC chips in a DIP package (Dual In-line Package) have two rows of pins that to which you need to connect other components. The center row isolates the two rows from each other, and gives you several holes connected to each pin, so that you can connect other components.

Powering the Breadboard

Avoid adding, removing, or changing components on a breadboard whenever the board is powered. You risk shocking yourself and damaging your components.

The most common connections you need on a breadboard are voltage and ground. That’s why solderless breadboards are designed the way they are. The long rows of connected holes down either side are designed to be used as power and ground buses. A bus is a long electrical connection that has many points where you can connect to it. Figure 13 shows the typical wiring on a breadboard, connecting the bus rows on the left with those on the right.

A solderless breadboard with the voltage and ground buses indicated on the sides.
Figure 13. A solderless breadboard with the voltage and ground buses indicated on the sides. The left and right sides of the board are connected via two wires which connect the voltage bus on the left with the one on the right, and the ground bus on the left with the one on the right.

Next you’ll see how to connect an Arduino microcontroller to your breadboard to supply power to the components on the board. Later on, you’ll see how to power a board without a microcontroller.

Using a Breadboard with a Microcontroller

For most projects in this class you’ll power your circuit via a microcontroller like the Arduino Nano 33 IoT or the Uno. To do that, your breadboard will usually be connected as shown in Figures 14 and 15. You’ll connect the voltage and ground buses on the breadboard to voltage and ground from the microcontroller. On the Arduino module, you can use the 5V or 3.3V output, depending on the circuit you are using and depending on your model. Typically, you’ll use 5V on the Uno and 3.3V on the Nano 33 IoT.

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 14. Breadboard view of an Arduino Uno on the left connected to a solderless breadboard, right.

As shown in Figure 15, the Uno’s 5V output hole is connected to the red side column of holes on the far left side of the breadboard; this is the voltage bus. The Uno’s ground hole is connected to the blue side column on the left of the board, or ground bus. 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. With this setup, you can supply 5V to any component on the breadboard, using the Uno’s onboard 5-volt regulator. You can power the Uno either through USB or through a 9-12V power supply plugged into the Uno’s power jack. There is a limit to the current that you can supply from this regulator, though, about 1 amp at 5V.

If you’re using an Uno for this lab, connecting the circuit in Figure 14, then set your multimeter to measure DC voltage, and measure the voltage between the voltage and ground buses of your breadboard. When the Uno is plugged into a USB power supply, you should get 5V.


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

In Figure 15, you see a similar setup for the Arduino Nano 33 IoT. 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 out pin (physical pin 2) is connected to the left side red column of the breadboard. This is the voltage bus. The Nano’s GND pin (physical pin 14) is connected to the left side black column, 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. Wired like this, you can supply 3.3V to any component on the breadboard through the Nano’s onboard 3.3V regulator. There is a limit to the current that you can supply from this regulator, though, about 1 amp at 3.3V.

If you’re using a Nano for this lab, connecting the circuit in Figure 15, then set your multimeter to measure DC voltage, and measure the voltage between pin 2 of the Nano (3.3V out) and pin 14 (ground). When the Nano is plugged into a USB power supply, you should get 3.3V.

Powering A Breadboard Circuit From A Microcontroller Via A DC Power Supply

Quite often, you’ll want to supply power to a circuit through an Arduino. Sometimes, you’ll have components that run at the microcontroller’s voltage, and sometimes they will require a higher voltage. From both the Nano and the Uno, if you power them from a DC power supply, you can supply 5V, 3.3V and the voltage of the power supply.

When you’re not powering it via its USB connector, the Nano 33 IoT and the Nano Every can be powered through the Vin pin (pin 15, bottom left side of the module) by a voltage range from 7 – 21 volts. This wide range means that you can use a 9V battery, or a DC power supply anywhere from 7-21V. When you power the Nano this way, you get 3.3V from the 3V3 pin (pin 2) just as if you were powering from USB. If you have components that need a higher voltage, you can supply them directly from your power supply via the Vin pin. Figure 16 shows a Nano powered from a 12V DC power jack. The Jack’s positive terminal is connected to the Vin pin (pin 15) and the negative terminal is connected to the ground pin (pin 14).

 Breadboard view of a Nano 33 IoT on a breadboard connected to a DC power jack for external DC powering.
Figure 16. Breadboard view of a Nano 33 IoT on a breadboard connected to a DC power jack for external DC powering. The jack’s positive terminal is connected to the Nano’s Vin pin (pin 15) and the negative terminal is connected to ground (pin 14). In this configuration, the Nano will run, and will output 3.3V between the 3V3 pin (pin 2) and ground.

When you are using a DC power supply as shown in Figure 16, you can also add a 5V regulator powered by the power supply, if you need both 3.3V and 5V for your components. Figure 17 shows a Nano supplied by a DC power jack on the Vin and ground pins, and a 5V regulator attached to the Vin pin as well, to supply 5V for components that need that voltage.

Try connecting the circuit in Figure 17, then set your multimeter to measure DC voltage, and measure the voltage between pin 2 of the Nano (3.3V out) and pin 14 (ground). When the DC power jack is plugged in, you should get 3.3V. Now move the positive (red) probe of your meter to the bottom pin of the voltage regulator (row 21 on the board). You should read 5V. Now move the positive probe to the Nano’s pin 16 (Vin). You should read whatever the voltage of the DC power supply is, somewhere between 7 and 21V.

Breadboard view of a Nano 33 IoT and a 7805 voltage regulator powered from a DC power jack.
Figure 17. Breadboard view of a Nano 33 IoT and a 7805 voltage regulator powered from a DC power jack. The DC power jack is wired as shown in the previous figure (positive terminal to Vin, negative terminal to ground. However, in this image, a 5V regulator is added on the breadboard below the Nano. Its Vin pin is connected to the Vin of the Nano (and the DC power supply’s positive terminal) and its ground is connected to the ground bus. In this circuit, you can supply 3.3V via the Nano’s 3V3 pin (pin 2), 5V from the 7805 regulator, and 7-21V from the DC power supply.

The Uno accepts 7-12V in via its DC power jack, and it has two voltage regulators on board. Pin 5 on the left side of the board supplies 5V, and pin 4 on the left side supplies 3.3V. Pin 8 on the left side is connected directly to the Vin, so you can supply 7-12V, depending on the voltage of your DC power supply, from that pin. For example, figure 18 shows an Uno connected to a 9V battery and supplying 9V to the breadboard via the Vin pin.

Uno connected to a 9V battery via a battery clip.
Figure 18. Uno connected to a 9V battery via a battery clip. The Uno’s Vin pin (pin 8 on the left side) is connected to a breadboard’s voltage bus, and one of the ground pins (pin 7) is connected to the ground bus. The Uno is thus supplying 9V for any components on that breadboard.

If you’re using an Uno for this lab, connecting the circuit in Figure 18, then set your multimeter to measure DC voltage, and measure the voltage between the voltage and ground buses of your breadboard. When the Uno is plugged into a DC power supply, you should get whatever the voltage of the DC power supply is, between 7 and 12V.

With an external power supply and a voltage regulator, you can supply almost any voltage your components might need, while still giving the Arduino the voltage it needs to run. In general, you will always connect the ground lines together, and keep the different voltages separate from each other. To see an application of this, see the Using a Transistor to Control High Current Loads with an Arduino Lab.

You can use the circuits above as templates for almost any microcontroller-driven project. Even if you’re just using the microcontroller to power the breadboard, as shown below, you can still work with these circuits as a base.

Powering the Breadboard without a Microcontroller

Close-up showing a 7805 5-volt voltage regulator connected to a breadboard. The breadboard is oriented so that the long rows are horizontal this time, and you are looking at the back of the regulator. The regulator is connected to the right-most three rows of the board.
Figure 19. Close-up showing a 7805 5-volt voltage regulator connected to a breadboard.

Sometimes you’ll want to build circuits without a microcontroller. This section shows you how to set up a breadboard without a microcontroller. You’ll add a 5-volt voltage regulator, and power the board from a 12-volt DC power adapter which feeds the regulator.

The regulator in Figure 19 is used to supply 5 Volts to the red side columns of the breadboard. In this image, you’re looking at the board sideways, with the the back of the regulator facing you. The pins of the regulator are, from left to right: voltage out, ground, voltage in. Notice that the regulator’s voltage out pin on the left is connected to the red side row of the breadboard with a red wire. The regulator’s center pin (ground) is connected to the black side row. These will be your voltage and ground bus rows. The side rows on one side are connected to the corresponding side rows on the other side via two wires. The two black rows are connected to each other via a black wire, and the red rows are connected via a red wire.

Related Video: Using a voltage regulator on a breadboard

With your board connected like this, you’ll be able to build many different 5-Volt circuits on the board. The last thing you need to add is a power connector to connect 9 – 12 volts DC to supply power for the voltage regulator. Figure 20 below shows a power connector connected to the voltage input and ground pins of the voltage regulator. This circuit is now the same as the one shown in Figure 17 above, but with the Arduino Nano removed.

Related Video: Wiring a power supply using a DC power jack

breadboard_power_jack
Figure 20. Board with 5V voltage regulator and power connector ready to go.

Will it Light? Test Your Understanding

Figures 22-30 below show an LED and a resistor connected in a breadboard. Some are connected correctly and others are not. Take a guess as to whether the LED will light or not, then click the links below the image to find out. All of the circuits below are versions of the same circuit, shown in the schematic in Figure 21:

Schematic image of a 220-ohm resistor and an LED connected to a 7805 5-volt regulator. At left, there is a power plug. The positive terminal of the power plug is connected to the voltage input of a 7805 voltage regulator. The negative terminal of the power plug is connected to the ground terminal of the regulator. The voltage output of the regulator is connected to a 220-ohm resistor. The other side of the resistor is connected to the anode of an LED. The cathode of the LED is connected to the ground terminal of the regulator.
Figure 21. Schematic image of a 220-ohm resistor and an LED connected to a 7805 5-volt regulator. Regulator pins are numbered from left to right.  One terminal of the resistor is connected to the regulator’s output pin (pin 3), and the other terminal is connected tothe LED’s anode. The LED’s cathode is attached to the regulator’s ground pin (pin 2). A 9-12V DC power source is connected to the regulator’s voltage in (pin 1) and ground (pin 2). Download the tactile schematic as SVG. Download the tactile schematic key as SVG.

These circuit images will test your understanding of how the breadboard works. You can build the circuits yourself, using any one of Figures 14, 15, 17 or 20 to supply 5V for the LED circuit.

If your board is wired as in Figure 22, will the LED below light up when you power the board? Take a guess, then click the link below the image to find out.

Photo of a solderless breadboard with a 7805 voltage regulator mounted on it, as in the images above. The regulator is connected to a DC power plug, and the ground and voltage output of the regulator is connected to the voltage and ground bus rows on the right side of the breadboard. The ground and voltage bus rows on the right are connected to the ground and voltage bus rows on the left with wires at the bottom of the board. A 220-ohm resistor is connected to the voltage bus on the left. Its other end is connected to row twelve in the center area. An LED is connected to another hole in row twelve. The other side of the LED is connected to a hole in row fourteen. Another hole in row fourteen connects to the ground bus on the right side of the board.
Figure 22. Photo of a solderless breadboard with a 7805 voltage regulator mounted on it, as in the images above. The regulator is connected to a DC power plug, and the ground and voltage output of the regulator is connected to the voltage and ground bus rows on the right side of the breadboard. The ground and voltage bus rows on the right are connected to the ground and voltage bus rows on the left with wires at the bottom of the board. A 220-ohm resistor is connected to the voltage bus on the left. Its other end is connected to row twelve in the center area. An LED is connected to another hole in row twelve. The other side of the LED is connected to a hole in row fourteen. Another hole in row fourteen connects to the ground bus on the right side of the board.

Try another one. When wired as in Figure 24, will the LED below light up when you power the board? Take a guess, then click the link below the image to find out.

Photo of a solderless breadboard with a 7805 voltage regulator mounted on it, as in the images above. The regulator is connected to a DC power plug, and the ground and voltage output of the regulator is connected to the voltage and ground bus rows on the right side of the breadboard. The ground and voltage bus rows on the right are connected to the ground and voltage bus rows on the left with wires at the bottom of the board. A 220-ohm resistor is connected to the voltage bus on the left. Its other end is connected to row twelve in the center area. An LED is connected to a hole in row twelve on the right side. The other side of the LED is connected the ground bus on the right side.
Figure 24. Photo of a solderless breadboard with a 7805 voltage regulator mounted on it, as in the images above. The regulator is connected to a DC power plug, and the ground and voltage output of the regulator is connected to the voltage and ground bus rows on the right side of the breadboard. The ground and voltage bus rows on the right are connected to the ground and voltage bus rows on the left with wires at the bottom of the board. A 220-ohm resistor is connected to the voltage bus on the left. Its other end is connected to row twelve in the center area. An LED’s anode is connected to a hole in row twelve on the right side. The cathode of the LED is connected the ground bus on the right side.

Here’s a third one, Figure 25. Will the LED below light up when you power the board? Take a guess, then click the link below the image to find out.

Photo of a solderless breadboard with a 7805 voltage regulator mounted on it, as in the images above. The regulator is connected to a DC power plug, and the ground and voltage output of the regulator is connected to the voltage and ground bus rows on the right side of the breadboard. The ground and voltage bus rows on the right are connected to the ground and voltage bus rows on the left with wires at the bottom of the board. A 220-ohm resistor is connected to the voltage bus on the left. Its other end is connected to row thirteen in the center area. A red wire connects row thirteen on the left with row thirteen on the right. An LED is connected to a hole in row thirteen on the right side. The other side of the LED is connected the ground bus on the right side.
Figure 25. Photo of a solderless breadboard with a 7805 voltage regulator mounted on it, as in the images above. The regulator is connected to a DC power plug, and the ground and voltage output of the regulator is connected to the voltage and ground bus rows on the right side of the breadboard. The ground and voltage bus rows on the right are connected to the ground and voltage bus rows on the left with wires at the bottom of the board. A 220-ohm resistor is connected to the voltage bus on the left. Its other end is connected to row thirteen in the center area. A red wire connects row thirteen on the left with row thirteen on the right. An LED’s anode is connected to a hole in row thirteen on the right side. The cathode of the LED is connected the ground bus on the right side.

Here’s another test. In Figure 27, will the LED below light up when you power the board? Take a guess, then click the link below the image to find out.

Photo of a solderless breadboard with a 7805 voltage regulator mounted on it, as in the images above. The regulator is connected to a DC power plug, and the ground and voltage output of the regulator is connected to the voltage and ground bus rows on the right side of the breadboard. The ground and voltage bus rows on the right are connected to the ground and voltage bus rows on the left with wires at the bottom of the board. A 220-ohm resistor is connected to the voltage bus on the left. Its other end is connected to row fifteen in the center area. An LED is connected to two holes in row fifteen of the left side of the board as well. A black wire connects row fifteen on the left side of the board to the ground bus on the right side of the board.
Figure 27. Photo of a solderless breadboard with a 7805 voltage regulator mounted on it, as in the images above. The regulator is connected to a DC power plug, and the ground and voltage output of the regulator is connected to the voltage and ground bus rows on the right side of the breadboard. The ground and voltage bus rows on the right are connected to the ground and voltage bus rows on the left with wires at the bottom of the board. A 220-ohm resistor is connected to the voltage bus on the left. Its other end is connected to row fifteen in the center area. An LED is connected to two holes in row fifteen of the left side of the board as well. A black wire connects row fifteen on the left side of the board to the ground bus on the right side of the board.

Here’s a final test. In Figure 29, will the LED below light up when you power the board? Take a guess, then click the link below the image to find out.

Photo of a solderless breadboard with a 7805 voltage regulator mounted on it, as in the images above. The regulator is connected to a DC power plug, and the ground and voltage output of the regulator is connected to the voltage and ground bus rows on the right side of the breadboard. The ground and voltage bus rows on the right are connected to the ground and voltage bus rows on the left with wires at the bottom of the board. A 220-ohm resistor is connected to the voltage bus on the right. Its other end is connected to row twenty in the on the right side of the center area. An LED is connected to a hole in row twenty on the right side as well. The other side of the LED is connected row twenty on the left side. A black wire connects row twenty on the left with the ground bus on the left side.
Figure 29. Photo of a solderless breadboard with a 7805 voltage regulator mounted on it, as in the images above. The regulator is connected to a DC power plug, and the ground and voltage output of the regulator is connected to the voltage and ground bus rows on the right side of the breadboard. The ground and voltage bus rows on the right are connected to the ground and voltage bus rows on the left with wires at the bottom of the board. A 220-ohm resistor is connected to the voltage bus on the right. Its other end is connected to row twenty in the on the right side of the center area. An LED is connected to a hole in row twenty on the right side as well. The other side of the LED is connected row twenty on the left side. A black wire connects row twenty on the left with the ground bus on the left side.

Below, in Figure 31, the three LED’s are connected in parallel using two rows. They are then connected to power and ground by connecting the rows to the voltage row and the ground row. These three LEDs are in parallel with each other.

Three LEDs mounted on a solderless breadboard. The three LEDs in this photo are connected in parallel using two rows. All of their anodes are connected to row 37 on the left side of the center area. All of their cathodes are connected to row 40 on the left side. They are then connected to voltage and ground through wires connecting the rows to the voltage row and the ground rows on the left side of the board.
Figure 31. LEDS in parallel on a breadboard

Many options are possible using a breadboard, which is what makes them very useful and convenient for building circuits. Once you understand which holes are connected to each other (and which ones are not), you can build any circuit very quickly.

Breadboarding Best Practices

It’s a good idea to keep your circuits neat. When possible, shorten the leads on components so there is no bare metal sticking up from the breadboard. Make sure no wires cross each other with metal touching (this is the biggest source of short circuits on a breadboard). Lay things out as sensibly as possible, so each component of the circuit is near the components it needs to connect to. Use wires when needed to separate parts of the circuit that are crowded together. Use consistent colors of wires when possible; for example, use green or black for ground connections, red for power connections, white or blue for data connections, and so forth. This will make your troubleshooting much easier.

Lab: Electronics

This lab will introduce you to a few basic electronic principles by trying them in action. You’ll learn how to measure voltage, amperage, and resistance using a multimeter. You will also learn about components in series vs. parallel and be introduced to Ohm’s Law in practice.

Introduction

This lab will introduce you to a few basic electronic principles by trying them in action. You’ll learn how to measure voltage, amperage, and resistance using a multimeter. You will also learn about components in series vs. parallel and be introduced to Ohm’s Law in practice. For more information on the theory behind this lab, please check out these notes.

When you’re building electronics, you run into problems all the time. Diagnosing those problems relies not only on a good theoretical knowledge of how circuits work, but also on practical knowledge of how to test them. The most common tool for testing circuits is the multimeter, a device that can measure current, voltage, resistance, and electrical continuity. More expensive multimeters can also measure other electrical properties, but if you can measure these four, you can diagnose most common circuit problems.

What You’ll Need to Know

To get the most out of this lab, you should be familiar with the following concepts beforehand. If you’re not, review the links below:

Safety Warnings! Check below when measuring Amperage in order to avoid damaging your meter!

Things You’ll Need

Photo of a solderless breadboard
Figure 1. A solderless breadboard with two rows of holes along each side.
Photo of flexible jumper wires
Figure 2. Flexible jumper wires. These wires are quick for breadboard prototyping, but can get messy when you have lots of them on a board.
5-volt regulator, model 7805. This component has three legs and a tab at the top with a hole in it. If you hold the component with the tab at the top and the bulging side of the component facing you, the legs will be arranged, from left to right, voltage input, ground, and voltage output.
Figure 3. 5-volt voltage regulator, model 7805
A DC power jack. It pairs with a plug with a 2.1mm inside diameter, 5.5mm outside diameter plug, and has screw terminals on the back so that you can attach wires to it.
Figure 4. A DC Power Jack
Wire strippers. The jaws of this wire stripper have multiple hole sizes so that it can strip wires of variable sizes.
Figure 5. Wire stripper tool
Photo of a handful of LEDs
Figure 6. LEDs. The long leg goes to voltage and the short leg goes to ground
Photo of two potentiometers
Figure 7. Potentiometer
Photo of a handful of 220-ohm resistors.
Figure 8. 220-ohm resistors. These ones are 4-band resistors
Photo of four breadboard-mounted pushbuttons
Figure 9. Pushbuttons
Multimeter tool. This tool has a dial to set the function, and three holes into which to plug the testing leads. The leads are currently plugged into the center hole and the right hand hole.
Figure 10. Multimeter tool

Testing The Meter

by Deqing Sun

Related video: Introduction to Multimeters

Before you get started, you will want to make sure your meter is working. This is a particularly good idea if you’re using a meter that lots of other people use, such as the ones at ITP. Here is how to test that:

Insert the two probes. Insert the Black probe in the “COM” jack. This is the COMmon, or ground, connection. The Red probe should be in the “V” jack (Figure 11). This connection is for measuring voltage. It can also be used to measure resistance in Ohms, or frequency in megaHertz, on the meter shown here.

Photo of the bottom half of a multimeter, showing the holes for the test leads. The left hole, labeled A, is empty. The center hole, labeled COM, has the black lead in it. The right hole, labeled VΩmA, has the red lead in it.
Figure 11. Multimeter detail, showing the holes for the probes.

Turn the function knob to the Diode/Continuity Function and switch the meter on. If the word “Hold” appears on the screen, press the hold button once to disable the hold function (not all meters have a clearly labeled Hold function; check your meter’s manual to be sure – see Figure 12). This function is used to hold a value onscreen after you remove the probes from a circuit. The “1.” on left picture means the value is out of range now.

Photo of a multimeter's top half, showing the screen and the power button on the left, and the hold button button on the right. Not all meters are arranged in the same way, so check your manual for the location of the buttons on yours.
Figure 12. This multimeter’s hold button is on the right side below the screen.

Touch the tips of the probes together. The meter will beep and the display value should be less than 0.01 (Figure 13). If it works, congratulations! you have a usable meter. If not, try to push the plug of the probes to improve the contacts (Figure 14). In many cases the failure is caused by loose contact of the jacks. In other cases, you might have a weak or dead battery.

Photo detail of .a meter measuring continuity. The two probes are touching each other. The meter reads .009. There is a diode symbol and a musical note on the left side of the screen.
Figure 13. Detail of .a meter measuring continuity. The meter is should be making a beeping sound in this case.
Photo detail of the bottom of a multimeter, showing the red lead not plugged in all the way.
Figure 14. If the meter is not working correctly, check to see if the probes are plugged in properly.

The Controls on a Meter

Different meters have different controls, but most meters will have the following:

  • Voltage: This setting is generally broken up into Volts DC, indicating that the polarity of the voltage will not change, and Volts AC, indicating that the polarity will alternate.
  • Amperage: This setting measures the current in a circuit. Again, it’s usually broken up into AC and DC. There are commonly two holes for the positive probe to measure current, one that’s low amperage and the other that’s high amperage. Don’t try to measure high amperages with the positive probe in the low amperage hole or you will damage the meter.
  • Resistance: Resistance is measured in ohms. This function is sometimes grouped with the continuity check.
  • Continuity: Continuity measures for a connection, generally very low or no resistance.
  • Diode Check: Diode check measures for a voltage drop across a diode, typically 2.7V or less. If you hold the positive probe on the anode of the diode and the common probe on the cathode, you’ll see a voltage drop. If you reverse the probes, you’ll see no reading.

Some meters are auto-ranging, meaning that they will choose the right order of magnitude for a reading automatically. These meters will only have one setting for a given property (volts, ohms, amps, etc). Other meters are not auto-ranging. These meters will have multiple settings for a given property. For example, the meter in the next section below has multiple settings for the resistance (or ohms) property: 2M (megohms), 200k (kilohms), 20k, 2k, and 200 ohms.

Many meters will have additional functions, like temperature, capacitance, transistor checks, and more. The functions listed above are the minimum that you can expect, however.

Figures 15 and 16 show two multimeters. Figure 16 is autoranging and Figure 15 is not. Notice how the autoranging meter has only one setting per function, while the non-autoranging meter has several per function. For example, Voltage on the meter in Figure 15 is divided into AC (marked by a ~) and DC (marked by a ⎓). Within  those two areas, there are multiple possible ranges: DC voltage can be set to 200mV, 2V, 20V, 200V, or 6ooV. Each range setting represents the maximum voltage you can read on that setting.

Photo of a non-autoranging multimeter.
Figure 15. A non-autoranging multimeter. Each function has multiple possible range settings.
Photo of an autoranging multimeter.
Figure 16. An autoranging multimeter. It has only one setting for each function and the meter automatically detects the range.

The Symbols on a Meter

Here are a few of the common symbols on electrical meters:

  • Volts: V
  • Ohms (resistance): Ω
  • Amps (current): A
  • AC: ~, ⏦ (tilde, sine wave)
  • DC: ⎓
  • Continuity: diode, speaker
  • Diode Check:diode
  • Non-Contact Voltage: NCV
  • Ground: ⏚ (vertical line with three horizontal lines below it)

Measuring Continuity

Continuity is simply whether or not there is a connection between two points. You just used this function to test your meter (Figure 17). Now you’ll use it to test a conductor.

Photo of a meter set to check continuity. The dial indicator is pointed to a symbol that has a dot next to three concentric arcs radiating out from the dot. This is a symbol for a speaker. The continuity check will beep.
Figure 17. This meter is ready to do a continuity check. The screen reads 1 on the right hand side. For this meter, this indicates that there is no continuity at the moment.

You can use the continuity check to find connections on a switch or if the pushbutton is connected when you press the button. You can also use it to measure whether there’s a break in a wire, or whether a given material conducts electricity. Set your meter as shown here, and try touching the probes together. The meter should beep.

Related video: Measure continuity with the Multimeter’s “beep”

Touching Two Ends of a Wire

Now try touching the probes to two ends of a wire. Again, the meter should beep. The wire conducts electricity. There is a continuous flow of electricity from one end of the wire to another.

Touching Two Points on a Switch

If you touch two points on a switch, what happens when you switch the switch? Beep or no beep? When you close the switch, the meter should beep, indicating that there is continuity between the two probes of the meter. If the meter beeps whether the switch is open or closed, then those two points are always connected.

Probing Points on a Breadboard

Put a wire in one hole of a breadboard that has no circuit on it. Then put another wire in another hole, chosen at random. Measure continuity between the two wires. Did you get what you expected? If the two holes were in the same row (or in the same column, on the side of the board) then you would get continuity and the meter would beep. If they were in different rows, then it would not beep.

Measuring Continuity Across Your Hand

Try measuring the continuity across your hand. Do you get anything? Why or why not? You probably don’t because the resistance across your skin is so high that it doesn’t register as a continuous conductor. It can conduct small amounts of current though. You don’t want your body to carry high amounts of current or voltage though, because it can damage or kill you.

Setup the Breadboard

For the rest of this lab, you’ll need a breadboard connected to a +5 Volt or +3.3 volt power supply. You can use an Arduino as your power supply (Using Arduino Uno shown in Figure 18, using Arduino Nano shown in Figure 20), if it’s connected to a USB power supply or a DC power supply, or you can solder together a DC power jack as shown in the Soldering lab, and use a 9-12V DC power supply and a 7805 voltage regulator (Figure 19). The voltage regulator will take the DC power supply’s Voltage and regulate it down to 5 Volts DC.

If you are using a Nano for the first time, you might want to check out these videos before you get started, to prep your board and care for your microcontroller.

Note: Schematics

The diagrams to the left of some of the breadboard images in this exercise are called schematics.They show the electrical layout (as opposed to the physical layout) of the components. For a good rundown on reading and understanding schematics, see this page and some very useful videos on this topic in the videos section of this site.

Related video: Using a voltage regulator on a breadboard

Breadboard drawing of an Arduino Uno connected to a breadboard. The Arduino's 5V hole has a red wire connecting it to the outer left side row of the board. This is the voltage bus on the left side. The Arduino's ground hole has a black wire connecting it to the inner left side row of the board. This is the ground bus on the left side. At the bottom of the breadboard, a red wire connects the left side voltage bus to the inner row on the right side. This is the right side voltage bus. Similarly, a black wire connects the left side ground bus to the outer row on the right side. This is the right side ground bus.
Figure 18. An Arduino Uno connected to a breadboard. The Arduino’s 5V and ground holes are supplying voltage to the breadboard.
Breadboard drawing of a DC power jack and a voltage regulator on a breadboard. At the top of the drawing, there is a DC power jack. Red and black wires from the jack connect to a 7805 5-volt voltage regulator mounted in the top right three rows of the breadboard with its tab facing to the right. input. The power supply's red wire is connected to the regulator's top pin row, the input pin. The power supply's black wire is connected to the regulator's middle pin, or ground. Another black wire connects the regulator's middle pin, ground, to the inner left side row of the board. This is the ground bus on the left side. A red wire connects the regulator's bottom pin, the output pin, to the outer left side row of the board. This is the voltage bus on the left side. At the bottom of the breadboard, a red wire connects the left side voltage bus to the inner row on the right side. This is the right side voltage bus. Similarly, a black wire connects the left side ground bus to the outer row on the right side. This is the right side ground bus.
Figure 19. DC voltage jack and 7805 voltage regulator on a breadboard. The regulator is supplying 5V and ground holes are supplying voltage to the rest of breadboard.
Arduino Nano on a breadboard.
Figure 20. Breadboard view of an Arduino Nano connected to a breadboard.When plugged into a USB port, this board will supply 3.3V across the voltage and ground buses. The +3.3 volts and ground pins of the Arduino are connected by red and black wires, respectively, to the left side rows of the breadboard. +3.3 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.

From here on out, diagrams will show the DC power supply and voltage regulator version, but feel free to use the Arduino version instead if you prefer.

Measuring Resistance of a Component

Resistance is a material property of any component, like a resistor or a wire. To measure the resistance of a component, you have to remove the component from the circuit. To measure resistance, turn your meter to the setting marked with the Greek letter Omega (Ω), as shown in Figure 21.

Photo of a multimeter set to measure resistance. The dial is pointing to a setting marked 20k in a section of the dial marked with the Greek letter omega.
Figure 21. Multimeter set to measure resistance.

If your meter is not an auto-ranging meter, you want the meter set to the approximate range, and slightly higher than, of the component’s resistance. For example, to measure a 10-Kilohm resistance, you’d choose 20K, because 10K and 20K are in the same order of magnitude. For a 50K resistance, or anything over 20K, you’d have to step up to 200K. If you don’t know the component’s resistance, start with the meter set to a high reading, like 2M (2 Megohms). If you get a reading of zero, turn the meter one step lower, and keep doing so until you get a good reading. A reading of 1 on the left side of the meter, or of 0L, indicates you’re set to too low a range.

Related video: Measure resistance with a Multimeter

Breadboard drawing of measuring resistance. A breadboard circuit similar to the one above is shown, with a 5-volt regulator and DC power jack. In this circuit, a red wire connects the left side power bus to row twelve. An LED is connected from row 15 to row 16, and a black wire connects row 16 to the left hand side ground bus. A 220-ohm resistor is off to the left side of the breadboard. It has been removed from the board to measure resistance. Two multimeter probes are attached to either end of the resistor.
Figure 22. Measuring resistance. Note that this circuit is not complete. To measure a component’s resistance, you have to take it out of the circuit.

Not all components will register resistance. For example, a wire will ideally register 0 Ohms, because you want wires to have as little resistance as possible so they don’t affect the circuit. The longer the wire, the greater the resistance, however. Likewise, switches have ideally zero resistance.

The circuit shown in Figure 22 is not complete. The resistor connecting the LED to voltage has been removed to measure its resistance. The resistor would normally connect in the row connecting to the red wire (row 12) to the anode of the LED (row 15). To measure resistance of a component, you must remove it from the circuit.

Resistance and Diodes

If you measure the resistance of a diode (such as the LED shown in Figure 20), you may see a number flash briefly on the meter, then disappear. This is because diodes ideally have little or no resistance once voltage is flowing through them, but have what’s called a forward bias, which is a minimum voltage needed to get current flowing. Before you reach the forward bias voltage, the diode’s resistance is ideally infinite. After you reach it, the resistance is ideally zero. There are no ideals in electronics, however, which is why you see a resistance value flash briefly as the meter meets the diode’s forward bias. Most meters have a diode check setting, marked with a diode symbol, that will allow you to check the forward bias of the diode.

Related video: Diodes and LEDs

Measuring Resistance Across Your Hand

Try measuring the resistance across your hand. Set the meter really high, perhaps 20 Megohms. Do you get anything? You should get a resistance in the 2-20 Megohm range. Make your palm sweaty, or lick it, and try again. You should get a lower resistance, perhaps 0.2 Megohms or so.

Measuring Voltage

Once a circuit is complete and powered, you should learn to read voltages between different points in the circuit. Wire a 7805 5-Volt voltage regulator on a breadboard as shown above and connect it to power. If you don’t have one, you can use the 5V or 3.3V output from an Arduino instead, as explained above. Now add an LED and a 220-ohm resistor to the breadboard as shown in Figure 23.

Breadboard drawing of a 220-ohm resistor and an LED powered by a 5-volt regulator . The breadboard is wired above, with a 5-volt voltage regulator and DC power jack. One side of the resistor is connected to the left side voltage bus of the breadboard. The other side is connected to row 15. The anode of an LED is connected to row 15 as well. The cathode of the LED is connected to row 16. A black wire connects row 16 to the left side ground bus.
Figure 23. Breadboard view of a 220-ohm resistor and an LED powered by a 5-volt regulator.

Note how the long leg, or anode, of the LED goes to voltage through the resistor, and the short leg, or cathode, goes to ground. Next you’re going to measure voltage in this circuit.

Voltage is a measure of the difference in electrical potential energy between two points in a circuit. It’s always measured between two points in a circuit. Measuring the voltage between the two sides of a component like an LED tells you how much voltage that component uses.  When you’re measuring voltage between one side of a component and another, for example, it’s called measuring the voltage drop “across” the component.

Set your multimeter to measure DC volts (Figure 24). The voltage regulator you’re using can take an input voltage range of about 8 to 15 volts, and it outputs 5 volts, so you know that no voltage you’ll read in this circuit is over 15 volts. If your meter has a variety of ranges for DC volts, choose a range that ‘s closest to, and greater than, 15 volts. For example, many meters have a setting for 20 volts, meaning that they can read up to 20V DC at that setting.

Photo of a multimeter set to measure DC voltage. The dial is pointing to a setting marked 20V in a section of the dial marked with the letter V and a horizontal line with a dashed line under it.
Figure 24. Multimeter set to measure voltage. Note the horizontal and dashed lines indicating DC.

Measure for voltage between the power and ground bus rows on the breadboard. You should have 5 volts, or very close to that.

Now measure the voltage drop across the LED (Figure 25). When you’re measuring the voltage drop  across a component, you put the meter probes in parallel with the component. In this case, the voltage across both the component and the meter will be the same.

Breadboard drawing of measuring voltage across an LED. The LED circuit is the same as shown above. The red probe of a multimeter is touching the anode of the LED. The black probe of the meter is touching the cathode of the LED.
Figure 25. Breadboard view of measuring voltage across an LED. The red lead is on the anode and the black lead is on the cathode of the LED.

Related video: Measuring voltage with a Multimeter

Getting a Negative Voltage

Did you get a negative voltage? Why would that happen? That means you placed the red probe on the point of lower voltage, and the black probe on the point of higher voltage. In other words, you reversed the polarity.

A Switched LED Circuit

Now you’re going to make a more complex circuit. Disconnect the board from power and add a switch in series with the LED and resistor as shown in Figure 26 and 27. Remember, long leg (anode) goes to voltage, short leg (cathode) goes to ground).

Schematic image of a pushbutton, a 220-ohm resistor and an LED connected to a 7805 5-volt regulator. At left, there is a power plug. The positive terminal of the power plug is connected to the voltage input of a 7805 voltage regulator. The negative terminal of the power plug is connected to the ground terminal of the regulator. The voltage output of the regulator is connected to one side of a pushbutton. The other side of the pushbutton is connected to a 220-ohm resistor. The other side of the resistor is connected to the anode of an LED. The cathode of the LED is connected to the ground terminal of the regulator.
Figure 26. Schematic view of a pushbutton controlling an LED. A DC power supply of 8-12V is connected to the input and ground of a 7805 5V voltage regulator. The output of the regulator is connected to a pushbutton. The other side of the pushbutton is connected to one side of a 220 ohm resistor. The other side of the resistor is connected to the anode of an LED. The cathode of the LED is connected to the voltage regulator’s ground connection.
Breadboard drawing of a solderless breadboard with a 7805 voltage regulator mounted on it as shown in the drawings above. The regulator is connected to a DC power plug, and the ground and voltage output of the regulator is connected to the voltage and ground bus rows on the right side of the breadboard. The ground and voltage bus rows on the right are connected to the ground and voltage bus rows on the left with wires at the bottom of the board. A pushbutton is mounted across the center of the breadboard, connected to rows ten and twelve. A red wire connects row ten to the voltage bus on the left side of the board. A 220-ohm resistor is connected to row twelve on the left side of the center section of the board. Its other end is connected to row sixteen in the center area. An LED is connected to another hole in row sixteen. The other side of the LED is connected to a hole in row seventeen. Another hole in row seventeen connects to the ground bus on the right side of the board.
Figure 27. Breadboard view of a pushbutton controlling an LED. The components are connected as described in Figure 26.

Connect the board to your power supply and press the switch. It will illuminate the LED. Let go of the switch and it will turn the LED off again. By pressing the switch you are completing a circuit and allowing the resistor and LED to begin consuming electricity. The resistor is very important in this circuit as it protects the LED from being over-powered, which will eventually burn it out. A typical LED operates at a voltage of 2.0-2.6 volts (V) and consumes approximately 20 milliamps (mA). The resistor limits the current to a level that is safe for the LED. The higher the resistor value, the less voltage that will reach the LED. The lower the resistor value (with 0 ohms being no resistor at all), the more  the voltage that will reach the LED.

Adding Up Voltage

Now, while playing with the pushbutton, measure the voltage across the pushbutton as you did in the last step, both in the on position and the off position. Is there a voltage drop across the pushbutton? What voltage do you read when the pushbutton is not pressed?

Measure the voltage across the LED and the resistor as well. Does the total voltage across all the components add up to the voltage between voltage and ground on your board? Remember, in any circuit, all of the voltage must be used up. Why? If the voltage across all the components doesn’t add up, that indicates to you that some of the electrical energy is getting converted to light, heat, and other forms of energy. No component is 100% efficient, so there’s always the possibility for some loss.

Components in Series

Change your circuit to add another LED in series with the first one, as shown in Figures 28 and 29.

Schematic image of a pushbutton, a 220-ohm resistor and two LEDs connected to a 7805 5-volt regulator. At left, there is a power plug. The positive terminal of the power plug is connected to the voltage input of a 7805 voltage regulator. The negative terminal of the power plug is connected to the ground terminal of the regulator. The voltage output of the regulator is connected to one side of a pushbutton. The other side of the pushbutton is connected to a 220-ohm resistor. The other side of the resistor is connected to the anode of an LED. The cathode of the LED is connected to another LED's anode. The cathode of the second LED is connected to the ground terminal of the regulator.
Figure 28. Schematic view of a pushbutton controlling two LEDs. This circuit is similar to the one in Figure 24, but there are two LEDs in series after the resistor. The cathode of the first LED connects to the anode of the second, and the cathode of the second LED connects to the regulator’s ground.
Breadboard drawing of a solderless breadboard as shown in the drawing above, with a 5-volt voltage regulator, a pushbutton, a 220-ohm resistor and 2 LEDs. The red probe of a multimeter is touching the side of the resistor that's connected to the pushbutton. The black probe of the meter is touching the other side of the resistor.
Figure 29. Breadboard view of a pushbutton controlling two LEDs. The components are wired as described in Figure 28.

Adding Up Voltage

Measure the voltage across the resistor, as shown in Figure 30. Then measure the voltage across each LED, as shown in Figures 31 and 32. Does the total add up to the voltage from power to ground? If not, where does the missing voltage go? The remaining energy is lost as heat generated from the components.

Breadboard drawing of a solderless breadboard as shown in the drawing above, with a 5-volt voltage regulator, a pushbutton, a 220-ohm resistor and 2 LEDs. The red probe of a multimeter is touching the side of the resistor that's connected to the pushbutton. The black probe of the meter is touching the other side of the resistor.
Figure 30. Measuring voltage across a resistor in a circuit. The circuit is wired as described in Figure 28. The meter’s leads are touching the two leads of the resistor.
Breadboard drawing of a solderless breadboard as shown in the drawing above, with a 5-volt voltage regulator, a pushbutton, a 220-ohm resistor and 2 LEDs. The red probe of a multimeter is touching anode of the first LED. The black probe of the meter is touching cathode of the first LED.
Figure 31. Measuring voltage across an LED in a circuit. The same circuit as Figure 28. The meter’s leads are touching the anode and cathode of the first LED.
Breadboard drawing of a solderless breadboard as shown in the drawing above, with a 5-volt voltage regulator, a pushbutton, a 220-ohm resistor and 2 LEDs. The red probe of a multimeter is touching the voltage bus on the left side of the board. The black probe of the meter is touching the ground bus on the left side of the board.
Figure 32. Measuring voltage across a whole circuit. The same circuit as Figure 28. The meter’s leads are touching the power and ground buses.

Did you use two different color LEDs and get a different voltage drop across each one? That’s normal. Different color LEDs are made with different elements, and have slightly different voltage drops. Did you get no reading when you measured? Did you remember to push the button before you took your reading?

Adding a Third LED in Series

Add a third LED in series with the other two. Do the LEDs light? Why or why not? They most likely will not light up. Each LED needs about 2V to reach its forward bias and turn on. If you have three in series, and a 5-volt supply, each is getting less than the 2V it needs to turn on.

Components in Parallel/Measuring Amperage

Connect three LEDs in parallel as shown in Figure 33 and 34 (remember, long leg (anode) goes to voltage, short leg (cathode) goes to ground):

Schematic image of a pushbutton, a 220-ohm resistor and three LEDs in parallel connected to a 7805 5-volt regulator. At left, there is a power plug. The positive terminal of the power plug is connected to the voltage input of a 7805 voltage regulator. The negative terminal of the power plug is connected to the ground terminal of the regulator. The voltage output of the regulator is connected to one side of a pushbutton. The other side of the pushbutton is connected to a 220-ohm resistor. The other side of the resistor is connected to the anodes of three LEDs. The cathodes of the three LEDs are connected to the ground terminal of the regulator.
Figure 33. Schematic view of a pushbutton controlling three LEDs wired in parallel. The circuit is similar to Figure 26, but the two LEDs have been replaced by three LEDs which are all in parallel. The anodes of all three LEDs are connected to the resistor, and the cathodes are all connected to the regulator’s ground connection.
A pushbutton is mounted across the center of the breadboard, connected to rows ten and twelve. A red wire connects the switch to the left side voltage bus. A 220-ohm resistor is connected to row twelve on the left side of the center section of the board. Its other end is connected to row sixteen in the center area. Three LEDs' anodes are connected to another hole in row sixteen. The cathodes of the LEDs are connected to holes in row seventeen. A black wire connects row seventeen to the ground bus on the left side of the board.
Figure 34. Breadboard view of a pushbutton controlling three LEDs wired in parallel. This circuit is wired as described in Figure 31.

Measure the voltage across each LED. It should be the same across each one.

Now you’re going to read the amperage at various points in the circuit. Move your meter’s red probe to the hole for measuring high amperage. On many meters, there are three holes, one marked  “Volts/Ohms/mA”,  and another marked “10A”. The right one can be used for measuring amperage when the expected amperage is less than 1A. The left is for measuring high amperage, up to 10A (Figure 35). If you’re not sure, it’s best to use the hole for 10A. Then set your meter to measure DC amperage.

Photo of a multimeter set to measure High DC Amperage. The dial is pointing to a setting marked 10A in a section of the dial marked with the letter A and a horizontal line with a dashed line under it. The red lead is in the hole marked 10A.
Figure 35. Multimeter set to measure amperage up to 10A.

To measure the amperage through a given component, you need to place your meter in series with the component. When two components are in series, the amperage flowing through both of them is the same. For this, use the circuit with the three parallel LEDs that’s shown in Figures 36 and 37. To measure the amperage through any one of the LEDs in this circuit, you’ll need to disconnect one of the LED’s ends from the circuit (disconnect power first!) and use the meter to complete the circuit, as shown in Figures 36 and 37:

Schematic image of how to measure amperage of three LEDs in parallel. The circuit is similar to the parallel circuit shown above. At left, there is a power plug. The positive terminal of the power plug is connected to the voltage input of a 7805 voltage regulator. The negative terminal of the power plug is connected to the ground terminal of the regulator. The voltage output of the regulator is connected to one side of a pushbutton. The other side of the pushbutton is connected to a 220-ohm resistor. The other side of the resistor is connected to the anodes of three LEDs. A meter set to measure amperage is inserted between the resistor and one of the LEDs. The cathodes of the three LEDs are connected to the ground terminal of the regulator.
Figure 36. Schematic view of measuring amperage of one LED of three LEDs wired in parallel. This is the same circuit as shown in Figure 31, but the anode of one LED has been disconnected and then connected to one lead of a meter measuring amps. The other lead of the meter is connected to the junction between the resistor and the anodes of the other two LEDs.
A pushbutton is mounted across the center of the breadboard, connected to rows ten and twelve. A red wire connects the switch to the left side voltage bus. A 220-ohm resistor is connected to row twelve on the left side of the center section of the board. Its other end is connected to row sixteen in the center area. Three LEDs' anodes are connected to another hole in row sixteen. The probes of a multimeter are inserted in between the anode of one of the LEDs and row sixteen. The cathodes of the LEDs are connected to holes in row seventeen. A black wire connects row seventeen to the ground bus on the left side of the board.
Figure 37. Breadboard view measuring amperage of one LED of three LEDs wired in parallel. This circuit is wired as shown in Figure 34.

You’ll find that the amperage drawn by the LEDs is tiny, on the order of 10 or 20 milliamps at the most. That’s normal for LEDs. Make sure that you check which holes your meter probes are connected to when you’re using a meter.

Warning: Measuring amperage with the red probe in the voltage hole when you have no idea how big the current is, or measuring voltage with it in the amperage holes is a good way to damage the meter.

Related video: Measuring amperage (current) with a Multimeter

Related video: Measure current in series, and voltage in parallel

Generating a Variable Voltage with a Potentiometer

In this last step, you’ll generate a changing voltage using a potentiometer. A potentiometer is a resistor that can change its resistance. A potentiometer (or pot) has three connections. The outer connections are the ends of a fixed value resistor. The center connection connects to a wiper which slides along the fixed resistor. The resistance between the center connection and either of the outside connection changes as the pot’s knob is moved. Related video: Potentiometer schematic

If your potentiometer does not have pins that will insert into a breadboard, then solder hook-up wires to the pot connections as shown in Figures 38 and 39.

Photo of a potentiometer with metal ring contacts.
Figure 38. A potentiometer with ring contacts, ready for soldering.
Photo of a potentiometer with ring contacts. Three wires are soldered to the three contacts, from left to right: black wire, blue wire, red wire.
Figure 39. Potentiometer with wires successfully soldered.

Next, connect the pot to an LED and a 220-ohm resistor using the circuit shown in Figure 38:

Schematic image of a potentiometer controlling an LED. At left, there is a DC power plug. The positive terminal of the power plug is connected to the voltage input of a 7805 voltage regulator. The negative terminal of the power plug is connected to the ground terminal of the regulator. The voltage output of the regulator is connected to one side of a potentiometer. The other side of the potentiometer is connected ground. The wiper of the potentiometer is connected to a 220-ohm resistor. The other side of the resistor is connected to the anode of an LED. The cathode of the three LEDs are connected to ground.
Figure 40. Schematic view of a potentiometer controlling an LED. The two ends of a potentiometer are attached to the voltage output and ground of a 7805 voltage regulator. The middle contact of the potentiometer is connected to one end of a 220-ohm resistor. The other end of the resistor is connected to the anode of an LED. The cathode of the LED is connected to ground.
Breadboard drawing of a potentiometer controlling an LED. A 7805 5-volt voltage regulator powers the board as shown in the circuits above. A potentiometer's outer connections are connected to the voltage bus and ground bus on the left side of the board. The center of the potentiometer connects to row seventeen on the left side of the center section of the board. A 220-ohm resistor is connected to row seventeen on the left side as well. Its other end is connected to row twenty-one in the left center area. An LED's anode is connected to another hole in row twenty-one. The LED's cathode is connected to row twenty-two. A black wire connects row twenty-two to the ground bus on the left side of the board.
Figure 41. Breadboard view of a potentiometer controlling an LED. This circuit is wired as described in Figure 40.

As you turn the potentiometer from one end to the other, measure the voltage between the center position and ground. The pot is acting as a voltage divider, dividing the 5V into two parts. As the voltage feeding the LED goes up or down, the LED gets brighter or dimmer. The 220-ohm resistor in the circuit protects the LED from over-voltage when the resistance between the pot’s voltage lead and its center lead is 0 ohms.

Related video: Measure a potentiometer’s variable resistance

Now you’ve got a basic understanding of how to use a meter to measure voltage, current, resistance, and electrical continuity. You’ll use these tests all the time.

Next, check out the lab on Switches.

Lab: Tone Output Using An Arduino

In this tutorial you’ll learn how to generate simple tones on an Arduino

Introduction

This lab is an introduction to generating simple tones on an Arduino. In order to make the most of this lab, you should understand the basics of how to program digital input and output on an Arduino, and how to read a simple circuit diagram.

Video of this lab

What You’ll Need

Making Sound Electronically

The following is adapted from SoundExamples.

Sound is created by vibrations in air. When those vibrations get fast enough, above about 20 times a second, you hear them as an audible pitch. The number of vibrations per second is called the frequency and frequency is measured in Hertz (Hz). So 20 times a second is 20Hz. Humans can hear pitches from about 20Hz to about 20,000Hz, or 20 kiloHertz (kHz).

What vibrations are we talking about? A speaker can vibrate. The paper cone of the speaker moves forward, then backward, then back to its resting place many times a second. The length of time it takes to move from rest through one back-and-forth motion, is called the period of the vibration. For example, if a speaker is vibrating at 20Hz, then it moves forward, backward, and back to rest 2in 1/20 of a second, or 0.05 seconds. 0.05 seconds is the period of the sound. Period and frequency are related inversely: frequency = 1/period.

A microcontroller makes sound by sending pulses of electrical energy from an output pin through a wire that’s connected to the paper cone of a speaker. That wire is wrapped in a coil, and mounted inside a magnet. The electrical energy generates a magnetic field, and that field is either attracted to the magnet or repelled by it, depending on which direction the electrical energy is flowing. The magnetic energy moves the coil, and since the coil is attached to the cone, the speaker moves.

So in summary: how do you make sound from an Arduino? Attach a speaker to an output pin and turn it on and off at a set frequency. You can write this code yourself, or you can use the tone() command.

Pulsewidth Modulation vs. Frequency Modulation

When you use analogWrite() to create pulsewidth modulation (PWM) on an output pin, you’re also turning the pin on and off, so you might think, “why not use analogWrite() to make tones?” That command can change the on-off ratio of the output (also known as the duty cycle) but not the frequency. If you have a speaker connected to an output pin running analogWrite(), you’ll get a changing loudness, but a constant tone. To change the tone, you need to change the frequency. The tone() command does this for you.

Prepare the breadboard

Connect power and ground on the breadboard to the microcontroller. On the Arduino module, use the 5V or 3.3V (depending on your model) and any of the ground connections. Figures 8 and 9 show connections for an Arduino Uno and a Nano, respectively.

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 8. Breadboard view of 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 (Figure 8). 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 9. Breadboard view of an Arduino Nano mounted on a solderless breadboard.

In Figure 9, 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 the Sensors and the Speaker

Connect a variable resistor such as a force-sensing resistor or photosensor to analog pin 0 in a voltage divider circuit as shown below. The 8-ohm speaker connects to pin 8 of the Arduino. You can use any digital I/O pin if you don’t like 8. The other end of the speaker connects to ground. Figures 10 through 12 show the schematic drawing and the breadboard layouts for an Uno and a Nano, respectively.

Note: Although the circuit shown in Figures 10-12 has a 100-ohm resistor with the speaker, you can use a larger resistor. The larger the resistor, the quieter the speaker. A 220-ohm resistor works reasonably well if you don’t have a 100-ohm resistor.

Figure 10. Schematic view of an Arduino connected to a force sensing resistor (FSR), a 10-kilohm resistor, and a speaker. One leg of the FSR is connected to voltage. The other leg is connected simultaneously to the first leg of a 10-kilohm resistor and the Arduino’s analog input pin A0. The second leg of the 10-kilohm resistor is connected to ground. The red positive wire of the speaker is connected to digital pin 8 of the Arduino. The black ground wire of the speaker is connected to one leg of a 100 ohm resistor. The other leg of the resistor connects to ground.
Figure 11. Breadboard view of an Arduino connected to a force-sensing resistor, a fixed resistor, and a speaker. The Arduino’s voltage out and ground pins are connected to the voltage and ground buses of the breadboard as usual. The FSR is mounted in the left center section of the breadboard. One leg of the FSR is connected to 5 volts. The other leg is connected simultaneously to the first leg of a 10-kilohm resistor and the Arduino’s analog input pin A0. The second leg of the 10-kilohm resistor is connected to ground. The red positive wire of the speaker is connected to digital pin 8 of the Arduino. The black ground wire of the speaker is connected to one leg of a 100 ohm resistor. The other leg of the resistor connects to ground.
Breadboard view of an Arduino Nano connected to two force sensing resistors (FSRs) and a speaker.
Figure 12. Breadboard view of an Arduino Nano connected to two force sensing resistors (FSRs) and a speaker. The Nano’s 3.3 Volts (physical pin 2) and ground (physical pin 14) are connected to the voltage and ground buses of the breadboard as usual. The FSR is mounted below the Nano in the left center section of the breadboard. One leg of the FSR is connected to voltage. The other leg is connected simultaneously to the first leg of a 10-kilohm resistor and the Arduino’s analog input pin A0. The second leg of the 10-kilohm resistor is connected to ground. The red positive wire of the speaker is connected to digital pin 8 of the Arduino. The black ground wire of the speaker is connected to one leg of a 100 ohm resistor. The other leg of the resistor connects to ground.

Check the sensor input range

Once you’ve got the circuit connected, check the range of the analog input and note the highest and lowest values you can reach.

1
2
3
4
5
6
7
8
void setup() {
  Serial.begin(9600);       // initialize serial communications
}
 
void loop() {
  int analogValue = analogRead(A0); // read the analog input
  Serial.println(analogValue);      // print it
}

Check that the Speaker Works

You can check that the speaker works by playing a single tone over and over. Here’s a short sketch to play middle A, 440Hz:

1
2
3
4
5
6
7
8
9
10
void setup() {
  // nothing to do here
}
 
void loop() {
  // play the tone for 1 second:
  tone(8, 440,1000);
  // do nothing else for the one second you're playing:
  delay(1000);
}

When you run this sketch, you should hear a tone of 44oHz, or middle A, continually. If you don’t, check to see that your speaker wiring is as shown above. If it’s too soft, try changing the 100 Ohm resistor to a smaller resistor.

Play Tones

Write a sketch to read the analog input and map the result to a range from 100 to 1000. The example below assumes your analog input circuit ranges from 200 to 900, so adjuct for your actual values.  Store the result in a local variable called frequency. This will be the frequency you play on the speaker Then use the tone() command to set the frequency of the speaker on pin 8.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
void setup() {
  // nothing to do here
}
 
void loop() {
  // get a sensor reading:
  int sensorReading = analogRead(A0);
  // map the results from the sensor reading's range
  // to the desired pitch range:
  float frequency = map(sensorReading, 200, 900, 100, 1000);
  // change the pitch, play for 10 ms:
  tone(8, frequency, 10);
  delay(10);
}

Once you’ve uploaded this, move your hands over the photocells, and listen to the frequency change. It will change from 100 Hz to 1000 HZ, because that’s what you set in the map() command. If you want to change the frequency range, change those two numbers. See if you can get it to play a little tune.

If you want to know how to generate a tone without the tone() command, here’s the basic algorithm to play one wavelength:

1
2
3
4
5
6
7
8
9
10
11
12
void makeTone(float frequency) {
  // set the period in microseconds:
  int period = (1 / frequency) * 1000000
  // turn the speaker on:
  digitalWrite(speakerPin, HIGH);
  // delay half the period:
  delayMicroseconds(period / 2);
  // turn the speaker off:
  digitalWrite(speakerPin, LOW);
  // delay half the period:
  delayMicroseconds(period / 2);
}

Play it Loud

If you’d like to amplify the speaker, modify the speaker circuit by adding a transistor. Most any NPN transistor circuit or N-channel MOSFET will do. Figure 13 shows a speaker getting power from a transistor. This example uses a TIP120 transistor, but an NPN transistor or N-channel MOSFET should work. When using a transistor to amplify the power going to the speaker, you should definitely use a resistor to limit the current. A 100-ohm resistor is shown in this example.

Schematic view of a speaker connected to a transistor
Figure 13. Schematic view of a speaker connected to a transistor. The first leg of the speaker connects to the Arduino’s voltage supply (3.3V). The second leg of the speaker connects to a10-0-ohm resistor. The other side leg of the resistor connects to the collector pin of an NPN transistor (for a TIP120 transistor, this is the middle pin). The transistor’s base pin (the pin to the left when the transistor’s body is facing you) connects to the Arduino’s tone output pin (pin 8 in the examples above). The transistor’s collector pin (on the right when the transistor is facing you) connects to ground.
Figure 14. Breadboard view of a speaker connected to a transistor. The speaker and transistor are connected exactly as described in the schematic view caption in Figure 13.

Use Headphones

You can also connect the tone output of an Arduino to headphones. Using a standard 3.5mm audio jack, connect the center pin of the jack to ground through a 10-kilohm resistor. Then connect the two sides to each other and to your tone output pin. The 10-kilohm resistor here is important, because without it the audio signal will be too strong for your headphones, and could cause you ear damage. Figure 15 shows an audio jack connected to an Arduino Nano 33 IoT for the examples shown here.

Breadboard view of a 3.5mm Audio jack connected to an Arduino Nano 33 IoT.
Figure 15. Breadboard view of a 3.5mm Audio jack connected to an Arduino Nano 33 IoT. The center pin of the audio jack is connected to ground through a 10-kilohm resistor. The two sides are connected to the Nano 33’s tone output pin, which is pin 8 in this example.

A more complex example

There’s an example in the Arduino IDE examples that can play a melody for you. Look in the File Menu under Examples -> Digital -> ToneMelody. You can find the code online at this link. In this example, you’ll see a second tab of text called pitches.h. This file includes constants that give you the pitches for a standard western scale.

You can add your own extra tabs using the new Tab menu to the right of the IDE window. Figure 16 shows the new Tab dropdown menu. Tabs make it easier to separate frequently copied code from custom code for a sketch, as you see in this example.

A dropdown menu located in the upper right hand corner of the Arduino IDE. In order the options are "New Tab", "Rename", "Delete", "Previous Tab", "Next Tab", and the last option shows the name of the sketch
Figure 16. A dropdown menu located in the upper right hand corner of the Arduino IDE showing the tab options. You can also type cmmand-shift-N to get a new tab.

You’ll notice that pitches.h lists a number of note names and numbers. Those numbers are the frequency of each note. For example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
/*************************************************
* Public Constants
*************************************************/
 
#define NOTE_B0  31
#define NOTE_C1  33
#define NOTE_CS1 35
#define NOTE_D1  37
#define NOTE_DS1 39
#define NOTE_E1  41
#define NOTE_F1  44
#define NOTE_FS1 46
#define NOTE_G1  49
#define NOTE_GS1 52
#define NOTE_A1  55
#define NOTE_AS1 58
#define NOTE_B1  62
#define NOTE_C2  65
#define NOTE_CS2 69
#define NOTE_D2  73

This tells you that that first note in the list, B0 (which is the second lowest note on a piano keyboard, 4 octaves below middle A) has a frequency of 31 Hz. The values listed in pitches.h allow you to play notes from B0 to D#8.

For this sketch, you’ll play a simple melody. A melody consists of notes played in a sequence, and rests between the note. Each note and rest has its own particular duration. You’re going to play a seven note sequence, as shown in Figure 17 (in C Major):

Two measures of a musical notation in 4 / 4 time. The notes are C4, G3, G3, G#3, G3,rest, B3, C4 the respective durations are: quarter note, eighth note, eighth note, quarter note, quarter note, quarter rest, quarter note, quarter note
Figure 17. Two measures of a musical notation. The melody is “Shave and a haircut, two bits”

image from seventhstring.com

The sequence is: C4, G3, G3, G#3, G3, rest, B3, C4

the durations are:

quarter note, eighth note, eighth note, quarter note, quarter note, quarter rest, quarter note, quarter note.

The sketch starts with two global variables. Using pitches.h, make an array variable holding those notes. Make a second array to hold the note durations, marking quarter notes as 4 and eighth notes as 8.

1
2
3
4
5
6
7
// notes in the melody:
int melody[] = {
NOTE_C4, NOTE_G3,NOTE_G3, NOTE_GS3, NOTE_G3,0, NOTE_B3, NOTE_C4};
 
// note durations: 4 = quarter note, 8 = eighth note, etc.:
int noteDurations[] = {
4, 8, 8, 4,4,4,4,4 };

How can you use the durations to play notes? Well, imagine that a quarter note is one quarter of a second, and eighth note is one eighth of a second, and so forth. In that case, the actual duration for each note is 1000 milliseconds divided by the value for it in the durations array. For example, the first note is 1000/4, the second is 1000/8, and so forth.

Now, you only want to play the song once, so everything will happen in the setup(). You’ll make a for loop in the setup to iterate over the seven notes. For each time through the loop, use tone() to play the next note in the array. Use the formula in the last paragraph to determine how long each note should play for. After you start the note, delay for as long as the note plays, plus 30 milliseconds or so, to separate each note.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include "pitches.h"
 
// notes in the melody:
int melody[] = {
NOTE_C4, NOTE_G3,NOTE_G3, NOTE_GS3, NOTE_G3,0, NOTE_B3, NOTE_C4};
 
// note durations: 4 = quarter note, 8 = eighth note, etc.:
int noteDurations[] = {4,8,8,4,4,4,4,4 };
 
void setup() {
  // iterate over the notes of the melody:
  for (int thisNote = 0; thisNote < 8; thisNote++) {
    // to calculate the note duration, take one second
    // divided by the note type.
    //e.g. quarter note = 1000 / 4, eighth note = 1000/8, etc.
    int noteDuration = 1000/noteDurations[thisNote];
    tone(8, melody[thisNote],noteDuration);
 
    //pause for the note's duration plus 30 ms:
    delay(noteDuration +30);
  }
}
 
void loop() {
  // no need to repeat the melody.
}

That’s the whole tune!

The Relation Between Pitches

For those interested in a little music theory, here’s where those frequency values in pitches.h came from. If you’re not interested in the details, feel free to skip to the next section.

You may have noticed in pitches.h that the value of B1 was twice that of B0, and that C1 is twice C0, and so forth.  In European classical music tradition, the most common tuning system in the last few hundred years has been the 12-tone equal temperament system. This system divides an octave into twelve pitches, in which the frequency interval between every pair of adjacent notes has the same ratio. The pitches are arranged on a logarithmic scale, and the ratio between pitches is equal to to the 12th root of 2, or 21/12, or approximately 1.05946. The whole tuning system is based off a reference frequency, 440 Hz, or middle A (a in the 4th octave, or A4). The step between each adjacent note is called a semitone. Wikipedia’s page on equal temperament gives a longer explanation if you want to know more. Musictheory.net is also a great source of information.

You can use this information to dynamically generate notes in this scale:

frequency = 440 * 2^((noteValue - 69) / 12.0));

This formula, taken from the MIDI tuning standard, works for a range of notes. Using this formula, note 27 is A0, the lowest note on a piano, and note 108 is C8, the highest note on a piano. 440 is the reference frequency, middle A, and 69 is the note number of middle A in MIDI. With this formula, you can cover a wide range of human hearing with note values 0 to 127. And you could generate note frequencies without needing pitches.h. This formula can be handy if you decide to dive into building MIDI devices later on as well. The Arduino API includes a function called the pow() function that raises a number to a power. So that formula, expressed as a line of Arduino programming code, would look like this:

float frequency =  440 * pow(2, ((noteValue - 69) / 12.0));

And the “shave and a haircut” tune from above, would be:

int melody[] = {40, 35,35, 36, 35, 0, 39, 40};

Expressed in note values like this, it would be simple to convert a musical sketch from playing using tone() to playing using a MIDI synthesizer.

Next, try making a musical instrument.

A Musical Instrument

Playing a tune like you just doesn’t allow for much user interaction, so you might want to build more of a musical instrument.

Here’s an example of how to use the note constants to make a simple keyboard. Figures 18-20  show the circuit.

Schematic view of an Arduino connected to three force sensing resistors (FSR) and a speaker. Each of the three FSRs have one of their respective legs connected to +5 volts. Each of the other legs connect to one leg of a 10-kilohm resistor and simultaneously connect to one of the Arduino's analog input pins. In this case the pin connections are A0, A1, and A2. Each of the respective 10-kilohm resistors then connect to ground. The red positive wire of the speaker is connected to digital pin 8 of the Arduino. The black ground wire of the speaker is connected to one leg of a 100 ohm resistor. The other leg of the 100-ohm resistor connects to ground.
Figure 18. Schematic view of an Arduino connected to three force sensing resistors and a speaker.
Breadboard view of an Arduino connected to three force sensing resistors (FSR) and a speaker. Each of the three FSRs have one of their respective legs connected to +5 volts. Each of the other legs connect to one leg of a 10-kilohm resistor and simultaneously connect to one of the Arduino's analog input pins. In this case the pin connections are A0, A1, and A2. Each of the respective 10-kilohm resistors then connect to ground. The red positive wire of the speaker is connected to digital pin 8 of the Arduino. The black ground wire of the speaker is connected to one leg of a 100 ohm resistor. The other leg of the 100 ohm resistor then connects to ground.
Figure 19. Breadboard view of an Arduino connected to three force sensing resistors (FSR) and a speaker. Each of the three FSRs have one of their respective legs connected to +5 volts. Each of the other legs connect to one leg of a 10-kilohm resistor and simultaneously connect to one of the Arduino’s analog input pins. In this case the pin connections are A0, A1, and A2. Each of the respective 10-kilohm resistors then connect to ground. The red positive wire of the speaker is connected to digital pin 8 of the Arduino. The black ground wire of the speaker is connected to one leg of a 100 ohm resistor. The other leg of the 100 ohm resistor then connects to ground.

Figure 20. Breadboard view of an Arduino Nano connected to three force sensing resistors (FSR) and a speaker. Each of the three FSRs have one of their respective legs connected to the voltage bus of the breadboard. Each of the other legs connect to one leg of a 10-kilohm resistor and simultaneously connect to one of the Arduino’s analog input pins. In this case the pin connections are A0, A1, and A2. Each of the respective 10-kilohm resistors then connect to ground. The red positive wire of the speaker is connected to digital pin 8 of the Arduino. The black ground wire of the speaker is connected to one leg of a 100 ohm resistor. The other leg of the 100 ohm resistor then connects to ground.

Program it

Make a sketch that plays a note on each sensor when the sensor is above a given threshold.

Start with a few constants: one for the threshold, one for the speaker pin number, and one for the duration of each tone. To make this instrument work, you need to know what note corresponds to each sensor. Include pitches.h as you did above, then make an array that contains three notes, A4, B4, and C3 as well. Set all of this up at the beginning of your sketch, before setup().

1
2
3
4
5
6
7
8
9
#include "pitches.h"
 
const int threshold = 10;      // minimum reading of the sensors that generates a note
const int speakerPin = 8;      // pin number for the speaker
const int noteDuration = 20;   // play notes for 20 ms
 
// notes to play, corresponding to the 3 sensors:
int notes[] = {
NOTE_A4, NOTE_B4,NOTE_C3 };

You don’t need anything in your setup(), but in your loop, you need a for loop that iterates over the first three analog inputs, 0, 1, and 2. For each one, read the sensor, and if it’s above a threshold, play the corresponding note in the notes array for the note duration.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include "pitches.h"
 
const int threshold = 10;      // minimum reading of the sensors that generates a note
const int speakerPin = 8;      // pin number for the speaker
const int noteDuration = 20;   // play notes for 20 ms
 
// notes to play, corresponding to the 3 sensors:
int notes[] = {
NOTE_A4, NOTE_B4,NOTE_C3 };
 
void setup() {
 
}
 
void loop() {
  for (int thisSensor = 0; thisSensor < 3; thisSensor++) {
    // get a sensor reading:
    int sensorReading = analogRead(thisSensor);
 
    // if the sensor is pressed hard enough:
    if (sensorReading > threshold) {
      // play the note corresponding to this sensor:
      tone(speakerPin, notes[thisSensor], noteDuration);
    }
  }
}

When you upload this sketch, you should have a three-key keyboard.

Get Creative

Now that you’ve got the basics, think about making an instrument for one of your projects. For more background on musical structure, see these notes on tone and generating a melody.

Doing More with Sound Output

If you’re interested going deeper into using sound outputs using speakers, take a look at the Mozzi Libary to produce more complex sound. In a future session, you’ll learn to play and control .wav files from Arduino, which is based on the I2S Library that connect digital audio devices together.

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:

1
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:

1
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

Analog Input

Introduction

This is an introduction to basic analog input 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:

These video links will help in understanding analog input:

Analog Input

While a digital input to a microcontroller can tell you about discrete changes in the physical world, such as whether the cat is on the mat, or the cat is off the mat, there are times when this is not enough. Sometimes you want to know how fat the cat on the mat is. In order to know this, you’d need to be able to measure the force the cat exerts on the mat as a variable quantity. When you want to measure variably changing conditions like this, you need analog inputs. An analog input to a microcontroller is an input that can read a variable voltage, typically from 0 volts to the maximum voltage that powers the microcontroller itself.

Many transducers are available to convert various changing conditions to changing electrical quantities. There are photocells that convert the amount of light falling on them to a varying resistance; flex sensors that change resistance as they are bent; Force-sensitive resistors (FSRs) that change resistance based on a changing force applied to the surface of the sensor; thermistors that change resistance in response to changing heat; and many more.

Related video: Resistors, variable resistors, and photocells

In order to read these changing resistances, you put them in a circuit and pass a current through them, so that you can see the changing voltage that results. There are a few variations on this circuit. The simplest is called a voltage divider. Because the two resistors are in series voltage at the input to the microcontroller is proportional to the ratio of the resistors. If they are equal, then the input voltage is half the total voltage. So in the circuit in Figure 1, if the variable resistor changes (for example, if it’s a flex sensor being bent), then the voltage at the input changes.  The fixed resistor’s value is generally chosen to complement the variable resistor’s range. For example, if you have a variable resistor that’s 10-20 kilohms, you might choose a 10 kilohm fixed resistor.

analog in schematic
Figure 1. voltage divider with a variable resistor and a fixed resistor

In Figure 2, you use a potentiometer,  which is a variable resistor with three connections. The center of the potentiometer, called the wiper,  is connected to the microcontroller. The other two sides are attached to power and ground. The wiper can move from one end of the resistor to the other. In effect, it divides the resistor into two resistors and measures the resistance at the point where they meet, just like a voltage divider.

Related videos:

potentiometer schematic
Figure 2. potentiometer schematic

Since a microcontroller’s inputs can read only two values (typically 0 volts or the controller’s supply voltage), an analog input pin needs an extra component to read this changing, or analog voltage, and convert it to a digital form. An analog-to-digital converter (ADC) is a device that does this. It reads a changing input voltage and converts it to a binary value, which a microcontroller can then store in memory.Many microcontrollers have ADCs built in to them. Arduino boards have an ADC attached to the analog input pins.

The ADC in the Arduino can read the input voltage at a resolution of 10 bits. That’s a range of 1024 points. If the input voltage range (for example, on the Uno) is 0 to 5 volts, that means that the smallest change it can read is 5/1024, or 0.0048 Volts. For a 3.3V board like the Nano 33 IoT, it’s 0.0029 volts. When you take a reading with the ADC using the analogRead() command, the microcontroller stores the result in memory. It takes an int type variable to store this, because a byte is not big enough to store the 10 bits of an ADC reading. A byte can hold only 8 bits, or a range from 0 to 255.

The command in Arduino is the analogRead() command, and it looks like this:

1
sensorReading = analogRead(pin);
  • Pin is the analog input pin you are using;
  • sensorReading is an integer variable containing the result from the ADC.

The number produced in sensorReading is will be between 0 and 1023. Its maximum may be less, depending on the circuit you use. A potentiometer will give the full range, but a voltage divider for a variable resistor like a force sensing resistor or flex sensor, where one of the resistors is fixed, will not.

The analog inputs on an Arduino (and in fact, on most microcontrollers), are all connected to the same ADC circuit, so when the microcontroller has to switch the ADC’s input from one pin to another when you try to read two pins one after another. If you read them too fast, you can get unstable readings. You can also get more reliable readings by introducing a small delay after you take an analog reading. This allows the ADC time to stabilize before you take your next reading.

Here’s an example of how to read three analog inputs with minimal delay and maximum stability:

1
2
3
4
5
6
sensorOne = analogRead(A0);
delay(1);
sensorTwo = analogRead(A1);
delay(1);
sensorOne = analogRead(A2);
delay(1);

Analog and digital inputs are the two simplest ways that a microcontroller reads changing sensor voltage inputs. Once you’ve understood these two, you’re ready to use a variety of sensors.

Lab: Using a Transistor to Control a High Current Load

In this tutorial, you’ll learn how to control a high-current load with a transistor.

Introduction

Transistors are often used as electronic switches, to control loads which require high voltage and current from a lower voltage and current. The most common example you’ll see of this in a physical computing class is to use an output pin of a microcontroller to turn on a motor or other high current device. The output pins of a microcontroller can only produce a small amount of current and voltage. But when coupled with a transistor, they can control much more.

What You’ll Need To Know

You should have read the notes on high current loads before doing this lab. In order to get the most out of this lab, you should know the basics of electronics, as well as how to use a solderless breadboard. It would help to do some reading on DC motors as well.

Microcontrollers aren’t the only integrated circuits that produce a low voltage and current on their output pins. There are many components that do this. You’ll see a whole range of so-called logic ICs that can’t produce very much current or voltage, but can produce a small change on their output pins that can be read as a data or control signal. The output voltage from devices is often referred to as a logic or a control voltage, as opposed to the supply or load voltage needed to control the high-current device. You can use transistors from circuits like these. For example, you might put a transistor on the output pin of a 555 timer IC (which produces a variable timing pulse), or a shift register IC (which allows you to produce multiple control signals in parallel) to control high current loads from those devices.

Things You’ll Need

Figures 1-12 are the parts you’ll need for this exercise.

Set Up the Breadboard

Connect a 7805 5V voltage regulator to your board, and power it from a 9-12V DC power supply. Connect the ground rows on the sides together. Don’t connect the two red rows on the side of the breadboard to each other, though. Wire the breadboard so that the right side of the board receives the 5V output from the regulator, but the left side gets 9-12V directly from your DC power supply. The 5V line is the 5-volt bus or logic supply and the 9-12V line is the high-voltage bus or load supply. The two ground lines are ground. Figure 13 shows the schematic drawing and Figure 14 shows the breadboard view of the circuit explained here.

Schematic drawing of a DC power jack connected to a 7805 5-volt voltage regulator. At left, there is a power plug. The positive terminal of the power plug is connected to the voltage input of a 7805 voltage regulator (the terminal on the left as it faces you). The negative terminal of the power plug is connected to the ground terminal of the regulator (the terminal in the middle).
Figure 14. Schematic drawing of a DC power jack connected to a 7805 5-volt voltage regulator.
At the top of the drawing, there is a DC power jack. Yellow and black wires from the jack connect to a 7805 5-volt voltage regulator mounted in the top right three rows of the breadboard with its tab facing to the right. The power supply's yellow wire is connected to the regulator's top pin row, the input pin. The power supply's black wire is connected to the regulator's middle pin, or ground. A yellow wire connects the regulator's top pin, the input pin, to the outer left side row of the board. This is an unregulated voltage bus on the left side. It will be used to control the motor. A red wire connects the regulator's output pin, the bottom pin, to the inner right side bus. This will be the regulated voltage bus. Another black wire connects the regulator's middle pin, ground, to the inner right side row of the board. This is the ground bus on the left side. Similarly, a black wire connects the left side ground bus to the outer row on the right side. This is the right side ground bus. There is no connection between the unregulated voltage bus on the left and the regulated voltage bus on the right, however.
Figure 14. DC voltage jack and 7805 voltage regulator on a breadboard. The regulator is supplying 5V and ground holes are supplying voltage to the rest of breadboard.

Add a Motor and Transistor

The transistor allows you to control a circuit that’s carrying higher current and voltage from the a lower voltage and current. It acts as an electronic switch. The one you’re using for this lab is an NPN-type transistor called a TIP120. The datasheet for it can be found here. It’s designed for switching high-current loads. It has three connections, the base, the collector, and the emitter as shown in Figure 15 and Figure 16. Attach high-current load (i.e. the motor or light) to its power source, and then to the collector of the transistor. Then connect the emitter of the transistor to ground. Then to control the motor, you apply voltage to the transistor’s base. When there’s at least a 0.7V difference between the base and the emitter, the transistor will “turn on” — in other words, it’ll allow voltage and current to flow from the collector to the emitter. When there’s no voltage difference between the base and the emitter, the transistor turns off, or stops the flow of electricity from collector to emitter.

The schematic symbol of an NPN transistor where B is the base, C is the collector, and E is the emitter.
Figure 15. The schematic symbol of an NPN transistor. B is the base, C is the collector, and E is the emitter.
Pinout drawing of a TIP-120 transistor. It is facing forward with the heat sink tab at the top and the bulging side of the component facing you. From left to right the legs are labelled 1. base, 2. collector, 3. emitter.
Figure 16. Pinout drawing of a TIP-120 transistor. From left to right the legs are labelled 1. base, 2. collector, 3. emitter.

Using a MOSFET instead of a TIP120

Figure 17. FQP30N06L MOSFET transistor pin diagram and schematic symbol
Figure 17. FQP30N06L MOSFET transistor pin diagram and schematic symbol

You can also use an N-channel MOSFET transistor for this. The diagram and schematic symbols are shown above in Figure 17. The IRF520 and the FQP30N06L MOSFETs are similar in function, and have the same pin configuration as the TIP120, and perform similarly. They can handle more amperage and voltage, but are more sensitive to static electricity damage.

Connect a 1-kilohm resistor from the transistor’s base to another row of the breadboard. This resistor will limit the current to the base.

You also need to add a diode in parallel with the collector and emitter of the transistor, pointing away from ground as shown in Figure 18 and Figure 19. The diode to protects the transistor from back voltage generated when the motor shuts off, or if the motor is turned in the reverse direction. This is called a snubber diode, or protection diode. Related topics: Transistors, Relays, and Controlling High-Current Loads

Schematic drawing of a transistor controlling a DC motor. At left, there is a power plug. The positive terminal of the power plug is connected to the voltage input of a 7805 voltage regulator (the terminal on the left as it faces you). The negative terminal of the power plug is connected to the ground terminal of the regulator (the terminal in the middle). A 1 kilohm resistor is connected to the regulator's output. The other side of the resistor is connected to the base pin of a TIP120 transistor. A DC motor connects to the voltage line between the DC plug and the voltage regulator. The motor's other pin is connected to the transistor's collector pin. The transistor's emitter pin is connected to ground. A diode's cathode is connected to the emitter as well, and its anode is connected to the transistor's collector.
Figure 18. Schematic drawing of a transistor controlling a DC motor.
Breadboard view of a transistor controlling a DC motor. THe breadboard is set up for power input as described above, with a DC power jack and a 7805 regulator. The left side voltage bus is unregulated, and takes its power directly from the DC power jack. The right side voltage bus takes its power from the regulator. A TIP120 transistor is connected to rows 16 to 18 in the right center section of the board. Its base is in pin 16, collector in pin 17, and emitter in pin 18. A black wire connects row 18 to the ground bus on the right. A DC motor is connected to the unregulated voltage bus on the left via a yellow wire. A green wire from the motor's other terminal connects to the transistor's collector, in row 17 in the right center section. A 1N400x diode's cathode is connected to row 18 with the emitter, and the diode's anode is connected to row 17, with the collector. A 1 kilohm resistor is connected to row 16. Its other end connects to row 12, and from there, a red wire connects to the regulated voltage bus on the right side of the board.
Figure 19. Breadboard view of a transistor controlling a DC motor.

Be sure to add the diode to your circuit correctly. The silver band on the diode denotes the cathode which is the tip of the arrow in the schematic, as shown in Figure 20:

Schematic representation and physical representation of a diode. The schematic form shows an equilateral triangle with a line bisecting the triangle equally from one point to and through the middle of the opposing flat side. There is also a line perpendicular to the other line that also intersects the triangle at its bisected point. The cathode is represented by the side of the schematic with the line. The drawing of the physical form of the diode looks like a black resistor with only a single grey stripe on one side. The side with the stripe represents the cathode
Figure 20. Schematic representation and physical representation of a diode.

This circuit assumes you’re using a 12V motor. If your motor requires a different voltage, make sure to use a power supply that’s appropriate. The TIP120 transistor can handle up to 30V across the collector and emitter, so make sure you’re not exceeding that. Connect the ground of the motor’s supply to the ground of your microcontroller circuit, though, or the circuit won’t work properly.

Add a Switch to Control the Transistor

To turn on the transistor, you need a voltage difference between the base and the emitter of at least 0.7V. Since the emitter is attached to ground, that means any voltage over 0.7V applied to the base will turn the transistor on.

  • Connect a wire from the 5-volt bus of the board (also called the regulated voltage bus) to the other end of the 1 kilohm resistor as shown above and you should see the motor turn on.

Of course, it’s inconvenient to connect and disconnect a wire like this, so use a switch instead.

  • Remove the red wire connecting the resistor to 5 volts and connect one side of a pushbutton or switch to the 5-volt bus, and the other side to the 1K resistor. Figure 21 shows the schematic drawing and Figure 22 shows the breadboard view of the circuit.
Schematic drawing of a transistor controlling a DC motor with a pushbutton. The drawing is the same as the previous schematic, but there is a switch or pushbutton symbol added between the resistor and the regulator.
Figure 21. Schematic drawing of a transistor controlling a DC motor, with a pushbutton to turn it on and off.
Breadboard drawing of a transistor controlling a DC motor with a pushbutton. The drawing is similar to the previous breadboard drawing, but a pushbutton has been added straddling the center divide in rows 12 and 10. The red wire that was in row 12 in the previous drawing has been moved to row 10.
Figure 22. Breadboard drawing of a transistor controlling a DC motor with a pushbutton.

Change the Switch for a Potentiometer

The voltage on the base of the transistor doesn’t have to be controlled by a switch. You can use a potentiometer, connected as a voltage divider, to produce a changing control voltage for the transistor’s base. Figure 23 shows the schematic drawing and Figure 24 shows the breadboard view of the circuit. Related video: Connecting the potentiometer

Schematic drawing of a transistor controlling a DC motor with a potentiometer. The drawing is similar to the previous schematic, but the pushbutton has been replaced with a potentiometer. The potentiometer's ends are connected to the regulator's output pin and ground, respectively. The wiper is connected to the resistor.
Figure 23. Schematic drawing of a transistor controlling a DC motor, with a potentiometer to change the speed.
Breadboard drawing of a transistor controlling a DC motor with a pushbutton. The drawing is similar to the previous breadboard drawing, but the pushbutton has been removed and a potentiometer is now in rows 7 through 9 in the right center section of the board. Row 7 is also connected to the right side regulated voltage bus through a red wire, and row 9 is connected to the right side ground bus through a black wire. Row 8 is connected to row 12 where it connects to the resistor.
Figure 24. Breadboard drawing of a transistor controlling a DC motor with a potentiometer.

When you turn the potentiometer, you’re producing a varying voltage on the wiper pin. That means you’re changing the voltage on the base of the transistor. Yet the motor doesn’t change its speed. It only turns on or off. When the voltage on the potentiometer’s wiper pin reaches 0.6V, the transistor will turn on. When it’s below 0.6V, the transistor will turn off. The transistor is acting like a switch, not a variable supply. If you want to vary the motor’s speed using a transistor, you need to turn the transistor on and off very fast, and change the ratio of on time to off time. This is called pulse width modulation. You’ll learn more about it in these notes on analog output from a microcontroller and see it in action in the analog lab.

Change the Potentiometer for a Voltage Divider

If you’ve understood everything so far and managed to get it to work, here’s where it gets really fun. Imaging you have a variable resistor and you want the motor to turn on when the variable resistor passes a particular threshold. For example, maybe you want to turn on the motor when a temperature changes on a thermistor (temperature sensitive resistor), or when a weight is placed on a force-sensing resistor. To make this happen, change your control circuit to include a variable resistor as shown in Figure 25 and Figure 26.

Figure 25. Schematic drawing of a transistor controlling a DC motor, with a potentiometer to change the speed.
Figure 26. Breadboard drawing of a transistor controlling a DC motor with a voltage divider.

Using a Voltage Divider to Control a Transistor

Extra credit: See if you can work out the correct resistor value for the fixed resistor of the voltage divider that will produce just the right voltage to turn the motor on when you turn on your room’s lights, and off when you turn them off.

Whoa, that blew my mind. How do I do that?

You know you need 0.7V to turn the transistor on, and less than that to turn it off. You know how to measure the resistance of a variable resistor. So find the resistance of your variable resistor with the lights on and with the lights off, and calculate what fixed resistor will give you 0.6V. The input to your voltage divider here is 5V. That means you want 4.3 volts across the variable resistor. You know that the output voltage is proportional to the ratio of the two resistors. And you know that the current running between them is the same, because they are in series. So:
Voltage = current * resistance 4.3V = current * photocell resistance
therefore,
current = 4.3V / variable resistor resistance
Then apply this to the fixed resistor:
0.7V = current * fixed resistor resistance
therefore,
fixed resistor resistance = current / 0.7V
or:
fixed resistor resistance = (4.3V / variable resistor resistance) / 0.7V

If you’re using a force sensing resistor as your variable resistor (an Interlink model 402 is shown here), you’ll probably find that they’re very sensitive. They tend to be greater than 10 megohms resistance when no force is on them and near zero when pressed. See the graph on page 3 of the datasheet for the voltage output for various fixed resistor values.

Connect a lamp instead

You could also control a lamp using a transistor. Figure 27 shows the schematic drawing and Figure 28 shows the breadboard view of the circuit. Like the motor, the lamp circuit below assumes a 12V lamp. Change your power supply accordingly if you’re using a different lamp. In the lamp circuit, the protection diode is not needed, since there’s no way for the polarity to get reversed in this circuit:

Schematic drawing of a transistor controlling an incandescent lamp with a pushbutton. The drawing is similar to the schematic with the pushbutton above, but the motor has been replaced with an incandescent lamp and the diode has been removed.
Figure 27. Schematic drawing of a transistor controlling an incandescent lamp with a pushbutton.
Breadboard drawing of a transistor controlling an incandescent lamp with a pushbutton. The drawing is similar to the breadboard drawing with the pushbutton above, but the motor has been replaced with an incandescent lamp and the diode has been removed.
Figure 28. Breadboard drawing of a transistor controlling an incandescent lamp with a pushbutton.

Conclusion

A motor controlled like this can only be turned in one direction. To be able to reverse the direction of the motor, an H-bridge circuit is required. For more on controlling DC motors with H-bridges, see the DC Motor Control lab.