Lab: Mouse Control With Pushbuttons

In this lab, you’ll build an alternative computer mouse using an Arduino Leonardo using pushbuttons to move the mouse left, right, up and down. You’ll see the difference between reading a digital input continually and reading for a change of state.

Introduction

In this lab, you’ll build an alternative computer mouse using an Arduino Leonardo using pushbuttons to move the mouse left, right, up and down. You’ll see the difference between reading a digital input continually and reading for a change of state.

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

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

A short solderless breadboard with two rows of holes along each side. There are no components mounted on the board.
Figure 1. A solderless breadboard.
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 2. Arduino Nano 33 IoT
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 3. 22AWG solid core hookup wires.
Resistors. Shown here are 220-ohm resistors. You can tell this because they have two red and one brown band, followed by a gold band.
Figure 4. Resistors. Shown here are 220-ohm resistors.  For this exercise, you’ll need 10-kilohm resistors (10K resistors are brown-black-orange. For more, see this resistor color calculator)
Photo of four breadboard-mounted pushbuttons
Figure 5. Pushbuttons.  You’ll need 5 switches for this exercise. Any switches will do the job as well.

About mouse control

NOTE: The sketches contained in this lab will cause the Arduino Leonardo to take control of your mouse. Make sure they’re working properly before you add the mouse commands. The example doesn’t introduce the mouse commands until the end of the lab. Instead, messages are printed to the serial monitor to tell you what should happen. When you’ve run this and seen the serial messages occurring when you think they should, then you can add the mouse commands safely.

The sketches here will work on an Uno until you add the mouse commands. So you can test this on an Uno simply by commenting out any line that says Mouse.begin() or Mouse.move().

Note on Mouse, Keyboard, and Serial Ports

The Mouse and Keyboard libraries on the SAMD boards (MKRZero, MKR1xxx, Nano 33IoT) have an unusual behavior: using them changes the serial port enumeration. When you include the Keyboard library in a sketch, your board’s serial port number will change. For example, on MacOS, if the port number is /dev/cu.usbmodem14101, then adding the Keyboard library will change it to /dev/cu.usbmodem14102. Removing the Keyboard library will change it back to /dev/cu.usbmodem14101. Similarly, if you double-tap the reset button to put the board in bootloader mode, the serial port will re-enumerate to its original number.

Windows and HID Devices

You may have trouble getting these sketches to work on Windows. On Windows, the default Arduino drivers must be uninstalled so the system can recognize the Arduino as both serial device and HID device. Read this issue and follow the instructions there.

Recovering From a Runaway HID (Mouse or Keyboard) Sketch

Programs which control your keyboard and mouse can make development difficult or impossible if you make a mistake in your code. If you create a mouse or keyboard example that doesn’t do what you want it to, and you need to reprogram your microcontroller to stop the program, do this:

Open a new blank sketch.

This sketch is your recovery:

1
2
3
4
5
6
void setup() {
 
}
void loop() {
 
}

Programming the board with this blank sketch removes your mistaken sketch and gives you control again. To do this, however, you need the current sketch to stop running. So:

Put the microcontroller in bootloader mode and upload the blank sketch

On the SAMD boards, you can do this by double-tapping the reset button. The on-board LED will begin glowing, and the bootloader will start so that you get a serial port enumeration, but the sketch won’t run. On the Leonardo and other 32U4-based boards, hold the reset down until you’ve given the upload command. The 32U4 bootloader will take a few seconds before it starts the sketch, so the uploader can take command and load your blank sketch.

Once you’ve got the blank sketch on the board, review the logic of your mistaken Keyboard or Mouse sketch and find the problem before uploading again.

Prepare the breadboard

Connect power and ground on the breadboard to power and ground from the microcontroller. On the Arduino module, use the 5V and any of the ground connections as shown below in Figure 6. If using the Arduino Nano connect the 3.3V and ground pins according to Figure 7.

An Arduino Leonardo on the left connected to a solderless breadboard, right. The Leonardo's 5V output hole is connected to the red column of holes on the far left side of the breadboard. The Leonardo'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 6. An Arduino Leonardo on the left connected to a solderless breadboard, right.
Arduino Nano on a breadboard.
Figure 7. Breadboard view of an Arduino Nano mounted on a breadboard.

Figure 7. Breadboard view of an Arduino Nano connected to a breadboard. 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.


Made with Fritzing

Add a pushbutton

Attach a pushbutton to digital pin 2 as shown below in Figure 9. See Figure 10 for Arduino Nano. See Figure 8 for the schematic view. Connect one side of the pushbutton to 5 volts, and the other side of the pushbutton to a 10-kilohm resistor. Connect the other end of the resistor to ground. Connect the junction where the pushbutton and the resistor meet to digital pin 2. (For more on this digital input circuit, see the Digital Input Lab).

Schematic drawing of an Arduino Leonardo connected to a pushbutton and two voltage divider inputs. The pushbutton is connected as described in the schematic above. On the left side of the board, two photoresistors are connected to +5 volts. The other sides of the photoresistors are connected to analog inputs A0 and A1, respectively. Two 10-kilohm resistors are also connected to those pins. The other sides of the fixed resistors are connected to ground.
Figure 8. Schematic view of an Arduino Leonardo connected to a pushbutton.
Breadboard drawing of an Arduino Leonardo connected to a pushbutton. The pushbutton straddles the center divide of the breadboard in rows 20 through 22. A red wire connects row 20 on the right center side to the right side voltage bus. A 10-kilohm resistor connects row 22 on the right center side to row 26 on the same side. A black wire connects from row 26 to the ground bus on the right side. A blue wire connects row 22 on the left center side of the board to digital p
Figure 9. Breadboard view of an Arduino Leonardo 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 10. Breadboard view of an Arduino Nano connected to a pushbutton.

Figure 10. 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.


Add four more pushbuttons

Repeat the last step, connecting four more pushbuttons to pins 3 through 6 as shown below in Figure 12. See Figure 11 for the schematic view. See Figure 13 for Arduino Nano.

Schematic drawing of a pushbutton and a joystick attached to an Arduino Leonardo. The pushbutton is attached to digital pin 2 on one side, and to +5 volts on the other. there is also a 10-kilohm resistor attached to digital pin 2. Its other side is attached to ground. Four other pushbuttons, with pulldown resistors like this one, are connected to pins 3 through 6 in the same way.
Figure 11. Schematic view of an Arduino Leonardo connected to five pushbutton.
Breadboard drawing of an Arduino Leonardo connected to five pushbuttons. The pushbutton from the previous breadboard drawing has been rearranged, and new buttons have been added, as follows. The pushbuttons straddle the center divide of the breadboard in rows 4-6, 9-11, 14-16, 19-21, and 24-26, respectively. 10-kilohm resistors straddle the center divide in rows 7, 12, 17, and 22, respectively. Each resistor's row on the left center side is connected to the row above it with a wire, thus connecting the pushbuttons and the resistors. Each resistor's row on the right center side is connected to the right side ground bus with a black wire. Each pushbutton's upper row (that is, rows 4, 9, 14, 19, and 23) on the right center side is connected to the right side voltage bus with a red wire. The junction rows, that is, rows 6, 11, 16, 21, and 26, are connected to digital inputs 2 through 6 on the Leonardo, respectively, with blue wires
Figure 12. Breadboard view of an Arduino Leonardo connected to five pushbuttons.

Breadboard drawing of an Arduino Nano connected to five pushbuttons. The pushbuttons straddle the center divide of the breadboard in rows 20-22, 25-27, 30-32, 35-37, and 40-42, respectively. 10-kilohm resistors connect the left side of each pushbutton to the breadboard's GND bus at rows 22, 27, 32, 37, 42. Blue wires connect the right side of each pushbutton at pins 22, 27, 32, 37, 42 to the arduino digital pins 2-6 respectively. Red wires connect the left side of each pushbutton to the voltage bus at rows 20, 25, 30, 35, 40
Figure 13. Breadboard drawing of an Arduino Nano connected to five pushbuttons.

Figure 13. Breadboard drawing of an Arduino Nano connected to five pushbuttons at digital pins 2-6 respectively.


Program the module to read the pushbutton

Follow the same steps as you did in the first Mouse Control lab to read when the pushbutton on pin 2 is pressed. Your code should only print out a message when the button changes state.

Similarly, set up a global variable to track whether or not you’re controlling the mouse, called mouseIsActive. Each time the pushbutton on pin 2 is pressed, change the state of this variable from false to true, just like you did in the first mouse control lab.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
// Global variables:
int lastButtonState = LOW;            // state of the button last time you checked
boolean mouseIsActive = false;    // whether or not the Arduino is controlling the mouse
 
void setup() {
  // initialize serial communication:
  Serial.begin(9600);
  pinMode(2, INPUT);
}
 
void loop() {
  // read the first pushbutton:
  int buttonState = digitalRead(2);
 
  // if it's changed and it's high, toggle the mouse state:
  if (buttonState != lastButtonState) {
    if (buttonState == HIGH) {
      // if mouseIsActive is true, make it false;
      // if it's false, make it true:
      mouseIsActive = !mouseIsActive;
      Serial.print("Mouse control state: ");
      Serial.println(mouseIsActive);
    }
  }
  // save button state for next comparison:
  lastButtonState = buttonState;
}

Activate the other four buttons

The other four pushbuttons are intended to control the mouse movement: the button on pin 3 should move the mouse right; the one on pin 4 should move it left; the one on pin 5 should move it down; and the one on pin 6 should move it up. If the user holds the button down, the mouse should continue to move in the corresponding direction.

To make this happen, you need to read the buttons’ states. You don’t need to tell when they change from off to on, in this case. You just need to know that they are on. But you shouldn’t do anything unless the mouseIsActive variable is true.

Add code to the setup to set pins 3 through 6 to input using the pinMode command. Then add code to the loop to read whether the mouseIsActive variable is true. If it is, read the four other pushbuttons. For each one, check if it’s high, and if so, print the letter of the direction you’re moving, U, R, L, or D.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
if (mouseIsActive) {
    // read the other buttons:
    int button2State = digitalRead(3);
    int button3State = digitalRead(4);
    int button4State = digitalRead(5);
    int button5State = digitalRead(6);
 
    if (button2State == HIGH) {
      Serial.println("R");
    }
    if (button3State == HIGH) {
       Serial.println("L");
    }
    if (button4State == HIGH) {
       Serial.println("D");
    }
    if (button5State == HIGH) {
       Serial.println("U");
    }
  }

When you run this sketch, you should see the Mouse Control State message once every time you press the first pushbutton, and the letters R, L, U, or D continuously when you hold down any of the other four pushbuttons. When you’ve got that working, you’re ready to take control of the mouse.

Add commands to control the mouse

The Mouse.begin() command is called in the setup. It initializes mouse control from your Leonardo.

The Mouse.move() command has three parameters: the horizontal movement, the vertical movement, and the scroll wheel movement. All movements are relative, so Mouse.move(1,0,0); moves one pixel to the right; Mouse.move(-1,0,0); moves one pixel to the left; Mouse.move(0,1,0); moves one pixel down; and Mouse.move(0,-1,0); moves one pixel up.

Include the Mouse library at the top of your code. Then modify the setup by adding the command Mouse.begin(). Then, in the loop where you print L, R, U, or D add Mouse.move commands to move as needed.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
#include "Mouse.h"
// Global variables:
int lastButtonState = LOW;        // state of the button last time you checked
boolean mouseIsActive = false;    // whether or not the Arduino is controlling the mouse
 
void setup() {
  // initialize mouse control:
  Mouse.begin();
  // initialize serial communication:
  Serial.begin(9600);
  // make pin 2 through 6 inputs:
  pinMode(2, INPUT);
  pinMode(3, INPUT);
  pinMode(4, INPUT);
  pinMode(5, INPUT);
  pinMode(6, INPUT);
}
 
void loop() {
  // read the first pushbutton:
  int buttonState = digitalRead(2);
 
  // if it's changed and it's high, toggle the mouse state:
  if (buttonState != lastButtonState) {
    if (buttonState == HIGH) {
      // if mouseIsActive is true, make it false;
      // if it's false, make it true:
      mouseIsActive = !mouseIsActive;
    }
  }
  // save button state for next comparison:
  lastButtonState = buttonState;
 
  // if the mouse is active, and any button is pressed,
  // move the mouse in the corresponding direction:
  if(mouseIsActive) {
    // read the other buttons:
    int button2State = digitalRead(3);
    int button3State = digitalRead(4);
    int button4State = digitalRead(5);
    int button5State = digitalRead(6);
 
    if (button2State == HIGH) {
      Serial.println("R");
      Mouse.move(2, 0, 0);      // move right
    }
    if (button3State == HIGH) {
      Serial.println("L");
      Mouse.move(-2, 0, 0);     // move left
    }
    if (button4State == HIGH) {
      Serial.println("D");
      Mouse.move(0, 2, 0);      // move down
    }
    if (button5State == HIGH) {
      Serial.println("U");
      Mouse.move(0, -2, 0);      // move up
    }
  }
}

That’s the whole sketch. When you run this, press the button to enable or disable mouse control, then press any of the other four buttons, and the mouse will move in the appropriate direction.

The full sketch for this can be found on the phys comp github repository, called MouseMoveSimpleButtons.

You can see from this sketch the difference between reading a digital input to look for the state change (the button on pin 2) and reading a digital input just to see the current state (buttons on pins 3 through 6). When you’re designing a response that can repeat infinitely, you can just read the current state. But when you’re designing a response that should happen just once, you need to determine when the button changes state.

Next, try the Mouse Control With Joystick lab.

Sensors: the Basics

Introduction

Sensors convert various forms of physical energy into electrical energy, allowing microcontrollers to read changes in the physical world.

The simplest sensors read changes in mechanical energy, usually by moving electrical contacts. For example the pushbutton or switch (related video) converts mechanical energy (e.g, your finger’s press) into electrical energy by closing a connection between two metal contacts. The potentiometer (related video) shown in Figure 1 and Figure 2 is another sensor that reads mechanical energy changes: a metal contact called a wiper slides along a resistor, effectively short circuiting the resistor (related video) into two halves and creating a voltage divider circuit.

Photo showing the inside of a potentiometer
Figure 1. A potentiometer broken open, showing the carbon substrate and wiper.
Drawing of the inside of a potentiometer. The wiper and carbon resistor are shown, and a symbol of a variable resistor is shown at the bottom of the drawing.
Figure 2. Inside a potentiometer, the wiper, attached to the center contact, slides along the carbon resistor, forming effectively two resistors in series.

Although switches and pushbuttons typically only read an on state or an off state, most other sensors can read a wide range of possible states. In other words, they’re analog sensors, because they read a variable change. Whenever you use a new sensor, the first thing you need to understand is what the range is that it can read and deliver. When you’re using your sensor in an application, you need to know the range of possible values your application requires. Do you just need high, medium, and low (3 possible values), or a range from 0 to 10? Do you need a 100-point range? The range that you need depends on what your user can perceive. For example, if you’re making a lighting dimmer, and your user can only perceive about a dozen different light levels, then you don’t need to give her a sensor that can give her a 1000-point range of control.

Resistive Sensors

Related Video: Sensors – Survey 1

Resistive sensors. Stretch sensor, top; flex sensor, middle; force-sensing resistor, bottom
Figure 3. Resistive sensors. Stretch sensor, top; flex sensor, middle and bottom; force-sensing resistor, bottom

Many sensors work by converting the energy they read into a changing electrical resistance by using a variably resistive material at their heart. Examples of resistive sensors are shown in Figure 3. For example, force sensors and stretch sensors are made of a partially conductive rubber. When the rubber is stretched or compressed, the resistance change. Photoresistors or light dependent resistors change their resistance when exposed to a change in light energy. In order to read changes in resistance, you typically place these sensors in a voltage divider circuit , which converts the resistance change into a changing voltage.

Optical Sensors

Related video: Light Sensors

Light is used in many sensors in a variety of ways. Light-emitting diodes, light-dependent resistors, and phototransistors  can be combined to sense dust, measure distance, or determine reflected color.  Light is also used in some ranging sensors to determine distance from a sensor to a target.

Ranging Sensors

Related video: Ranging Sensors

Ranging sensors: ultrasonic ranger, top; infrared ranger, bottom.
Figure 4. Ranging sensors: ultrasonic ranger, top; infrared ranger, bottom.

Many sensors measure movement or distance indirectly, by sending out a pulse of light or sound and reading the reflected signal when it bounces off a target as illustrated in Figure 5. These are called ranging sensors (Figure 4) because they read a range of distance.

Drawing of a ranging sensor, showing energy waves radiating out, then bouncing off a human figure back to the sensor.
Figure 5. Ranging sensors work by bouncing energy off the target and reading the reflection.

MEMS Sensors

Related video: MEMS Sensors

Still other sensors work by converting the energy they read into a change in capacitance. For example, accelerometers and other miniaturized electromechanical (MEMS) sensors typically have a tiny moving conductive mass at their core, suspended on tiny springs and surrounded on both sides by electrical contacts. Because the conductive mass is parallel to the outer contacts, a capacitance builds up between the contact. When the mass is moved, the capacitance changes between the two sides, effectively creating two variable capacitors as illustrated in Figure 6. That variable capacitor is then placed in a resistor-capacitor circuit to convert the change in capacitance into a changing voltage.

Diagram of a MEMS sensor, showing a moving mass that moves a capacitive plate in between two other capacitive surfaces.
Figure 6. MEMS sensors often form a variable capacitor by moving a capacitive plate in between two other capacitive surfaces.

Digital Interface Sensors

Related video: Sensors – Interfacing

Other than switches and variable resistors, most sensors you buy are integrated circuits that include the resistance-to-voltage or capacitance-to-voltage circuit and provide you with an analog voltage output. Some will even include an analog-to-digital converter and provide you with a serial data interface, either I2C, SPI, or asynchronous serial, so that you can connect the sensor to the serial ports of your microcontroller. Still others will provide a changing pulse output, or pulse width modulation (PWM) output, where the width of the pulse represents the sensor value.

Photo of sensors with digital interfaces
Figure 7. A collection of sensors with digital interfaces. Clockwise, from top: AS7341 spectrometer; LIS3DH accelerometer; VL53L0X Time-of-flight distance sensor; Max3010x particle detector. These sensors are on small breakout boards which can connect to a solderless breadboard. They all connect to a microcontroller using SPI or I2C.

Data Sheets

Related Video: Datasheets

When you shop for sensors, you need to look at the data sheet to learn how they operate. The data sheet will usually include the following essential facts:

  • a text description of the sensor and its operation;
  • a pin diagram to tell you what pins perform what functions;
  • a table of electrical characteristics that tells you what the supply voltage is, what the operating current is, and what the output is, along with other electrical and physical properties;
  • a graph or conversion formula that relates the input energy to the output energy;
  • a mechanical description of the sensor itself.

Some datasheets will include other information as well, such as application circuits, reliability data, and so forth.

You should follow the datasheet’s guideline for sensor operation. Don’t exceed the maximum or minimum operating voltage, and make sure to supply adequate current to operate the sensor. Avoid supplying too much current, because the excess current will get turned into heat, which often changes the sensor’s operating characteristics. Make sure you understand the sensor’s interface. Be clear on whether it’s an analog electrical property like resistance, capacitance or voltage, or a digital serial data interface. Look for typical application circuits and microcontroller code samples online if you can find them.

Using a Sensor With a Microcontroller

Related video: Sensors – Testing

Once you understand how a sensor works and what its output will be, you should connect it to your microcontroller and write a simple program to read the output. Don’t jump right into writing a complex program. Write the smallest program necessary to read the sensor’s changing values and output them for debugging purposes. Then put the sensor in the physical context in which you plan to use it and read the output values in action. The range that a sensor can read will change depending on the specific conditions or actions that you plan to read. So make sure the physical setting of the sensor is as close to reality as possible in order to test it. Once you know the range of values that it’s going to output in those conditions, then you can write a function to convert the sensor’s raw output range into a range you can use. Depending on the context, you probably won’t get the full output range that the sensor is capable of delivering. So your conversion function should be based on the range you’re actually seeing, not the total range.

You probably don’t need to convert the sensor’s readings into its output voltage or its physical property. For example, if you’re using a force sensing resistor, you probably don’t need to know how many Newtons of force are being exerted on the sensor, or what the output voltage is. Instead, you probably just need to know whether someone is pressing gently, firmly, or really firmly against the sensor. Perhaps you just need a range from 0 to 10. When you write your conversion function, consider what the relevant result is for you, and write a function that delivers that result.

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.

Controlling Stepper Motors

Introduction

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

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

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

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

Bipolar stepper motors

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

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

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

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

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

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

Unipolar Stepper Motors

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

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

Common Stepper Motor Types

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

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

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

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

Control of Stepper Motors

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

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

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

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

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

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

H-bridge Stepper Drivers

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

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

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

Step & Direction Stepper Drivers

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

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

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

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

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

Videos: Schematic Diagrams

ITP Videos by Jeff Feddersen on Vimeo.

Schematic Diagrams

A schematic diagram is a representation of an electrical circuit, showing the electrical relationships using abstract graphic symbols rather than realistic pictures of components.

There are some components that schematics commonly include: voltage, ground, resistors, diodes, light emitting diodes (LED), switches, relays, capacitors.

A transistor includes three connections: a base, a collector and a emitter. It can work as an amplifier and a switch.

In schematics, to show a junction point, draw a dot at crossing.

Review on schematics components mentioned above.

Videos: Digital and Analog Input and Output

ITP Videos by Jeff Feddersen on Vimeo.

Digital Input and Output

The Fixed Resistor is Necessary!

Ohm Part 2 from ITP_NYU on Vimeo.

Digital input with internal pull-up resistors

Analog Input

Analog Output

Pseudo-analog output:

Tone Output

Servo Control using Pulse Width Modulation

Analog Output: Motor Control

Multiple Inputs or Outputs

Multiplexers

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

Shift Registers

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

Binary Coded Decimal (BCD) controller

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

Electricity: the Basics

Introduction

Adapted from Understanding Electricity
In order to understand how electronic circuits work, and how to use them to build physical interfaces to digital systems using microcontrollers, there are some basic terms, relationships, and components that you need to know about. What follows is a brief introduction to those terms.

You won’t need to know anything about electricity or electronics to understand this page.

Definitions

Electricity is the flow of electrical energy through conductive materials.  An electrical circuit is made up of two elements: a power source and components that convert the electrical energy into other forms of energy.  We build electrical circuits to do work, or to sense activity in the physical world.

Sensors are components that convert other forms of energy into electrical energy so we can read the changes in those other forms. Switches, knobs, light and motion sensors all fit in this category.  Actuators are components that convert electrical energy into other forms. Light bulbs, motors, LEDs, and heaters are all actuators.

Electronics refers to reading changes in electrical properties as information.  For example, a microphone changes sound pressure waves in the air to a changing electrical voltage. This process of changing one energy into another is called transduction, and devices that do it are called transducers. Much of the technical work of physical computing is about figuring out what forms of energy a person is generating, and what kind of transducer you can buy or build to read that energy. In order to do that, though, it’s necessary to understand a few things about electricity. Following are a few terms we’ll use to refer to electrical properties and components. After that, we’ll talk about the important relationships between some of these terms.

Voltage is a measure of the difference in electrical potential energy between two points in a circuit. It is measured in Volts.

Current is a measure of the magnitude of the flow of electrons through a particular point in a circuit. It is measured in Amperes, or Amps.

Resistance is a measure of a material’s ability to oppose the flow of electricity. It is measured in Ohms.

To understand the relationship between voltage, current, and resistance, imagine an avalanche of snow on a mountain. The height of the mountain is analogous to the voltage; the higher the mountain, the more potential energy the falling material has.  The amount of snow and rocks in the avalanche is analogous to the current.  And the steepness of the mountain is analogous to the resistance: the steeper the mountain, the less it will resist the flow of the snow and rocks. We’ll define this a bit more formally below.

Every circuit has to have a source of electrical energy and a load that uses the energy.All of the electrical energy in a circuit has to get used by the load. The load will convert the electrical energy to some other form of energy, A circuit with no load  is called a short circuit. In a short circuit, the power source feeds all of its power through the wires and back to itself, and either the wires melt (if you’re lucky), or the battery and the components blow up.

Figure 1 is a very basic circuit, consisting of a lamp, a pushbutton, and a battery. The battery is the source and the lamp is the load. The electrical energy coming from the battery is converted to heat and light energy by the light bulb. All of the energy is used up in the process. However, if the bulb cannot take the voltage produced by the battery (for example, a 6V lamp and a 9V battery), the lamp’s filament will melt trying to transduce all the electrical energy into light and heat.

One AA Battery connected to a button switch and lamp in series
Figure 1. AA Battery connected to a button switch and lamp in series

There are two common kinds of circuits:  Direct Current (DC), and Alternating Current (AC). In a DC circuit, current always flows one direction. In an AC circuit, the direction of current flow is reversed in a regular repeating cycle.  Most of the circuits we’ll talk about in this class will be DC circuits.

Schematic diagrams are diagrams of circuits that represent the electrical relationships between the components in the circuit. A schematic doesn’t  always show the spatial arrangement of the components; it’s arranged so that you can best understand the flow of the electricity. You can find a large collections of schematic symbols in SVG format, useful for drawing your own, on the Wikipedia page for “Electronic Symbol”. An SVG collection of them in one file, convenient for editing into your own diagrams, can be found on this Wikimedia commons page. The symbols for the components you’ll use most commonly in this class are shown below as well.

Figure 2 show two schematics of the light bulb circuit above. In both, the important parts to note are the functional components, namely the lamp and the switch, and the power and ground terminals. In the diagram on the right, the whole circuit is shown as a loop, with the battery (marked V1) to the left of the loop. In the diagram on the left, the circuit is not shown as a loop. Instead, the power source is at the top, and the point of lowest energy, or ground, is at the bottom.  This diagram shows the flow of energy from the top of the diagram to the bottom. Related Video: Intro to Schematics

Schematic of a 1.5 volt battery connected to a switch and lamp in series. In the diagram on the right, the whole circuit is shown as a loop, with the battery (marked V1) to the left of the loop. In the diagram on the left, the circuit is not shown as a loop. Instead, the power source is at the top, and the point of lowest energy, or ground, is at the bottom.
Figure 2. Two schematics of a 1.5 volt battery connected to a switch and lamp in series.

Components

Conductors are materials through which electrical current moves freely.

Insulators are materials which prevent the flow of electricity.

Resistors resist, but do not totally block, the flow of electricity. They are used to control the flow of current. Current can move either way through a resistor, so it doesn’t matter which way they’re connected in a circuit. Resistors are measured by their resistance in ohms (Ω), often seen in kilohms (kΩ). They are symbolized as shown in Figure 3:

Four resistor types, from left to right: Fixed Value Resistor, Variable Resistor, Potentiometer, Photo-resistor or light dependent resistor
Figure 3. Four resistor types, from left to right: Fixed Value Resistor, Variable Resistor, Potentiometer, Photo-resistor or light dependent resistor.

Related videos: Resistors, variable resistors, and photocells; Potentiometer

There are many different types of variable resistors, including:

  • Thermistors change resistance in reaction to varying temperature;
  • Photoresistors change resistance in reaction to varying light;
  • Flex sensors change resistance in reaction to being bent or flexed;
  • Force sensing resistors change resistance in reaction to a force placed upon them;

Capacitors store up electricity while current is flowing into them, then release the energy when the incoming current is removed. Capacitors are measured by their capacitance in farads (F), most commonly seen in microfarads (µF). Sometimes they are polarized, meaning current can only flow through them in a specific direction, and sometimes they are not. If a capacitor is polarized, it will be marked as such on the diagram. Don’t wire a polarized capacitor backwards; this can damage the capacitor, and your circuit. Capacitors are also rated by their maximum voltage. Don’t apply more voltage to a capacitor than it’s rated for, or it will explode.

Capacitors are symbolized as shown in Figure 4:

Schematic symbols of a polarized capacitor and a non-polarized capacitor. Polarized shows a + symbol near the anode and the cathode is connected to a curved line. The non polarized capacitor symbol contains only straight lines and is symmetric
Figure 4. Schematic symbols of a polarized capacitor and a non-polarized capacitor

Related video: Capacitors

Diodes permit the flow of electricity in one direction, and block it in the other direction. Because of this, they can only be placed in a circuit in one direction. Light-Emitting Diodes (LED’s) are special types of diodes which emit light when current flows through them.  Diodes are symbolized as shown in Figure 5:

Schematic symbols of a diode and a light-emitting diode. The light-emitting diode looks like the diode symbol with 2 arrows pointing away from the center of the symbol.
Figure 5. Schematic symbols of a diode and a light-emitting diode (LED)

Related video: Diodes and LEDs

Switches and pushbuttons control the flow of current through a junction in a circuit, as shown in Figure 6:

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 6. Schematic drawing of a switch and a pushbutton

Related video: Switches

Transistors and relays are electrical switching devices, as shown in Figure 7:

Schematic symbols for an NPN transistor, a PNP Transistor, and a Relay
Figure 7. Schematic symbols for an NPN transistor, a PNP Transistor, and a Relay

Related video: Relays

Piezoelectric devices create a varying voltage in reaction to slight changes in pressure.

Relationships

Voltage (V), Current (I), and Resistance (R) are all related, by the following formula, as shown in figure 8:

Volts = Amps x Ohms

or

V = I x R

Three equations using ohms law to calculate Voltage, Amperage, or Resistance. A circle is divided into 3 sections, each section containing one element of Ohms law, V for voltage, I for Amperage, R for resistance. Each equation is adjacent to the corresponding section of the circle
Figure 8. Three equations using ohms law to calculate Voltage, Amperage, or Resistance

Related video: Ohm’s Law Part 1 & Part 2. See also Measuring Voltage and Current.

Current (I), voltage (V), and resistance (R) are also related to electrical power (P) (measured in watts), as follows:

Watts = Volts * Amps

or

P = V * I

Electrical current flows from places of higher potential energy to places of lower potential energy (i.e. from positive to negative), as shown in Figure 9. In order for current to flow, there has to be a circuit, and there has to be a load to convert the electrical energy into some other form of energy.

Simple circuit showing the direction of current flowing from the + V terminal to ground
Figure 9. Simple circuit showing the direction of current flowing from the + V terminal to ground

Ground is the place in a circuit with where the potential energy of the electrons is zero. Sometimes this point is connected to the actual ground, either through a grounded electrical circuit, water pipe, or some other method. Basically, any conductor that goes to the earth will do.

Electrical Energy Flow in a Circuit

When you start to add multiple components to a circuit, following the electrical energy can get a bit more complex.  Following are some principles that explain how energy flows in a circuit.

Electrical components can be arranged in a circuit so that the energy flows through one to the other, or they can be arranged so that the energy is split, flowing through both at the same time. When the energy flows from one to the other, the components are in series (Figure 10). When it flows through them at the same time, they are in parallel (Figure 11).

Two lightbulbs in series
Figure 10. Two lightbulbs in series
Two lightbulbs wired in parallel
Figure 11. Two lightbulbs wired in parallel

There are a few rules that explain how electrical energy moves through these circuits:

Current tends to follow the path of least resistance to the ground. So if it has a choice of two paths in a circuit, and one has less resistance, that’s the path it’ll take. Looking at the parallel circuit above, if one light bulb offered less resistance, then more of the current wold pass through that bulb.

In any given circuit, the total voltage around the path of the circuit is zero. Each component that offers a resistance lowers the voltage, and by the time you reach the end of the circuit loop, there will be no voltage left. In other words, all energy generated by the electrical power source in a circuit is converted to some other form of energy.  Looking at the light bulbs in series above, if you were to measure the voltage on between the two contacts of each bulb, it would be less than the voltage between the contacts of the battery, but when you add up the voltages for all the bulbs, the sum would equal the voltage of the battery.

This explains why some components in a circuit get warm when you don’t expect them to. They are offering resistance to the energy in the circuit, and if they are not efficient at converting that energy into their desired form of energy, they convert it to heat.

The amount of current going into any point in a circuit is the same as the amount coming out of that point.

Let’s look in more detail at how the current and voltage changes when components are in series or in parallel:

When two components are in series, they are placed one after another, as shown in Figure 12:

Two resistors wired in series with a junction in between the resistors
Figure 12. Two resistors wired in series.

When resistors are in series, the voltage drops across each resistor, and the total resistance is equal to the sum of all the resistors:

Resistors in series:

Rtotal = R1 + R2 + R3

In the above circuit, the current through both of the resistors is the same and the voltage drops across each resistor, and the total of all the voltage drops equals the voltage across the battery. The voltage between the junction point and the negative terminal of the battery (which is the ground of this circuit)  is dependent on the ratio of the two resistors in series. If the resistors are equal in resistance value, then the voltage at the junction point is exactly half that of the battery’s total voltage.

When two components are in parallel, they are placed beside each other, as shown in Figure 13:

Two resistors wired in parallel
Figure 13. Two resistors wired in parallel

For resistors in parallel, the voltage across them is equal, but the current is divided between them. The divided current across the parallel resistors is equal to the total current. So I1 + I2 = Itotal. That means that

1/Rtotal = 1/R1 + 1/R2 + 1/R3

If the resistors are equal in resistance value, then the current flowing through each of them is half that of the total current.

Though it’s sometimes useful to think about the mathematical relationships of parallel and series circuits, it’s often more useful to think about them in terms of practical effects: resistors divide voltage when in series, and divide amperage when in parallel.

When you’re ready to begin building circuits, read the Breadboard Setup Lab for a quick introduction to how to use a solderless breadboard. The Components Lab introduces many of the components you will use and the Electronics lab introduces you to how to measure electrical properties. You should also read the the switches lab, and watch this video about connections in schematics.

Digital Input & Output

Introduction

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

These videos will help in understanding digital inputs and outputs:

Digital Inputs

When you’re trying to sense activity in the physical world using a microcontroller, the simplest activities you can sense are those in which you only need to know one thing about the physical world: Whether something is true or false. Is the viewer in the room or out? Are they touching the table or not? Is the door open or closed? In these cases, you can determine what you need to know using a digital input, or switch.

Digital or binary inputs to microcontrollers have two states: off and on. If voltage is flowing, the circuit is on. If it’s not flowing, the circuit is off. To make a digital circuit, you need a circuit, and a movable conductor which can either complete the circuit, or not.

Schematic of a Digital Input to a microcontroller
Figure 1. Schematic of a Digital Input to a microcontroller

Figure 1 shows the electrical schematic for a digital input to a microcontroller. The current has two directions it can go to ground: through the resistor or through the microcontroller. When the switch is closed, the current will follow the path of least resistance, to the microcontroller pin, and the microcontroller can then read the voltage. The microcontroller pin will then read as high voltage or HIGH. When the switch is open, the resistor connects the digital input to ground, so that it reads as zero voltage, or LOW.

On an Arduino module, you declare the pin to be an input at the top of your program. Then you read it for the values 1 (HIGH) or 0 (LOW), like so:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
void setup() {
 // declare pin 2 to be an input:
 pinMode(2, INPUT);
 declare pin 3 to be an output:
 pinMode(3, OUTPUT);
}
 
void loop() {
 // read pin 2:
 if (digitalRead(2) == 1) {
   // if pin 2 is HIGH, set pin 3 HIGH:
   digitalWrite(3, HIGH);
 } else {
   // if pin 2 is LOW, set pin 3 LOW:
   digitalWrite(3, LOW);
}

Digital output

Just as digital inputs allow you to sense activities which have two states, digital or binary outputs allow you to control activities which can have two states. With a digital output you can either turn something off or on. Figure 2 is the schematic diagram for digital output controlling an LED:

Schematic of and led as a digital output from a microcontroller
Figure 2. Schematic of and led as a digital output from a microcontroller

Digital outputs are often used to control other electrical devices besides LEDs,  through transistors or relays. For more information on that, see these notes on controlling high-current circuits.

On an Arduino module, you declare the pin an output at the top of the program just like you did with inputs. Then in the body of the program you use the digitalWrite() command with the values HIGH and LOW to set the pin high or low, as you’ve seen above.
Here’s a simple blinking LED program in Arduino:

1
2
3
4
5
6
7
8
9
10
void setup() {
  pinMode(13, OUTPUT);
}
 
void loop() {
  digitalWrite(13, HIGH);
  delay(1000);
  digitalWrite(13, LOW);
  delay(1000);
}

As inputs, the pins of a microcontroller can accept very little current. Likewise, as outputs, they produce very little current. The electrical signals that they read and write are mainly changes in voltage, not current. When you want to read an electrical change that’s high-current, you limit the current input using a resistor. Similarly, when you want to control a high-current circuit, you use a transistor or relay, both of which allow you to control a circuit with only small voltage changes and minimal current. Related video: Transistor

Lab: Components

In this lab you will learn about some of the components you’ll use frequently when making electronic circuits.

Introduction

In this lab you will learn about some of the components you’ll use frequently when making electronic circuits. For more on any given component, please check out its datasheet. There are no specific activities in this lab other than to examine the components and to familiarize yourself with them.

Video: Schematics 5

A datasheet or spec sheet is a document (printed or .pdf) that describes the technical characteristics of a sensor, electronic component, product, material or other. It includes details on how to use the component in a circuit and other useful design info on how to integrate it into a system together with specifications on performance and other characteristics that are important to know.

Components

Video: Datasheets

Voltage Regulator

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 1. 5-volt voltage regulator, model 7805

Related Video: Voltage Regulator
Related Video: Using a voltage regulator on a breadboard

Different electronic circuits operate at different voltages. For example, the Arduino Uno operates at 5 volts, while the Arduino Nano 33 IoT and BLE, and the MKR series, operate at 3.3 volts. A voltage regulator takes a range of DC voltage as input and convert it to a constant voltage. For example, this regulator shown in Figure 1, a 7805 regulator, takes a range of 9 – 15 volts DC input and converts it to a constant 5-volt output. Using this regulator, you could power a 5-volt motor or a string of addressable LEDs from a 12-volt power source.

Note the label on the regulator that reads “7805”. This is the part number. Other parts have the same physical form factor, however. The form factor, called the package, is not dependent on what the actual part is. This  is a TO-220 package. Many different parts use this same package, for example, and not all of them are voltage regulators. Also, sometimes the same part will come in different packages, so you can use it in different size devices.

Related Video: Read the labels to differentiate similar packages

The 7800 series regulators come in many different voltages. 7805 is a 5-volt regulator. 7809 is a 9-volt regulator. 7812 is a 12-volt regulator. All the regulators of this family have the same pin connections. In the image above, the left leg is connected to the input voltage. The middle leg is connected to ground. The right leg is the output voltage.

Link to 7805 datasheet

3.3-volt regulator, model LD111733V. 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, ground, voltage output, and voltage input. The back tab is attached to the voltage output pin.
Figure 2. 3.3V voltage regulator

3.3V regulators are also common. Note that not all regulators which share the same package have the same pin configuration. For example, the LD1117V33, a 3.3V regulator shown in Figure 2, comes in the same physical package as a 7805, but its pins are in a different order. The LD1117V33’s pins, from left to right, are ground, output voltage, input voltage.

LED

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 3. 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.

Related Video: Diodes and LEDs

LEDs, or Light Emitting Diodes (see Figure 3), are diodes that emit light when given the correct voltage and current. Like all diodes, they are polarized, meaning that they only operate when oriented correctly in the circuit. The anode of the LED connects to voltage, and the cathode connects to ground. The anode in the LEDs in this photo is the longer leg on each LED. LEDs come in many different packages. The packages above have built-in lenses.

Related Video: How to connect an LED and resistor

These LEDs are the cheapest you can buy, and they’re not very bright. You can get super-bright LEDs as well, which are much brighter. If you’re working on applications that need very small light sources, you can also get LEDs in a surface mount package.

LEDs can only handle a limited amount of current and voltage. The details should be covered in each LED’s datasheet. Here is the datasheet of a typical white LED. You’ll see that the forward current is 30 mA max, and the forward voltage is between 2.9 and 3.6V. That means if you give it 30mA at 3.6V, you should get maximum brightness out of it. If you don’t have the datasheet for your LED, here’s a link to a handy LED current calculator. Try putting in the supply voltage (3.3V or 5V), the voltage drop across the LED (the forward voltage), and the current (30 mA) and see what value of resistance you get. For most common LEDs running at 3.3 or 5 volts, a resistor about 220 will limit the current safely while still providing enough to light the LED.

Solderless Breadboard

A short solderless breadboard with two rows of holes along each side. There are no components mounted on the board. The board is oriented sideways so that the long rows of holes are on the top and bottom of the image.
Figure 4. A short solderless breadboard.

Related Video: Introduction to breadboards

Solderless breadboards are reusable prototyping tools for electronics that allow you to build and experiment with circuits simply by plugging components in and out of its rows and columns. They come in different shape and sizes. Figure 4 shows a typical short solderless breadboard. It has two rows of holes on either side of the board, usually used as voltage and ground buses. The board is turned in this photo so that the bus rows are on top and bottom. In the center of the board, there are thirty rows of holes. There is a divider down the center of the board that breaks up the rows of holes into separate rows. There are five holes per row on the center left and on the center right of each row.

Resistors

Resistors. Shown here are 220-ohm resistors. You can tell this because they have two red and one brown band, followed by a gold band.
Figure 5. Resistors. Shown here are 220-ohm resistors. You can tell this because they have two red and one brown band, followed by a gold band.

Related Video: Resistors, variable resistors, and photocells

Resistors resist the flow of electrical current. When placed in series, they reduce the voltage, and limit the current. The bands on a resistor indicate the resistor’s value. Here’s a handy resistor color code calculator. Resistors come in 4-band, 5-band, and 6-band models. In a 4-band resistor, the bands represent the first digit, second digit, multiplier, and tolerance. The resistors shown in Figure 5 are 4-band resistors marked red, red, brown, and gold, for 2, 2, times 101, 5%. In other words, these are 220 ohm resistors, +/-5%.  The resistor color code calculator explains the bands for 5-and 6-band resistors as well.

Potentiometers

Potentiometer. The one shown here has three legs spaced 0.1 inches apart and can be therefore mounted on a solderless breadboard.
Figure 6. Potentiometer. The one shown here has three legs spaced 0.1 inches apart and can be therefore mounted on a solderless breadboard.

Related Video: Potentiometer

Potentiometers are variable resistors. The two outside terminals act as a fixed resistor. A movable contact called the wiper moves across the resistor, producing a variable resistance between the center terminal and either of the two sides. The potentiometer in Figure 6 has pins so you can mount it on a breadboard.

Related Video: Measure a potentiometer’s variable resistance
Related Video: Potentiometer schematic

Trimmer potentiometers. These are small potentiometers, square, approximately half an inch (1cm) square. They have three legs spaced 0.1 inches (2.54cm) apart and can be therefore mounted on a solderless breadboard.
Figure 7. Trimmer potentiometers

Trimmer potentiometers like those shown in Figure 7 are designed to be mounted on a circuit board, and are difficult to turn, so you can use them to adjust a circuit. They’re very small. They’re handy to use as physical variables, to tune your project.

Force Sensing Resistors

Force sensing resistors are sensors that change their resistance in response to force. They’re usually used to make analog alternatives alternatives to buttons. They’re made of a substrate of resistive rubber between two layers of conductive ink on a plastic film. They come in a variety of form factors. Figure 8 shows a pair of force sensors about 2.5cm across, sized for finger presses. There are a few companies who make them, including Interlink, Ohmite, and Tekscan.

A pair of force sensing resistors
Figure 8. Force sensing resistors

Flex Sensors (Flex Resistors)

Flex sensors are similar to force sensing resistors in construction, but they change their resistance as they bend. They are typically about the length of a finger, and they work well for measuring the bend of a finger. Spectrasymbol make these.

Photo of a flex sensor. A plastic strip approx. 0.25 inches wide by 6 inches long, with pins at one end. When you bend the sensor, the resistance between the pins changes
Figure 9. Flex sensor

Force Sensing Potentiometers

Force Sensing Potentiometers, sometimes called SoftPots, are also similar to force sensing resistors. The difference is that a force sensing resistor gives one value wherever you press on it, while a force sensing potentiometer acts like a normal potentiometer: the value changes depending on where along its length you press. They come in linear and round form factors. Ohmite, Interlink, and Spectrasymbol make FSPs.

Figure 10. Force Sensing Potentiometer

Light-Dependent Resistors (Photocells)

Photocell, or light-dependent resistor. This component has a round top and two wire legs. You measure the resistance between the two legs and expose the top to a varying light source in order to vary the resistance between the two legs.
Figure 11. Photocell, or light-dependent resistor

Related Video: Wiring a photocell to measure light

Light-dependent resistors, or photocells, are variable resistors whose resistance changes with the intensity of the light falling on the resistor. Photocells, as seen in Figure 11, are made with cadmium sulfide, which is a toxic chemical. Increasingly, they are being replaced in hobbyist kits by phototransistors, which are somewhat less toxic (see below).

Thermistors

Thermistor, or temperature-dependent resistor. This component has a bulbous top and two wire legs. You measure the resistance between the two legs and expose the top to a varying temperature in order to vary the resistance between the two legs.
Figure 12. Themistor, or temperature-sensitive resistor

Thermistors, seen in Figure 12, are variable resistors whose resistance changes as the temperature changes. You measure the resistance between the two legs of the thermistor and expose the top to a varying temperature in order to vary the resistance between the two legs.

Switches

Pushbuttons. These ones are designed to be mounted on a solderless breadboard. They have four legs spaced 0.2 inches apart on both sides of the component.
Figure 13. Pushbuttons, also called momentary switches

Related Video: Switches
Related Video: Connect a switch to a digital pin

Switches are one form of digital input. There are many kinds of switches. The two most useful categories are momentary switches, which remain closed only when you press them, and toggle switches, which stay in place after you switch them.

Pushbuttons are a common type of momentary switch. The pushbuttons in the photo in Figure 13 above are designed to be mounted on a circuit board. They are very small, less than 1 centimeter on a side. They have four pins. When the button is facing you,  top two are connected to each other, and the bottom two are connected to each other. Pushing the button connects the top pins to the bottom pins.

Toggle switches (Figure 14) stay in one position when you flip them. Wall light switches are common examples of toggle switches. Unlike a momentary switch, a toggle switch can be used to turn a device on or off, because they stay in one state when you remove your hand. The toggle switches below each have three connectors, also called pins or legs. They’re usually labeled C for common, NO for Normally Open, and NC for Normally Closed. When you switch the switch, it will open the connection between the common pin and the normally closed pin, and close the connection between the common pin and the normally open pin. Switch it the other way, and you will reverse the connection.

Toggle switches. These switches are approximately half an inch (1cm) long, and have a switch on top that moves from one side to the other. They typically have two or three legs.
Figure 14. Toggle switches

Rotary Encoder

Photo of a rotary encoder
Figure 15. Rotary encoder

A rotary encoder is a sensor that usually looks a bit like a potentiometer. It has a central shaft that you can turn with your fingers, or with an axle. It produces a pair of electrical pulses as you turn the shaft of the encoder, one slightly before or after the other, depending on the direction you are turning the shaft. Unlike a potentiometer, they can turn endlessly. They are used both as tangible controls, when you want a knob that turns endlessly, and as rotary sensors for motors and axles. The encoder in Figure 15 has three pins. The center is connected to ground, and the two side pins produce the pulses. The Encoder library for Arduino is useful for reading these.

Capacitors

Ceramic capacitor. This component has a disc top and two wire legs. You measure the capacitance between the two legs. Ceramic disc capacitors like this are generally low-capacitance components.
Figure 16. Ceramic disc capacitors

Related Video: Capacitors

Capacitors store electrical energy while there’s energy coming in, and release it when the incoming energy stops. They have a variety of uses. One common use is to smooth out the dips and spikes in an electrical supply. This use is called decoupling.

Related Video: Clean a noisy signal with a Capacitor

Ceramic capacitors are unpolarized. They generally have very small capacitance values. They’re useful decoupling caps in a low-current circuit. You often see them used to decouple the power going into a microcontroller or other integrated circuit.

The number on a ceramic cap gives you its value and order of magnitude. For example, 104 on the capactors in Figure 16 indicates a 0.1 microfarad (uF) cap. 103 indicates a 0.01 microfarad cap.

Electrolytic capacitor. This component has a tubular top and two wire legs coming out of one end of the tube. They are generally polarized. The longer leg is the positive leg. You measure the capacitance between the two legs. Electrolytic capacitors are generally higher capacitance than ceramic capacitors.
Figure 17. Electrolytic capacitor

Electrolytic capacitors (Figure 17) can generally store more charge than ceramic caps, and are longer lasting. They’re usually polarized, meaning that they have a positive leg and a negative leg. This is because current flows more efficiently through them one way than the other.

Electrolytic capacitor, showing the minus sign on the negative side. This component has a tubular top and two wire legs coming out of one end of the tube. They are generally polarized. The longer leg is the positive leg. You measure the capacitance between the two legs. Electrolytic capacitors are generally higher capacitance than ceramic capacitors.
Figure 18. Electrolytic capacitor, showing the minus sign on the negative side.

An electrolytic cap will have a + or – on one side, as shown in Figure 18.

Diodes

Diodes. Shown here are 1N400x power diodes. The body of the component is black, and the end is silver. The silver end indicates the cathode end of the diode.
Figure 19. Diodes. Shown here are 1N400x power diodes. The body of the component is black, and the end is silver. The silver end indicates the cathode end of the diode.

Related Video: Diodes and LEDs

Diodes permit voltage to flow in one direction and block it in the other direction. LEDs are a type of diode, as are the 1N4001 diodes shown in Figure 19. They’re useful for stopping voltage from going somewhere you don’t want it to go. The 1N4001 diodes are power diodes, capable of carrying a higher amount of current than other diodes.

Zener diodes. These diodes are smaller than the power diodes shown above, and have a gladd body and a black stripe to indicate the negative end of the diode. They have a breakdown voltage past which they allow current to flow in both directions.
Figure 20. Zener Diodes

Zener diodes (Figure 20) have a breakdown voltage past which they allow current to flow in both directions. They’re used to chop off excess voltage from a part of a circuit. They are usually smaller than power diodes.

Transistors

TIP120 transistor. The transistor here has the same physical package as the voltage regulators shown above. It has three legs and a tab at the top with a hole in it. The tab is the back of the component. 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, base, collector, emitter. The only way to know the difference between two components of the same package is to read the label on the package, unfortunately. This one is labeled TIP120.
Figure 21. TIP120 transistor

Video: Schematics 3 – Transistors

Transistors act as electronic switches. When you put a small voltage across the base and emitter, the transistor allows a larger current and voltage to flow from the collector to the emitter. The transistor shown above in Figure 21, a TIP120, is a type of transistor known as a Darlington transistor. It is usually used to control high-current loads like motors. Note that it uses the same physical form factor, or package, as the voltage regulator above (the TO-220 package).

The TIP120 shown here is jus one option for controlling high current loads. Metal Oxide Semiconductor Field Effect Transistors, or MOSFETS, are also good for controlling motors, lights, and other high current loads. These two models also come in the same physical package as the TIP120. The IRF510 and IRF520 MOSFETs have the same pin configuration as the TIP120, and perform similarly with a 5V gate voltage. The FQP30N06L MOSFET has the same pin configuration, and operates on as low as 1.0V, and works well for 3.3V applications. MOSFETs can generally handle more amperage and voltage, but are more sensitive to static electricity damage. 

Related Video: Connect Transistor

Phototransistors

Photo of a handful of Phototransistors.
Figure 15. Phototransistors. The short leg goes to voltage, and the long leg goes to the input pin of a microcontroller.

Phototransistors are transistors, but instead of being controlled by electricity, they are controlled by light. The base of a phototransistor is photosensitive. They often look like LEDs. The ones in Figure 15, Everlight model ALS-PT243-3C/L177, have flat tops to differentiate them from LEDs. The short leg of a phototransistor is the emitter, and the long leg is the collector. The lens is the base. To use them in an analog input circuit.  emitter goes to voltage and the collector goes to your input pin. A 10-kilohm pulldown resistor connects the input pin to ground, just as it would if you were using a photocell..

Power Jacks

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 22. A DC Power Jack

DC Power jacks are used to connect your breadboard to a DC power supply that you can plug into a wall. They’re less common in microcontroller circuits now that USB power connectors and USB wall plugs are common, but they are still very handy when you have only a DC power supply to work with. The one in Figure 22 has screw terminals on the back to which you can connect wires to connect to your breadboard. It is a 2.1mm inside diameter, 5.5mm outside diameter jack, which is a very common size.

Battery Holders

This is a square box that can hold four AA size batteries. There are four columns in the box, each with a spring in it. The negative end of the battery (the flat end) contacts the spring. The positive end of the battery (the end with a small protrusion) connects to the end opposite the spring. The batteries sit parallel to each other, each facing the opposite direction of its neighbors. Two round metal terminals protrude from one corner of the box, one red and one black. These connect to a 9-volt battery
Figure 23. AA battery holder
9V battery snap. This flat component with rounded ends has two round metal mounts on one side. One is slightly bigger than the other, about half an inch (3-2cm) across. They are designed to snap onto a 9-volt battery. There is a pair of wires coming out one end that has a DC power plug attached to it. This can plug into a DC power jack.
Figure 24. 9V battery snap with DC power plug on it.

Battery connectors like the ones shown in Figures 23 and 24 are good for connecting batteries to your project. The one in Figure 20 can hold 4 AA batteries, and has a 9V battery snap on the outside. The one in Figure 21 has a DC power jack  on one end, and a 9V battery snap on the other end.

Motors

Servo Motor

Servomotor. This is a rectangular motor with a round shaft protruding from one of the narrow sides. a wire connector protrudes from the diagonally opposite corner. The motor is approximately 1.t5 inches square (about 4cm) by half an inch thick (about 1cm). The shaft connects to one of several plastic horns so you can attach it to things you want to move. When turned by hand, the shaft will only turn 180 degrees.
Figure 25. A small RC Servomotor

Video: Analog Output: Servo

A servo motor is a motor paired with an encoder (e.g. a potentiometer) to provide position/speed readings and control messages in a feedback loop. This loop is used to precisely control of the servo’s degree of rotation. RC servomotors like the one shown in Figure 25 can only turn 180 degrees. They are often used for the rudder control on remote control planes and cars. The plastic bits shown in the photo are called horns, and they attach to the shaft to let you attach the motor to the mechanism that you want to control.

DC Motor

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

Related Video: Inside a DC Motor

DC motors, as seen in Figure 26, utilize induction (an electromagnetic field generated by current flowing through a wire coil) to rotate a central shaft. You can reverse the direction that the shaft rotates by reversing the leads powering it.

Motor Driver

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

A motor driver, sometimes called an H bridge, is an electronic circuit that enables a voltage to be applied across a load in either direction. They are often used to control the direction of DC motors. The motor driver in Figure 27 is a Toshiba model TB6612FNG. It is a good option for both 5V (from an Arduino Uno) and 3.3V (from a Nano 33 IoT) control of DC motors and stepper motors.

Electromechanical Relay

These components are rectangular, approximately three quarters of an inch long and half an inch tall, with seven pins on the bottom.
Figure 28. Electromechanical relays: top and left views as well as inside.

Like transistors, relays are electronic switches. Electromechanical relays contain a small coil that, when energized, creates a magnetic field that moves a small metal armature to open or close an electrical contact. Relays can handle higher current than transistors and can be used for AC or DC loads. However, because they rely on a physical mechanism, they are slower and more prone to wearing out. If you want to control a relay with the Arduino, you will need to use a transistor as an intermediary because most relays draw more current than the Arduino’s output pins can supply.

Relays come in many packages. The ones shown in Figure 28 are for controlling relatively low power loads. For more on relays, see the Transistors, Relays, and Controlling High-Current Loads topic page.

Screw Terminal

These components have a small round depression on the top, inside of which is a screw. On the side there is a square hole into which you can insert a wire. On the bottom, there is a pin connected to the square socket. There is one screw, socket, and pin per connection.
Figure 29. Two-contact screw terminal

Screw terminals, as seen in Figure 29, are electrical connectors that hold wires in place with a clamping screw. They allow for a more secure connection than female headers and more flexibility than soldering a wire in place. There is one screw, socket, and pin per connection.

Sensor Modules

Increasingly, sensors are no longer just simple components that output a changing resistance or capacitance. Sensor modules are application-specific integrated circuits (ASICs) which read a particular physical property and give you a measurement via a synchronous serial communications channel like I2C.

Figure 30 shows four different I2C sensors: a ten-channel spectrometer, at the top, which measures the intensity of light in ten different frequencies; An accelerometer, on the right (read below for more); a time-of-flight distance ranging sensor, that measures distance using an infrared low-power laser, on the bottom; and a light sensor that functions as both a particle sensor and a pulse oximeter, on the left, by measuring the change in color of your blood through the skin of your finger.

These are only a few of the many sensor modules available that can be connected to a microcontroller via I2C. You’ll see color and gesture sensors, temperature and humidity sensors, and many more. They are often available as breadboard-friendly breakout board modules, like the ones shown here, that are typically a circuit board that’s a few centimeters square, with holes on one side spaced 0.1″ apart so you can attach pins to plug it into a breadboard.

Photo of four different I2C sensor modules
Figure 30. Various I2C sensors

Accelerometer

Photo of an accelerometer, model LIS3DH
Figure 31. Accelerometer, LIS3DH

Accelerometers are sensors which measure a changing acceleration (Figure 31). They are typically part of sensors called Inertial Measurement Units, or IMUs. They are useful for measuring the tilt of a body, or for measuring the force of an impact. They come in both digital and analog forms. A typical accelerometer measures acceleration along three axes, all perpendicular to each other. Accelerometers are increasingly built into microcontroller modules and other electronic devices. There is accelerometer and a gyrometer built into the Nano 33 IoT.

Infrared Distance Ranger

Sharp makes a line of infrared distance ranging sensors that measure distance in about a 1-meter range using infrared light. The one shown in Figure 32 has an analog voltage output.

Photo of an infrared distance sensor. It has two lenses on top, one for the light and one for the sensor, and three pins on the side, to plug into a solderless breadboard.
Figure 32. IR distance ranger

Ultrasonic Distance Ranger

Ultrasonic distance rangers measure distance by emitting pulsed ultrasonic waves and listening for the echo from a distant object. These are sometimes used in cars to aid in detecting the distance of objects behind the rear bumper. The one shown in Figure 33 outputs a digital pulse whose pulse width varies with the distance from the target object.

Ultrasonic sensor model HC-SR04
Figure 33. An Ultrasonic sensor, model HC-SR04. The sensor has two cylindrical transducers, and four pins at the bottom of the board, labeled from left to right: Vcc, Trig., Echo, Ground.

Temperature and Humidity Sensors

There are dozens of temperature and humidity sensors on the market, with many different interfaces. The one shown in Figure 34, the DHT22, is very popular because it’s simple to use, reliable with a long track record, and inexpensive. It uses a one-wire interface.

Figure 34. a DHT-22 temperature and humidity sensor

Speaker

Photo of an 8 ohm speaker
Figure 35. Photo of an 8 ohm speaker

A speaker is a paper or plastic cone mounted to a coil of wire. The coil is mounted next to a magnet. When a current is passed through the wire, it induces a magnetic field, which attracts or repulses the magnet. This makes the cone vibrate, and produce sound. The speaker shown in Figure 35 is an 8-ohm speaker.