MagicCode Lesson 5
Reading the state of Push Button
Turn a LED on/off from the input of a push button
From this example, you’ll get an understanding about,
- IF-ELSE conditions
Microcontroller recognizes the signal as 1(HIGH) when the signal is close to 3.3v (or 5v depending on the microcontroller) and recognizes as 0(LOW) when the signal is close to 0v. This reading can be used in the program to do various things.
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 pullups/pulldowns follow this link), which means when the button is not pressed the status of the button is 1(HIGH), & when the button is 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, lets 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 button is an INPUT, 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.
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 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. LED turns on when button pressed & released, LED turns off when button is pressed & released again. (Hint: Make use of variables to ‘remember’ the state of the button press).