Switch Debouncing

In the LED Toggle with a Push-Button Switch post, I have explained how electro-mechanical devices, such as push-button switches, do not close or open an electrical circuit instantaneously, causing electrical noise. Every time a switch closes or opens, spring-loaded pieces of metal bounce causing the circuit to be opened and closed rapidly for a brief moment. In my previous post, I explained how to counteract switch bounce using software. In this post I will show a simple electronic solution to switch bounce using a resistor and a capacitor. In the Arduino’s Blink post we have seen that resistors are electronic devices that restrict current flow according to Ohm’s law. We will now describe a new passive electronic device, the capacitor. The featured image at the beginning of this blog post was created by Michael Maggs and edited by Richard Bartz, CC BY-SA 3.0, and can be found in the Wikimedia Commons.

Capacitors

A capacitor is a two-terminal device that can store electrical energy. It consists of two leads attached to conducting bodies that are separated from one another by an insulator, called a dielectric. Because of the dielectric, charges cannot move from of conducting body to the other within the device. Instead, charges of equal magnitude and opposite sign accumulate on each conducting body in proportion to the voltage across the device. The capacitance of a capacitor is defined as the ratio of the magnitude of the charge Q on either conducting bodies to the magnitude of the potential difference V between the two conducting bodies.

C = Q/V

It follows from its definition that the unit of capacitance is coulombs per volt. A capacitance of one coulomb per volt is said to have a value of one farad (1 F) in honor of Michael Faraday. In terms of quantity of electrons, one coulomb corresponds to 6.25×1018 electrons. The most common type of capacitor consists of two conducting plates parallel to each other and separated by a distance which is small in comparison to the linear dimensions of the plates such as in the following figure. Note that the quantity of positive charges is always the same as the quantity of negative charges and that the total charge remains zero.

undefined

In electronic schematics, capacitors are represented by two parallel lines separated by a gap with perpendicular lines attached to each parallel line representing the leads as in the following figure. Note the second representation in the middle which has a straight line and a curved one. Both representations are valid. Some capacitors are polarized, that is that one lead must always have a higher voltage than the other in order to function properly and not be damaged. A plus sign indicates the positive lead of a polarized capacitor as shown with the capacitor symbol at the right.

We have determined the relationship between charge and voltage. It would be more interesting to establish the relationship between current and voltage. It turns out that current is defined as the rate of change of charge over time. Hence, current is defined as

i = dQ/dt

Where dQ, delta charge, is the change in charge and dt, delta time, is the change in time. Current is thus defined as the quantity of charge per second, or the number of coulombs per second. One ampere, the standard unit of current is defined as one coulomb per second. Since Q = C•V, the relationship between current and voltage is

i = dQ/dt = C•dv/dt

The current in a capacitor is equal to the capacitance of the capacitor times the rate of change of voltage over time. This type of equation is called a differential equation and solving it is beyond the scope of this post. Its solution depends on the function representing the change of voltage over time. I will present, however, solutions to this equation when dealing with digital circuitry.

Within digital circuitry, we are interested in the operation of the capacitor when values in the circuit change between a logical low, 0 V, and a logical high, 5 V on an Arduino Uno, and when the values in the circuit change from a logical high to a logical low. Instantaneously switching the voltage across a capacitor requires an infinite amount of current according to the equation above. The change in time is 0 seconds, being instantaneous, resulting in a division by zero. Of course, this does not happen in reality because there are no perfect conductors and wires and device leads are always slightly resistive, limiting the current required to charge up the capacitor. Let’s find out what happens when we put an actual resistor in series with a capacitor and switch the voltage from low to high. In the following figure, the voltage across the capacitor is initially 0 V and we close a switch, applying 5 V across the resistor and capacitor.

The moment the switch is closed, the voltage across the capacitor is 0 V while the voltage across the resistor is 5 V. As explained in the Blink post, Kirchhoff’s voltage law stipulates that the sum of voltage drops along a closed-circuit loop is 0 V. In this case, the battery provides 5 V while the resistor and capacitor drop 5 V together. At the moment the switch is closed and as the capacitor’s charges start accumulating on its conducting bodies, the current through the circuit is I = V/R, following Ohm’s law. As charges accumulate in the capacitor, the voltage across the capacitor increases and the voltage across the resistor decreases. Eventually, after a long time, the voltage across the capacitor reaches 5 V while the voltage across the resistor becomes 0 V and current ceases flowing in the circuit. Charges start by accumulating fast and as time goes by and as current becomes smaller and smaller, charges within the capacitor accumulate at a slower and slower rate. Intuitively, we can draw a graph of the voltage across the capacitor as time goes by as follows.

We have seen the behavior of a capacitor as it accumulates charges, or charges up, through a resistor. Let’s now see what happens when a capacitor discharges through a resistor. In the following figure, the voltage across the capacitor is initially 5 V and we close a switch, applying 5 V across the resistor as we close the circuit.

The moment the switch is closed, the voltage across the resistor reaches 5 V. Again, Kirchhoff’s voltage law stipulates that the sum of voltage drops along a closed-circuit loop is 0 V. In this case, the capacitor provides 5 V while the resistor drops 5 V. At the moment the switch is closed and as the capacitor’s charges start to flow out of its conducting bodies, the current through the circuit is I = V/R, following Ohm’s law. As charges flow out of the capacitor, the voltage across the capacitor and resistor decreases. Eventually, after a long time, the voltage across both capacitor and resistor reaches 0 V and current ceases flowing in the circuit. Charges start by flowing out of the capacitor fast and as time goes by and as current becomes smaller and smaller, the capacitor discharges at a slower and slower rate. Intuitively, we can draw a graph of the voltage across the capacitor as time goes by as follows.

It turns out that the voltage across the capacitor as a function of time for the discharging capacitor through a resistor is:

VC = V0e-t/RC

Where VC is the voltage across the capacitor, V0 is the initial voltage across the capacitor, t is the time in seconds after the switch has been closed, R is the value in ohms of the resistor and C is the value in farads of the capacitor. Similarly, the voltage across the capacitor as a function of time for the capacitor charging through a resistor is:

VC = V0(1 – e-t/RC)

Where VC is the voltage across the capacitor, V0 is the voltage across the voltage source, t is the time in seconds after the switch has been closed, R is the value in ohms of the resistor and C is the value in farads of the capacitor. The product of the resistance by the capacitance, RC, is called the RC time constant and its value is in seconds. It corresponds to the time it takes for the capacitor to charge or discharge by approximately 63%.

Capacitor Devices

Capacitors are manufactured in many ways and take many size, shape and form. All capacitor devices are built around the same principle: two conductors, often in the form of plates, separated by dielectrics. Where they differ is how they are constructed and the type of dielectrics used. Most capacitors used in circuits are of one of two types: non-polarized and polarized capacitors.

Ceramic, paper and film capacitors are non-polarized capacitors that are named after the dielectric material used in the capacitor. Electrolytic capacitors are polarized capacitors that are named after the material used as the anode, the positive lead of the capacitor, such as aluminium, tantalum, niobium, and the electrolyte used as the cathode, the negative lead of the capacitor. Generally speaking, non-polarized capacitors have values smaller than one microfarad and polarized capacitors have values greater or equal to one microfarad. The following picture shows three types of capacitors.

In the picture above, the first capacitor to the left is a ceramic disk capacitor with marking 680K 1KV Z5R. The middle capacitor is a Mylar film capacitor with marking NIH153. The third capacitor is an electrolytic aluminium capacitor with marking 2200µF 25V. The first two capacitors are non-polarized capacitors while the last one is polarized with its cathode marked with a minus sign.

Markings tell us about the value and ratings of the capacitor. For the first capacitor to the left, the marking 680K is read as follows: the first two digits represent the value of the capacitor, the third digit represents the power of 10 multiplier in picofarads, 10-12 farads, for the capacitor value and the letter represents the tolerance. In this case, the capacitor has a 68×100 picofarads value, 68 pF. The K represents a capacitance value tolerance of 10%. 1KV is the voltage rating of the capacitor, 1 kilovolt. Z5R represents the temperature characteristic of the capacitor, there is a maximum capacitance value shift of +15% when temperatures range from 10˚C to 85˚C. Specifications for ceramic disk capacitors can be found here.

In the case of the polyester film capacitor, the middle one, the first two digits represent the value of the capacitor and the third digit represents the power of 10 multiplier in picofarads, 10-12 farads, for the capacitor value. In this case, the capacitor has a value of 15×103 picofarads, 15000 pF, 15 nF, or 0.015 µF. I did not find the meaning for the “NIH” marking. The markings on the electrolytic capacitor are quite explicit: it has a value of 2200 microfarads and a voltage rating of 25 volts.

Demonstrating Mechanical Bounce in a Switch

In order to demonstrate the effect of switch bounce I built a circuit and Arduino program that sequentially turns LEDs on and off every time a high to low edge is detected at one of the digital inputs of an Arduino Uno. The circuit is as follows.

In this circuit, the Arduino’s digital input/output pin 12 is connected to a push-button switch and a 10 K pull-up resistor. The other end of the pull-up resistor is connected to the 5 V supply and the other end of the switch is connected to ground. The rest of the circuit consists of 4 LEDs whose cathodes are connected to ground through 330 Ω resistors and whose anodes are connected to the Arduino’s digital input/output 8, 9, 10, and 11 respectively. The following diagram depicts how to connect the different parts using a solderless breadboard, jumper wires, four LEDs, a push-button switch, a 10 K resistor and four 330 Ω resistor.

Switch Bounce Demonstration Program

The Arduino sketch used to demonstrate switch bounce can be found on Github at https://github.com/lagacemichel/SwitchBounce. Download the sketch SwitchBounce.ino and load it in the Arduino IDE. You can also copy the following code directly into a new Arduino sketch within the IDE.

Following the usual comment at the beginning of the sketch, you will find a definition for INPORT, the input port connected to the switch, and the Boolean value switchState holding the last state of the input switch. Then LED0, LED1, LED2, and LED3, the output ports to the four LEDs, are defined followed by the definition of Boolean value litLED holding a value between 0 and 3 corresponding to the currently lit LED.

The board circuitry is prepared for use in the setup() function. The pin mode for pin INPORT is set to INPUT, which will allow us to read the switch value. The pin mode for pins LED0, LED1, LED2, and LED3 is set to OUTPUT, allowing the program to output HIGH or LOW values to the LEDs. Within setup(), switchState is set to HIGH, the switch is not being depressed, and litLED is set to 0 (zero) indicating that LED0 is lit. We finally turn LED0 on and LED1, LED2 and LED3 off using the digitalWrite() built-in function.

/*
Switch Bounce sketch
Uses four LEDs connected to digital I/O pins 8, 9, 10, and 11 to demonstrate
the effect of a mechanical switch's bounce by lighting the LEDs in sequence
everytime the switch's input goes from high to low.
MIT License
Copyright (c) 2020, Michel Lagace
*/

// Switch value will be read from pin 12
#define INPORT 12
static bool switchState = HIGH; // State of the switch

// LED values will be output on pins 8, 9, 10, and 11
#define LED0 11
#define LED1 10
#define LED2 9
#define LED3 8
static unsigned int litLED = 0; // Currently lit LED

// Setup the board.
void setup() {
  // Set Arduino<s input and output ports
  pinMode(INPORT, INPUT);
  pinMode(LED0, OUTPUT);
  pinMode(LED1, OUTPUT);
  pinMode(LED2, OUTPUT);
  pinMode(LED3, OUTPUT);

  // Initialize switch state and currently lit LED
  switchState = HIGH;
  litLED = 0;
  digitalWrite(LED0, HIGH);
  digitalWrite(LED1, LOW);
  digitalWrite(LED2, LOW);
  digitalWrite(LED3, LOW);
}

// Wait for an edge and return state
bool waitForEdge() {
  bool newValue = switchState;
  while (newValue == switchState) {
    newValue = digitalRead(INPORT);
  }
  switchState = newValue;
  return newValue;
}

// Repeat forever
void loop() {
  // Wait for a rising or falling edge
  bool value = waitForEdge();

  // Increase output on dropping edge (input is LOW when button is pressed)
  if (!value) {
    litLED++;
    if (litLED > 3) {
      litLED = 0;
    }

    // Light up the appropriate LED
    digitalWrite(LED0, litLED == 0);
    digitalWrite(LED1, litLED == 1);
    digitalWrite(LED2, litLED == 2);
    digitalWrite(LED3, litLED == 3);
  }
}

The waitForEdge() function waits until the switch value changes from its previously registered value in variable switchState to a new switch value. The function first copies the value of switchState into the newValue variable and loops, using a while loop, until the value of the switch value read using the digitalRead() built-in function becomes different. Variable switchState is set to the new switch value and the value is returned by the function.

Finally, the main loop() function repeatedly waits for a switch value change through a call to the waitForEdge() function. If the returned value is LOW, that is the push-button has been depressed making the (!value) condition true, we increment the value of litLED by one using the post increment operator ++. The post increment operator increases the value of the variable by one after all other operations in the statement have been evaluated. If the value of litLED is larger than 3 it is set to 0. The last four lines of the loop() function set the LED output pins to HIGH or LOW according to the value of variable litLED. LED0 is lit if variable litLED is 0, LED1 is lit if litLED is 1, and so forth for each LED output pin. Note that the second parameter of the digitalWrite() function takes a Boolean value. To set the digital output to HIGH, the parameter is set to true, and it is set to false to set the digital output to LOW. This allows us to use a Boolean test, such as the equality test, to set the output to the appropriate value.

Observing Switch Bounce

Without mechanical bounce, the circuit and program behaves as follows: every time the switch is depressed, the waitForEdge() function detects a change from HIGH to LOW and returns the value LOW. The main loop() function, because the returned value is LOW increments the value of variable litLED and the next LED is turned on while the currently lit LED is turned off. Each LED is turned on, in sequence, at each switch press.

However, since there is mechanical bounce, every time the switch is pressed, there is more than one HIGH to LOW transition and the litLED variable is incremented one, two, or more times making the program skip LEDs when the switch is depressed. The same phenomenon may happen when the switch is released since mechanical bounce may happen both when the switch is depressed and when it is released. Try to hit the switch several times rapidly to see it happen. Sometimes the LEDs will light in sequence and at other times LEDs will be skipped.

A Switch Debounce Circuit

Following, is the switch bounce demonstration circuit to which I have added a resistor and a capacitor. The resistor, R1, is connected on one side between the pullup resistor and the switch and on the other side to the Arduino’s input pin. The capacitor, C1, is connected between the Arduino’s input pin and ground. The voltage across the capacitor is thus applied to the Arduino’s input pin. The idea is to try to keep the voltage at the input pin LOW when the switch is depressed even though the voltage value at the switch rapidly changes from HIGH to LOW and LOW to HIGH because of mechanical bounce. Similarly, we try to keep the voltage at the input pin LOW when the switch is released for as long as there is electrical noise caused by the mechanical bounce.

As discussed in a previous post, I measured up to 4 ms worth of noise when the micro-switch in this circuit is depressed or released. Since the system is to activate upon the switch being depressed, we want the voltage across the capacitor to drop fairly fast, but remain between 0 and 1 volt, a LOW value, for at least 4 ms. As a rule of thumb, we want the voltage to drop at least 10 times faster than when it comes back up. From the equation of a charging capacitor

VC = V0(1 – e-t/RC)

We want VC to remain between 0 V and 1 V for at least 4 ms. In the previous formula for a charging capacitor, we substitue 1 V for VC, the maximum capacitor value; 5 V for V0, the supply value; 4 ms for t, the maximum time for the capacitor voltage to reach 1 V; C1 for C, the value of the capacitor; and (10 K + R1) for R, the value of the resistor while charging the capacitor. We thus get

1 V = 5 V(1 – e-4 ms/(10 K+R1)C1)

4/5 = e-4 ms/(10 K+R1)C1)

ln 4/5 = -4 ms/(10 K+R1)C1

(10K +R1)C1 = -4 ms/ln 0.8

From the previous formula for a discharging capacitor

VC = V0e-t/RC

We want the capacitor voltage to reach 1 V, the maximum voltage for a LOW, in less than 0.4 ms. So, using the formula for the discharging capacitor, we substitute 1 V for VC maximum capacitor value; 5 V for V0, the initial capacitor voltage; 0.4 ms for t, the maximum time for the capacitor voltage to reach 1 V; C1 for C, the value of the capacitor; and R1 for R, the only resistor through which the capacitor discharges when the switch is depressed. We get

1 V = 5 Ve-0.4 ms/R1C1

1/5 = e-0.4 ms/R1C1

ln 1/5 = -0.4 ms/R1C1

R1C1 = -0.4 ms/ln 0.2

Hence we get two equations

10 K C1 + R1C1 = -4 ms/ln 0.8

R1C1 = -0.4 ms/ln 0.2

Substituting -0.4 ms/ln 0.2 for R1C1 in the first equation, we get

10K C1 – 0.4 ms/ln 0.2 = -4 ms/ln 0.8

C1 = (0.4 ms/ln 0.2 – 4 ms/ln 0.8)/10 K

C1 = 1.7 µF

C1 is approximately equal to 1.7 µF (microfarads). The standard capacitor value closest to 1.7 µF is 2.2 µF. Substituting 2.2 µF for C1 in the second equation, we get

R1 = -0.4 ms/(2.2 µF ln 0.2)

R1 is approximately equal to 112 Ω. The standard resistor value closest to 112 Ω is 100 Ω. In order to cope with a maximum switch bounce of 4 ms, we modify the circuit with C1 set to 2.2 µF and R1 set to 100 Ω. In the following circuit diagram, notice that the capacitor symbol has changed and that the capacitor is now polarized. This is because when capacitors have a value larger than 1 µF we generally use polarized capacitors such as electrolytic capacitors.

The following graph depicts what happens to the mechanical noise after the resistor and capacitor are added to the circuit. In blue, we have the voltage across the switch. Notice the two 1 ms spikes when the switch is depressed and the 1 ms downward spike 3 ms after the switch has been released. In orange, we have the voltage across the capacitor. Notice how all spikes have been flattened below 1 volt and how relatively quickly the voltage drops when the switch is depressed. It takes approximately 0.4 ms for the capacitor to discharge to 1 V when the switch is depressed. Conversely, it takes about 20 ms for the capacitor to charge to 3 volts, a HIGH value, after the switch has been released, limiting the number of successive switch activation to approximately 40 switch closures a second, which is more than acceptable.

The following picture depicts how to connect the different parts of the electronic debounce demonstration circuit using a solderless breadboard, jumper wires, four LEDs, a push button, a 2.2 µF capacitor, a 100 Ω resistor, a 10 K resistor and four 330 Ω resistor. Note that the lead aligned with the negative sign on the capacitor body is connected to ground.

Observing Switch Debounce

With the new circuit, whether there is mechanical bounce or not, the circuit and program behaves as follows: every time the switch is depressed, the waitForEdge() function detects a change from HIGH to LOW and returns the value LOW. The main loop() function, because the returned value is LOW increments the value of variable litLED and the next LED is turned on while the currently lit LED is turned off. Each LED is turned on, in sequence, at each switch press. Because the capacitor eliminates switch bounce, the LED sequence advances by only one LED every time the switch is depressed.