Step 3: Adding the LED

We can switch between two states, and the program prints some output when this switch happens. It would be nice to have a way to show the user which state the program is in now. We can make use of a LED for this.

Now we can import the neopixel library, and use it to set up some variables to control the LED.

##--- Imports
import neopixel

##--- Variables
# For the Chainable LED:
pin_leds = board.D10
num_leds = 1
leds = neopixel.NeoPixel(pin_leds, num_leds, auto_write=False, pixel_order=neopixel.GRBW)


Attach the LED to D3. Let’s create a function that can change the LED’s color.

##--- Functions
##--- Acting machine effect functions
def set_led_color(color):
    global leds
    leds.fill(color)
    leds.show()

The LED takes RGB colors, with each channel ranging between 0 and 255. To make things easier on us, we can store some color variables to use later.

##--- Variables
led_off = (0, 0, 0, 0)
led_red = (255, 0, 0, 0)
led_green = (0, 255, 0, 0)
led_blue = (0, 0, 255, 0)
led_yellow = (255, 255, 0, 0)
led_white = (0, 0, 0, 255)

Equipped with our new variables and function, we can change the color of the LED with only minimal alterations to our original main loop:

##--- Main loop
while True:
    # State Idle
    if current_state == state_idle:
        if check_button_press():
            print("Switch from Idle to Work") 
            current_state = state_work
            set_led_color(led_green)

    # State Work
    elif current_state == state_work:
        if check_button_press():
            print("Switch from Work to Idle") 
            current_state = state_idle
            set_led_color(led_off)
            

It’s time to upload your code to the PicoExpander and see if it works! Your code should now:

  • Output a print statement once the state changes
  • Switch between states upon button press
  • Turn the LED green when the state changes from idle to work
  • Turn the LED off when the state changes from work to idle

Click here to see the code you should have until now.

Next Step


Table of contents