Scheduler example on Kickstarter

General discussions and questions abound development of code with MicroPython that is not hardware specific.
Target audience: MicroPython Users.
Post Reply
Neil Higgins
Posts: 6
Joined: Sun Apr 27, 2014 10:25 am

Scheduler example on Kickstarter

Post by Neil Higgins » Sat Aug 16, 2014 12:42 pm

FWIW, the scheduler example on Kickstarter (https://www.kickstarter.com/projects/21 ... sts/675393) does not work with the current release of Micropython. I suspect the pyb module has undergone some refinement since the example was posted. Here's my updated version which actually runs:

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()

Post Reply