The Button become Toggle Switch using Arduino

Today we will as push button switch as toggle switch. When we press the button “on” it will store status “on” hold, although, we will release. Then, we press it again it will “off” and store status “off” as well.

How it works and building
We want to control LED ON-OFF by button (as toggle switch). So we use schematic as Figure 1
The Button become Toggle Switch using Arduino_schem

Figure 1 Schematic diagram of The Button become Toggle Switch using Arduino

Parts will you needs
•Arduino UNO R3
•Normally open pushbutton
•one LED
•10K resistor
•470 ohns resistor
•jumper wires

Then, we connect parts on breadboard and the arduino as Figure 2
The Button become Toggle Switch using Arduino_bb
Figure 2 circuits connection on breadboard
We code programming on Sketch – Arduino IDE as code below.

int ledPin = 13;  // the number of the pushbutton pin
int buttonPin = 2;  // the number of the LED pin
boolean buttonState; 
boolean lastState;
boolean state = HIGH; // variable for first status
 void setup() {
  pinMode (buttonPin,INPUT);  // initialize the pushbutton pin as an input: 
  pinMode (ledPin,OUTPUT);  // initialize the LED pin as an output:
void loop() {
  reading = digitalRead(buttonPin);
  if ( reading == LOW && lastState == HIGH ) { 
    delay (10);  // To solve the The problem switch bounce 
    if (digitalRead(buttonPin) == LOW) state = !state; 
  lastState = reading;

Next, when we finished the code we have to verify/compile it will be done for no error.
And then, we have to upload into the Arduino (UNO) it will work.
(Learn more Simplest programing C on Arduino UNO)

How code works

We’ve learned about the button switch is applied in the code above.
When a button is pressed state is opposed to a state change from High to Low or from Low to High, change by the command.

state =! state;

And store value “buttonState” finally, to “lastState” too. To check whether the value of the press in this round. Logic signals “LOW” from the previous state. (no pressing) The status is “HIGH” is certainly to read once only.

The problem switch bounce
All switches has contact as metal. Often the problem of bouncing signals is the signal swing In a short time 5-50 nanoseconds in first time as Figure 3 It is caused by the contact not close, High or Low rapidly. Before into a stable state.

switch-bounce graph
Figure 3 The problem switch bounce

We can solve the problem by add a “delay (10)”, it makes the system not working for this time 10mS.

Then, we apply the USB to computer to upload code. As Figure 4 We are testing the Button become Toggle Switch using Arduino.
Figure 4
The Button become Toggle Switch using Arduino

Next step, as video we try to press LED is ON Even if we leave it to the LED is still ON. But when press again LED is OFF and still status util we press button again.

How to learn electronics with simple ways

Related Posts


I always try to make Electronics Learning Easy.

Close Menu