LED Toggle with a Push-Button Switch

This new circuit is an evolution of the LED blinker circuit and program. Instead of using a delay to alternately turn the LED on and off, we are going to use a push-button to signal the system to toggle an LED on or off.

Hooking Up a Push-Button Switch to the Arduino

A push-button switch is a very simple electro-mechanical device that has a spring-loaded contact, keeping the circuit open, that is unconnected, until the button is pressed, forcing a metal piece to bridge internal contacts thus closing the electrical circuit and allowing current to flow through. The circuit re-opens as the pressure on the push button is released, preventing current from flowing.

Floating Inputs

Let’s connect normally open push-buttons as in the following diagram.

Push Button

While the button is pushed, the circuit works. S2 is connected to the power supply, providing a HIGH value to the input pin; S1 is connected to ground, providing a LOW value to the input pin. When the push-button is not depressed, what is the value at the input pin? It is undefined, neither HIGH or LOW, or possibly fluctuating between the two values as the unconnected input acts like an antenna, picking up signals from the surrounding electromagnetic noise. This situation is known as floating inputs and must be corrected.

There is a solution. As shown in the following diagram, we can connect a resistor to ground, called a pull-down resistor, for the switch connected to the power supply; or connect a resistor to the power supply, called a pull-up resistor, for the switch connected to the ground. These resistors will ensure that the value at the input pin is always in a known state.

Pull-up Pull-down
Pull-up and pull-down resistors

The value of R can be very high as the Arduino’s digital pin input impedance, that is its opposition to current when a voltage is applied, is very high.  My current SparkFun kit has 10K resistors that will do the job. Setting R to 10K will limit the current to 0.5mA (remember, V = RI, I = V/R) when the switch is closed, allowing current to flow. The Arduino offers an input pin mode that programmatically attaches a 20K pull-up resistor to the input pin, limiting the current to 0.25 mA when the switch is closed. This mode, of course, only works if the push-button is connected to ground.

The LED Toggle Circuit

The circuit that we will use is shown in the diagram below. The push-button switch is connected to the Arduino‘s input pin 12 and to a 10K pull-up resistor. The LED‘s anode is connected to digital pin 13 and its cathode, to ground through a 330Ω current limiting resistor, exactly as was done in the LED blinker circuit.

LED Toggle
LED Toggle’s complete circuit

One thing that must be said about push-buttons is that because they are electromechanical devices, the electrical contact is not instantaneous and electrical noise is produced every time the switch is closed or opened. This is caused by the way spring-loaded metal pieces bounce as they make contact with metal connectors closing the circuit within the switch. This bouncing of metal against metal makes the contact close and open repeatedly for a few milliseconds. This happens as the switch closes and as it opens. There are debouncing electronic circuits that can be used to counteract this effect. In this post, we will only use a software solution explained as part of the program below.

Breadboarding

The following picture depicts how to connect the different parts using a solderless breadboard, jumper wires, an LED, a push button, a 10K resistor and a 330Ω resistor.

LED Toggle_bb

The LED Toggle Program

You can copy the following code directly in the Arduino IDE.

Following the usual header, you will find definitions for the INPORT, input port value, and DEBOUNCE_DELAY, the time in milliseconds to allow the switch to stabilize after it changes state when it closes or opens. Finally, the Boolean value outputValue holds the on and off LED values, HIGH for turned on and LOW for turned off.

First, we prepare the board circuitry in the setup() function. The pin mode for pin INPORT is set to INPUT, which will allow us to read the switch value. Digital I/O pins on the Arduino board can be set to either output a value or input a value, not both at the same time. The circuit described previously uses a 10K pull-up resistor. We could have specified the pin to be INPUT_PULLUP instead, which would have programmatically installed a 20K pull-up resistor at the digital input pin. The pin mode for pin LED_BUILTIN is set to OUTPUT, allowing the program to output HIGH or LOW values to the LED circuitry. Within setup(), the outputValue is set to LOW and sent to the output pin, thus extinguishing the LED.

/* Light Toggle
   Uses an LED connected to pin LED_BUILTIN as a light
   source toggled on and off at the press of a button.
   This sketch was written by Michel Lagacé, 2018-09-16
   This code is in the public domain. */

// Button value will be read from pin 12
#define INPORT 12

// Time to wait in milliseconds to consider switch debounced
#define DEBOUNCE_DELAY 10

// LED state kept across loops
static bool outputValue;

// Setup the board.
void setup() {
    pinMode(INPORT, INPUT);
    pinMode(LED_BUILTIN,OUTPUT);
    outputValue = LOW;
    digitalWrite(LED_BUILTIN,outputValue);
}

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

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

    // Toggle output on dropping edge (input is LOW when button is pressed)
    if (!value) {
        outputValue = !outputValue;
        digitalWrite(LED_BUILTIN, outputValue);
    }
}

The waitForEdge() function waits until the switch value changes from HIGH to LOW or LOW to HIGH and then returns the new switch value. The function first reads the current switch value using the digitalRead() built-in function. It then sets the newValue variable to be the same as the value just read and loops, using a while loop, until the value of the switch becomes different from the first value read. The program then waits for DEBOUNCE_DELAY milliseconds to let the switch settle. I have measured the duration of the bounce noise produced by a micro push-button switch and found that it was never more than approximately 4 milliseconds. I believe that it is therefore safe to let the switch settle for twice that amount of time. Since the switch cannot be depressed manually for more than 50 times per second, it is also safe to assume that a 10 millisecond wait will not prevent normal operation of the switch. The limitation that a 10 millisecond delay imposes is that we will not be allowed to close and open the switch within a 20 millisecond lapse of time, having to wait 10 milliseconds when the switch is closed and another 10 milliseconds when the switch is open. The waitForEdge() function returns the last switch value read.

The while loop works similarly to the for loop seen in the Morse code generator. It executes the code contained between the curly braces until the specified condition is not met, or false. Unlike the for loop, the while loop lacks initializer and post-processing statements. it has the following structure:

    while (condition) {
        // Execute the code within the curly braces
    }

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, the LED outputValue is inverted, or toggled, and then output to digital pin LED_BUILTIN.

What Next?

This circuit shows how one can read a digital value using the digitalRead() function, how switch noise can be removed with a debouncing delay, and how the while loop control structure works. You can experiment with the circuit and program to see first what happens if you remove the pull-up resistor and move your hand around the circuit. The LED will turn off or on unexpectedly without you having touched the switch. You can also try to touch the open digital input attached to the switch with your finger. The LED will start flickering as your body acts as an antenna and picks up the 50 or 60 Hz electromagnetic signals surrounding us. As another experiment, comment out the delay() line within the waitForEdge() function and depress the switch repeatedly. At some point, the LED will remain as it was, without toggling, or will briefly flicker, quickly turning on and off.

Arduino’s Blink

The very first project everybody makes in any Arduino starter kit is the blinking LED project, “Blink.” In this post, we will have a look at the theory behind this simple circuit and program.

The Circuit

This circuit is very simple and contains only two components. An LED’s anode is connected to a current limiting resistor, which is connected to the Arduino’s digital output pin 13. The LED’s cathode is connected to the Arduino’s ground as in the following circuit:

Blink Circuit

When the Arduino’s digital output pin is set to HIGH or 5 volts, current flows through the resistor and LED making the LED emit light. When the Arduino’s digital output pin is set to LOW or 0 volt, current stops flowing and the LED does not emit light.

Each component will be described later in the post. The value of the resistor may vary from one kit to another. I will explain how to compute its value later in the post.

Breadboarding

The following picture depicts how to connect the different parts using a solderless breadboard, jumper wires, an LED and a 330Ω resistor.

Arduinos Blink_bb

The Program

We start with the simple blinker program found in most if not all Arduino kits. If it is not included in your kit, you can always download a copy of Blink on the Arduino site. The following is an excerpt from the actual listing, some comments have been removed for clarity.

/* Blink: turns an LED on for one second, then off for one second,
   repeatedly.
   This example code is in the public domain.
   http://www.arduino.cc/en/Tutorial/Blink  */
 
 // the setup function runs once when you press reset
 void setup() {
   // initialize digital pin LED_BUILTIN as an output.
   pinMode(LED_BUILTIN, OUTPUT);
 }
 
 // the loop function runs over and over again forever
 void loop() {
   // turn the LED on by making the voltage HIGH, wait a second
   digitalWrite(LED_BUILTIN, HIGH);
   delay(1000);
   // turn the LED off by making the voltage LOW, wait a second
   digitalWrite(LED_BUILTIN, LOW);
   delay(1000);
 }

The language used within the Arduino IDE (Integrated Development Environment) is actual C++. The major difference is that the Arduino system does not call a main( ) function like it does under normal Windows or Linux console applications. instead, the system expect the programmer to define two ‘C’ functions:

void setup();

and

void loop();

The setup( ) function (or method) is called once the first time the program is downloaded, once after the Arduino board reset button has been depressed, or once the Arduino board has been powered up. The loop( ) function is called repeatedly and indefinitely after setup( ) has been called once.

The Arduino system also comes with a set of predefined function libraries. In our first example, two functions are used to access the digital output pin to make the LED blink. The first function’s signature (this is how we call a function’s description) is

void pinMode ( int pin, int mode );

Where pin is an integer specifying the digital pin to be setup and mode is an integer specifying the mode this pin will be used in. In the program above, the pin number used is LED_BUILTIN which corresponds to the pin number connected to the built-in Arduino board LED, pin 13 on the Arduino UNO. The mode can have one of three values: INPUT, OUTPUT, or INPUT_PULLUP, all constant values that can be used as the digital I/O pin mode. In the program, we use OUTPUT, allowing us to use the pin as a digital output. The pinMode( ) function is used as part of the setup( ) function body to prepare the LED_BUILTIN digital I/O pin to be outputted to.

The second function signature is

void digitalWrite ( int pin, int value );

Where pin is an integer specifying the digital pin we are outputting to, while value is an integer whose value can be 0 or 1, LOW or HIGH. digitalWrite( ) can only be used if the pin mode was previously set to OUTPUT.

The last function signature used within our simple piece of code is

void delay( int value )

where value is an integer specifying the amount of time in milliseconds (thousandths of a second) the program is to wait and do nothing. In the program above it waits twice for a full second each time, leaving the LED on for a full second then turning it off for a full second.

Components

Two electronic components are used within this circuit, a resistor and an LED. We will describe each in turn in the following paragraphs

Resistors

Resistors are electronic devices that restrict current flow according to Ohm’s law. Ohm’s law states that the current through a conductor between two points is directly proportional to the voltage across the two points. In mathematical terms, Ohm’s law can be restated

I = V / R

Where I is the current in amperes (A), V is the voltage across the conductor in volts (V) and R is the resistance of the conductor in ohms (Ω). Hence, a 330Ω resistor with 5V across its leads will let a current flow of 5V / 330Ω, 0.01515A, or 15.15mA.

Resistors
Two 1/4 watt carbon film resistors

Resistors restrict current by dissipating energy in the form of heat. This is an important factor as resistors have to be selected not only in terms of their resistance, but also for their capacity to dissipate heat, or power rating. The energy dissipated per second by a resistor, the electrical power, is expressed in watts (W). In mathematical terms, Power can be computed as

P = VI

Where P is the power in watts (W), V is the voltage across the resistor in volts (V) and I is the current, in amperes (A) flowing through the resistor. in the previous example, the power dissipated by the 330Ω resistor is 5V • 0.01515A, 0.07575W, or 75.75mW. The resistors supplied with most kits have a power rating of 1/4W (250mW). A 1/4W power rating is sufficient for our current example and most Arduino circuits you will encounter.

LED

LEDs are semiconductor devices that emit light when current flows through them. as its name suggests, an LED only allows current to flow in one direction, from anode to cathode, in the direction of the arrow of the diode symbol. Unlike resistors, an LEDs voltage across it leads is not linearly proportional to the current through the device and we have to look at its specification sheet to determine how the LED will perform within a circuit.

Red LED
A standard 20 mA red LED

Here is a sample datasheet for a standard 20mA LED:

YSL-R531R3D-D2

As can be seen from the data sheet, the forward voltage across the LED, that is the voltage across the LED when 20mA of current is flowing from the anode to the cathode, is between 1.8 and 2.2 volts. Also, it is suggested to limit the current between 16 to 18 mA in normal operation.

Computing the Resistor Value

Apart from Ohm’s law and the power rating formula, we need a bit more information to find a resistor value that will limit the current flow within the LED to a value not exceeding 18mA. Kirchkoff’s Voltage Law states that the sum of voltages around a closed circuit loop is 0V. Current goes in the counter-clockwise direction in this circuit, from the positive end of the power source to the negative end and the voltage drop around the power source is negative since voltage does not drop but increases around it. Redrawing our LED circuit when the digital output pin is HIGH and replacing the pin by a 5V source we get:

Kirchkoff

The sum of all voltages around the circuit is:

-5V + 1.8V + VR1 = 0V

Solving for VR1, we get

VR1 = 5V – 1.8V = 3.2V

Thus, we know that we want 18mA to flow through both LED and resistor and that the voltage across the resistor is 3.2V. Going back to Ohm’s law we know that

R1 = VR1 / I = 3.2V / 0.018A = 177Ω

This is the smallest resistor value to obtain the maximum optimal amount of current through the circuit. Resistors don’t come in all possible values. The most common values are the following values multiplied by powers of 10: 10, 15, 22, 33, 47, 68. The value just higher than 177Ω is 220Ω. Using this new value, we get

I = VR1 / R1 = 3.2V / 220Ω = 14.5mA

A value close to the optimal value suggested by the LED manufacturer. The value shown in the first circuit, 330Ω is the value used in the SparkFun kit I used for this experiment. This value limits the current to a value of 9.7mA which does allow the LED to emit light, but at a dimmer intensity.

There is Beauty in Geeky Things!

Welcome to my blog about sharing my life long passion with electronics, software design and my newfound passion with micro-controllers and their open hardware and software platforms. This blog is a series of tutorials and experiments to allow hobbyists understand the basics of electronic design and software programming and be able to reproduce the experiments, add to them and create their own circuits and programs.

Experiments in this blog make use of the Arduino Uno, a micro-controller, and a few electronic components that come with starter kits that can be found on the Internet. Experiments were tested using SparkFun Inventor’s Kit. The kit comes with a SparkFun RedBoard, a version of the Arduino Uno micro-controller, a solderless breadboard, jumper wires and electronic components such as LEDs (Light Emitting Diodes), resistors, light and temperature sensors, and more.

I recommend to the beginning enthusiast to procure a kit, whether from Sparkfun or other suppliers as they contain instructions on how to setup the Arduino, on how to get necessary software from the Internet, and how to use the software to program the micro-controller and make it work. Here is a non-exhaustive list of starter kits found on the Internet in no particular order.

Once equipped with a kit, we will embark on a series of circuits and programs that will complement and further your starter kit experience with explanations, tips and ideas.

Progress lies not in enhancing what is, but in advancing toward what will be. — Khalil Gibran

Place_Jacques-Cartier_Jan_2006