,

Algorithm to LED blink with microPython

Posted by

First watch the video and see how the project works, then scroll down to replicate it. It uses a Raspberry Pi Pico 2 with microPython.

Schematic diagram:

Pi Pico 2, LED and button schematic diagram
Pressing a button on a breadboard with raspberry pi pico 2
Raspberry Pi Pico 2 on a breadboard with button and LED

Now the code. Paste it into Thonny IDE and download it to the Raspberry Pi Pico 2.

import machine
import time

led= machine.Pin(15, machine.Pin.OUT) #Pi Pico 2
button = machine.Pin(16,machine.Pin.IN) #Pi Pico 2

def main():
    
    #https://docs.micropython.org/en/latest/library/time.html
    ledtime= time.ticks_ms() # keep track of LED blinking timing
    buttontime= time.ticks_ms() # keep track of button presses time
    countresult= time.ticks_ms() # keep track of 2s after button pressed
    countdebounce= 0
    countresult= 0
    blinktimes= 0
    enableblink = 0
    buttontime= 0
    olddebounce= 0

    while True:
        
        if time.ticks_diff(time.ticks_ms(), ledtime) > 300: # this IF will be true every 300ms
            ledtime= time.ticks_ms() #update with the "current" time
            
            if blinktimes != 0: # blinktimes represents the number of blinks of the LED
                if enableblink == 1: # If blink is enabled we can toggle the LED
                    blinktimes= blinktimes - 1 #keep track of number of blinks
                    led.value(not led.value())  # Toggles the LED
            else:
                led.value(0)
                enableblink= 0

        # The button reading function executes every 20ms
        if time.ticks_diff(time.ticks_ms(), buttontime) > 20:
            buttontime= time.ticks_ms()
            
            countdebounce+= 1 # This keeps track of 400ms debounce function
                        
            if button.value() == 1: # When the button is pressed
                if countdebounce - olddebounce > 20: # button debounce time has passed
                    olddebounce= countdebounce
                    blinktimes+= 2
                
                    countresult= time.ticks_ms()
                    
            # Enable blink only if 2s have passed after last button detection
            # and a number of blinks is present at blinktimes
            if time.ticks_diff(time.ticks_ms(), countresult) > 2000 and blinktimes != 0:
                
                enableblink = 1
            else:
                enableblink = 0
main()

Leave a Reply

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