Code: Select all
import pyb
# a scheduler class
# schedule(): queue a function for delayed execution (delay in ms)
# run(): execute functions with specified delays
class Scheduler:
def __init__(self):
# begin with no events
self.events = []
# queue a function for delayed execution (delay in ms)
def schedule(self, delay, function):
if delay <= 0:
# if no delay, run the function straight away
function()
else:
# queue the function
self.events.append([delay, function])
# sort the queue, smallest delay first
self.events.sort(key = lambda event: event[0])
# execute functions with specified delays
def run(self):
# loop while there are events to process
while len(self.events) > 0:
# get the first event
delay, function = self.events.pop(0)
if delay > 0:
# subtract time from remaining events
for event in self.events:
event[0] -= delay
#Wait for the required delay
pyb.delay(delay)
#run the function
function()
# a flashing LED class
class FlashingLED:
def __init__(self, led_id, time_on, time_off):
# LED will turn on for time_on and off for time_off
self.led = pyb.LED(led_id)
self.led_id = led_id
self.time_on = time_on
self.time_off = time_off
# start with LED on
self.on()
def on(self):
# turn the LED on
print("LED", self.led_id, "on")
self.led.on()
# schedule a function to turn the LED off
sched.schedule(self.time_on, self.off)
def off(self):
# turn the LED off
print("LED", self.led_id, "off")
self.led.off()
# schedule a function to turn the LED on
sched.schedule(self.time_off, self.on)
# make an instance of Scheduler
sched = Scheduler()
# make LED 1 turn on for 1 second, off for 2 seconds
FlashingLED(1, 1000, 2000)
# make LED 2 turn on for 3 seconds, off for 1 second
FlashingLED(2, 3000, 1000)
# make LED 3 turn on for 0.5 second, off for 1 second
FlashingLED(3, 500, 1000)
# make LED 4 turn on for 0.25 second, off for 0.25 second
FlashingLED(4, 250, 250)
#run the scheduler
sched.run()