
Micropython Lesson 2
Turn a LED on/off with a button
Components Required
Introduction
Learning Outcomes
From this example, you’ll get an understanding about,
- IF-ELSE conditions
- Variables
Theory
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.
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 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.
Code
from machine import Pin
led = Pin(16, Pin.OUT)
btn = Pin(34, Pin.IN)
while True:
if btn() == 0:
led.on()
else:
led.off()
Explanation
IF/ELSE: Used to evaluate a digital condition, we can put a digital logic condition in then 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. 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).