Reading the state of Push Button
Turn a LED on/off from the input of a push button
Components Required
Introduction
Learning Outcomes
From this example, you’ll get an understanding about,
- IF-ELSE conditions
- Variables
Theory
The microcontroller recognizes the signal as 1(HIGH) when the signal is close to 3.3v (or 5v depending on the microcontroller) and recognizes it as 0(LOW) when the signal is close to 0v. This reading can be used in the program to do various things.
Methodology
Magicbit is equipped with two onboard push buttons. Let us select the push button which is wired to D34. Buttons on the board are pulled up internally (to learn more about pull-ups/pull-downs, follow this link). This means when the button has not been pressed the status of the button is 1(HIGH), & when the button has been pressed the status of the button is 0(LOW).
Also, like in the previous example, we need to select a LED to indicate the change, let’s select RED LED which is wired to pin D27.
First, we set the input-output configurations of the Button and the LED using Pin(), in this case, the button is an INPUT, the LED is an OUTPUT.
Then we can use the variable as the condition of the if block, and if the button is pressed, the bulb should turn on, and the button is not pressed the light should turn off.
Script
Explanation
This program starts by clicking the green flag. The forever block continuously runs the code held inside the block. This ‘read button’ block takes the output values(“HIGH” or “LOW”) from push buttons(right or left) and turns on the red LED connected to pin 27 when the right push button is pressed, and else turns it off.
If and else control block evaluates the boolean condition of the boolean block. If the condition is true, it executes the code block inside the if part and if the condition is false it executes the code block inside the else part.
Note: Write a code to toggle an LED in the button press. The LED turns on when the button is pressed & released, the LED turns off when the button is pressed & released again. (Hint: Make use of variables to ‘remember’ the state of the button press).