Skip to content

Instantly share code, notes, and snippets.

@yoyicue
Created July 29, 2014 00:51
Show Gist options
  • Save yoyicue/45a1caa953e07e2a6f9b to your computer and use it in GitHub Desktop.
Save yoyicue/45a1caa953e07e2a6f9b to your computer and use it in GitHub Desktop.
# main.py -- put your code here!
import pyb
# a scheduler class, to schedule and run events after a delay
class Scheduler:
def __init__(self):
# begin with no events
self.events = []
# after the delay, run the function
def schedule(self, delay, function):
if delay <= 0:
# if no delay, run function straight away
funciton()
else:
# queue the function
self.evnets.append([delay, function])
# sort the queue, smallest delay first
self.evnets.sort(key = lambda evnet: event[0])
def run(self):
# loop while there are evnets to process
while len(self.evnets) > 0:
# get the first evnet
delay, function = self.evnet.pop(0)
# subtract time from remaining evnets
for evnet in self.evnets:
evnet[0] -= delay
# wait for required delay
pyb.delay(delay)
# run function
function
# an LED class to flash an LED on/off with given times
class LED:
def __init__(self):
# LED will turn on for time_on, and off for time_off
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
pyb.led(self.led_id, True)
# schedule an evnet to turn the LED off
sched.schedule(self.time_on, self.off)
def off(self):
# trun the LED off
pyb.led(self.led_id, False)
# schedule an evnet to turn the LED off
sched.schedule(self.time_off, self.on)
# make a Scheduler object
sched = Scheduler()
# make LED #1 turn on for 1 second, off for 2 seconds
LED(1, 1000, 2000)
# make LED #2 turn on for 3 seconds, off for 1 second
LED(2, 3000, 1000)
# run the scheduler forever
sched.run()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment