Micropython Lesson 2
Reading the state of Push Button
Turn a LED on/off with a button
From this example, you’ll get an understanding about,
- IF-ELSE conditions
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.
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, 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.
from machine import Pin led = Pin(16, Pin.OUT) btn = Pin(34, Pin.IN) while True: if btn() == 0: led.on() else: led.off()
IF/ELSE: Used to evaluate a digital condition, we can put a digital logic condition in the parenthesis. If the condition is true, it executes the code block immediately below it, if the condition is false it executes the code block in the else block.
if (condition) # Do if condition is true else # Do if condition is false
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).