Pyboard's On-board Peripherals - LEDs

Contents

Introduction to Pyboard's LEDs

The Pyboard V1 has four onboard LEDs - red, green, orange, blue - that are easy to control through MicroPython.

The LEDs are connected to the P2,  P3,  P4  and P5  pins. The red, green and orange LEDS are current limited with 560 Ω resistors. The blue LED is limited with a 220 Ω resistor.

A MicroPython program gains access to these four LEDs through the simple to use pyb.LED class.

MicroPython pyb.LED Class

There are four LEDs on the Pyboard with colours; red, green, orange and blue. They are controlled with methods from the pyb.LED.


Syntax:
pyb.LED(id)
Creates an LED object associated with the given LED id.

Where:
  id : The LED number, 1-4
       1 = Red, 2 = green, 3 = orange, 4 = blue 

Syntax:
LED.on()
Turn the LED on.

Syntax:
LED.off()
Turn the LED off.

Syntax:
LED.toggle()
Toggles the LED.
If the LED is on, it is turned off.
If the LED is off, it is turned on.

Examples:
from pyb import LED, delay

# Get an LED object, colour is green.
led = LED(2)

# Turn the green LED on.
# Wait 2 seconds.
led.on()
delay(2000)

# Turn the green LED off.
# Wait 2 seconds.
led.off()
delay(2000)

# Toggle the green LED on.
# Wait 2 seconds.
# Toggle LED off.
led.toggle()
delay(2000)
led.toggle()
          

Example: Using Pyboard's LEDs

This example uses all four of the Pyboard's LEDS. They are turned on in sequence - red, green, orange, blue - each for 500 ms. This sequence is repeated till the program is user interrupted with (for example) CTRL-C.

If a KeyboardInterrupt  exception is raised by user interaction then it is trapped. All the LEDs are turned off and the program exits safely with a soft reboot.


Example:
# This program cycles through the
# Pyboard's on-board LEDS.

# Each LED in turn is held on for 500 ms
# before being toggled off and the next LED
# in sequence is turned on.

# This cycles in an infinite loop.

from pyb import LED
from time import sleep_ms
import sys

# Define the four LEDs.
red = LED(1)
green = LED(2)
orange = LED(3)
blue = LED(4)
leds = (red, green, orange, blue)

# Run the LED sequence indefinitely.
# Trap any keyboard interrupt exception and
# clean up before exiting with a soft reset.

try:
    while True:
      for led in leds:
        led.on()
        sleep_ms(500)
        led.off()
        sleep_ms(500)
except KeyboardInterrupt:
    print('\nKeyboard Interrupt.\nTurning all LEDs off.')
    for led in leds: led.off()
    sys.exit(0)