MicroPython LED Blink Examples for P2
# LED Blink Example #0
# The Simple Way: Using p2 module's delay(), pinh(), and pinl() methods
# SimpleP2 has two free LEDs on P52 and P53, so using one of these
led=52
# Toggle LED state every second using pinh() and pinl() methods
while True:
p2.pinh(led)
p2.delay(1000)
p2.pinl(led)
p2.delay(1000)
# LED Blink Example #1
# A Simpler Way: Using p2 module's delay() and pint() methods
import p2
# SimpleP2 has two free LEDs on P52 and P53, so using one of these
led=52
# Toggle LED state every second using the pint() method
while True:
p2.pint(led)
p2.delay(1000)
# LED Blink Example #2
# A better way: Using p2 module's startled() and setled() methods
# These methods let you adjust the brightness from 0 (off) to 255 (on)
import p2
# SimpleP2 has two free LEDs on P52 and P53, so using one of these
led=52
p2.startled(led,0) #start off
# Toggle LED state every second using pinh() and pinl() methods
while True:
p2.setled(led,0) #LED Off
p2.delay(1000)
p2.setled(led,255) #LED On
p2.delay(1000)
# LED Blink Example #3
# Without Delay: Using time module instead of p2 for pause
import p2
# SimpleP2 has two free LEDs on P52 and P53, so using one of these
led=52
level = 0
p2.startled(led,level) #start off
import time
prev_millis = time.ticks_ms()
interval = 1000
# Toggle LED state every second using pinh() and pinl() methods
while True:
curr_millis = time.ticks_ms()
if curr_millis - prev_millis > interval:
prev_millis = curr_millis
level = 255 - level #toggle
p2.setled(led,level)
# LED Blink Example #4
# Fade In/Out: Using p2 module's startled() and setled() methods
# These methods let you adjust the brightness from 0 (off) to 255 (on)
import p2
# SimpleP2 has two free LEDs on P52 and P53, so using one of these
led=52
p2.startled(led,0) #start off
# Toggle LED state every second using pinh() and pinl() methods
while True:
for x in range(256):
p2.setled(led,x) #Fade In
p2.delay(4)
for x in range(256):
p2.setled(led,255-x) #Fade Out
p2.delay(4)
# LED Blink Example #5
# Heart Beat: Using p2 module's startled() and setled() methods
# These methods let you adjust the brightness from 0 (off) to 255 (on)
import p2
# SimpleP2 has two free LEDs on P52 and P53, so using one of these
led=52 # LED pin
value = 0 # LED value
p2.startled(led,value) #start led
tick = 0 # counter variable
while True:
if tick <= 3:
value = 255 - value
p2.setled(led, value)
# make sure value of tick has a 0..9 range
tick = (tick + 1) % 10
p2.delay(100)
# LED Blink Example #6
# Heartbeat with fade
import p2
led =52
p2.startled(led,0)
tick = 0 # counter variable
while True:
if tick < 40:
# self.tick % 20 gives a number 0 to 19
# subtracting 9 makes it -9 to 10
# abs maps it 9 to 0 to 10
# subtracting from 10 maps it 1 to 10 to 0
# multiplying by 25 scales it 25 to 250 to 0
p2.setled(led,((10 - (abs((tick % 20) - 9))) * 25))
tick = (tick + 1) % 100
p2.delay(10)