,

Buttons and LEDs with microPython

Posted by

Today’s post will teach you how to control buttons and LEDs with microPython. We are using the Raspberry Pi Pico 2 and Thonny IDE for the job. The idea is to show you a way of not using time.sleep(), which blocks code execution. I also show you how to use “print()” to print texts and variables into the Thonny IDE shell (“serial monitor” in Arduino words).

import machine
import time


led = machine.Pin(15, machine.Pin.OUT)
button= machine.Pin(16, machine.Pin.IN)

def main():
    
    ledtime= time.ticks_ms() #https://docs.micropython.org/en/latest/library/time.html
    buttontime= time.ticks_ms()
    counting= 0
    ledon= False
    laststate= 1
    buttonon= False
    clicks= 0
    
    while True:
        
        if time.ticks_diff(time.ticks_ms(), ledtime) > 200 and ledon == True: # this IF will be True every 2000 ms
            ledtime= time.ticks_ms() 
        
            led.value(not led.value())  

        if time.ticks_diff(time.ticks_ms(), buttontime) > 20: # this IF will be True every 2000 ms
            buttontime= time.ticks_ms() 
            
            if button.value() == 1 and laststate == 0:
                clicks+= 1
                print("LED state changed")
                print("clicks: " + str(clicks))
                laststate= 1
                ledon = not ledon
                buttonon= True
            
                
            if buttonon == True and counting < 20:
                counting+= 1
                
            else:
                counting= 0
                buttonon= False
                laststate= 0
            
main()

Leave a Reply

Your email address will not be published. Required fields are marked *