Search code examples
pythoncallbackswitch-statementiotled

Pyboard: Changing LED colour on USR button press


I got these this board Pyboard D-series which has internal LED diode with three different colours. My goal is to make it change the LED colour on button press so basically if u press for the first time, red goes red, second time led goes green, third time led goes blue and at the fourth time I would love it to ("reset") and go back to red.

I tried making this fucntion based on stuff I found online, but it doest seem to be working.

I am new to IoT and micropython so I might be missing something important, but have no clue what.

Thanks for any advice

from pyb import Switch
from pyb import LED


led_R = LED(1)
led_G = LED(2)
led_B = LED(3)
# 1=red, 2=green, 3=blue

sw = pyb.Switch()

def cycle():
    counter = 0
    buttonState = ''
    buttonState = sw.value()
    print(buttonState)
    if buttonState == True:
        counter = counter + 1
        print(counter)

    elif counter == 0:
        led_R.off() 
        led_G.off() 
        led_B.off() 

    elif counter == 1:
        led_R.on() 
        led_G.off() 
        led_B.off()

    elif counter == 2:
        led_R.off() 
        led_G.on() 
        led_B.off() 

    elif counter == 3:
        led_R.off() 
        led_G.off() 
        led_B.on()

    else:
        counter = 0

sw.callback(cycle())

Solution

  • Your callback cycle is called when button state transitions from off to on

    In the callback sw.value() will always evalluate into true so it does not make sense to check it.

    your counter should be initialized outside of callback

    from pyb import Switch
    from pyb import LED
    
    
    led_R = LED(1)
    led_G = LED(2)
    led_B = LED(3)
    # 1=red, 2=green, 3=blue
    
    sw = pyb.Switch()
    counter = 0
    
    def cycle():
        counter = counter + 1
        if counter == 4:
            counter = 0
        print(counter)
    
        if counter == 0:
            led_R.off() 
            led_G.off() 
            led_B.off() 
    
        elif counter == 1:
            led_R.on() 
            led_G.off() 
            led_B.off()
    
        elif counter == 2:
            led_R.off() 
            led_G.on() 
            led_B.off() 
    
        elif counter == 3:
            led_R.off() 
            led_G.off() 
            led_B.on()
    
    
    sw.callback(cycle())