Search code examples
pythonmicropythonraspberry-pi-pico

How to make an LED on, in micropython by adding 5 seconds each time you press a push button


could you please help me : I want to make an LED ON by pressing a button it Should stays ON for 5 seconds, but I want it to, if I push the button while it's ON, it will stay ON as long as the time added up. for example: when the LED is On and I push the button another time, it will be ON for 10 seconds. I'm using raspberry pi pico, with Thonny

Here is my code :

from machine import Pin, Timer
import time

White_LED = Pin(15, Pin.OUT)

button = Pin(14, Pin.IN, Pin.PULL_DOWN) 



while True:
    if button.value() == 1:
        White_LED.on() 
        time.sleep(5) 
        White_LED.off()

Solution

  • At the moment when you sleep for 5 seconds, the code stops. So, it won't notice if you press the button again.

    I think you'll need to make use of interrupt handlers (https://docs.micropython.org/en/v1.8.6/pyboard/reference/isr_rules.html) , or you could implement a simple event loop yourself.

    An event loop keeps looking for things that happen and performs some action when it does. Here's a rough idea of how you might do it.

    from machine import Pin, Timer
    import time
    
    White_LED = Pin(15, Pin.OUT)
    
    button = Pin(14, Pin.IN, Pin.PULL_DOWN)
    
    button_was = 0
    light_on_until = 0
    
    while True:
        # See if the state of the button has changed
        button_now = button.value()
        if button_now != button_was:
            button_was = button_now 
            if button_now == 1:
                # button is down, but it was up. 
                # Increase light on time by 5 seconds
                if light_on_until > time.ticks_ms():
                    # light is already on, increase the time by 5,000 ms
                    light_on_until += 5000
                else:
                    # light isn't on, so set time to 5 seconds from now (5,000 ms)
                    light_on_until = time.ticks_ms() + 5000
    
        if light_on_until > time.ticks_ms():
            # light should be on, so if it's currently off, switch it on        
            if White_LED.value() == 0:
                White_LED.on()
        else:
            # light should be off, so if it's currently on, switch it off
            if White_LED.value() == 1:
                White_LED.off()