fbpx
Micropython Lesson 2: Reading the state of Push Button
Micropython Lesson 2

Reading the state of Push Button

Turn a LED on/off with a button

Components Required

Magicbit
Buy

Introduction

In this example, you are learning how to read a digital input from something like a button & use it to turn on and off a LED or any other digital device.

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).

Magicbit push button

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.

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 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).

Related Posts
Leave a Reply