Navigation

Saturday 3 September 2016

Pseudocode for using push button tactile switches as toggle switch

Normally, a toggle switch is used to turn on or off an output connected to a microcontroller such as LEDs or othe output sensor. What if you have a push button switch and you want to turn off and on an LED without having to keep holding down the switch? In this tutorial, the pseudocode and Arduino code to do such will be provided

The desired input/output behaviour is as follows: The first time the push button switch is pressed the LED should be ON, the second time it is pressed it should be OFF, the third time the switch is pressed, the LED should come ON again, and the fourth time turn off the LED. This on/off pattern should repeat each time the switch is pressed.

We define a variable to remember the previous state of the switch: remember_switch

Four conditions will be defined:

Condition 1: The switch is in the pressed position for the first time
Condition 2: The switch is in the released position after pressing the first time
Condition 3: The switch is in pressed position at the second time
Condition 4: The switch is in the released position initially or after the second press

Condition 1:
if (switch == HIGH && remember_switch == 0)
 remember_switch = 1;
 LED = HIGH;
Condition 2:
if (switch == LOW && remember_switch == 1)
 remember_switch = 0;
 LED = HIGH;
Condition 3:
if (switch == HIGH && remember_switch == 1)
 remember_switch = 1;
 LED = LOW;
Condition 4:
if (switch == LOW && remember_switch == 0)
 remember_switch = 0;
 LED = LOW;

No comments:

Post a Comment