###### Import the Timer library, so we can use interrupt and callback functions - ING ######
###### Timer instructions are here: Please read https://docs.micropython.org/en/latest/library/pyb.Timer.html
from machine import Timer
# Initialise the Red LED port, a toggle variable, and an instance of a "Timer".
ledRed = machine.Pin(21, machine.Pin.OUT)
toggleRed = False
redRate = Timer()
###### This is the RED interrupt routine. Keep it short so that it can then jump back to the main loop.
def redLED_interrupt(redRate):
global toggleRed
toggleRed = True
###### Initialise the Green LED port, a toggle variable, and an instance of a "Timer".
ledGreen = machine.Pin(2, machine.Pin.OUT)
toggleGreen = False
greenRate = Timer()
###### This is the GREEN interrupt routine. Keep it short so that it can then jump back to the main loop.
def greenLED_interrupt(greenRate):
global toggleGreen
toggleGreen = True
###### similarly, This is a fast clock interrupt routine,
fastClock = Timer()
counter1sec = 0
secondFlag = True
### using a flag called secondFlag to be asserted True every 1000 milliseconds.
def clockTicker_interrupt(fastClock):
global counter1sec, secondFlag
if counter1sec > 1000:
secondFlag = True
counter1sec = 0
else:
counter1sec = counter1sec+1
########### ACTION starts here! let's start the background timers, and wait in the while loop! ###########
redRate.init(freq=3,mode=Timer.PERIODIC, callback=redLED_interrupt)
greenRate.init(freq=8,mode=Timer.PERIODIC, callback=greenLED_interrupt)
fastClock.init(freq=1000,mode=Timer.PERIODIC, callback=clockTicker_interrupt)
count = 0
while 1:
# We can now do multiple things in the forground! AVOID using sleep delays
# Act on the Red led
if toggleRed == True:
ledRed.toggle()
toggleRed = False
# Act on the Green led
if toggleGreen == True:
ledGreen.toggle()
toggleGreen = False
# Act upon the 1 second rate stuff
if secondFlag == True:
if count == 5:
count = 1
print("\nlet's repeat:")
else:
count = count+1
print("Count to 5...", count)
secondFlag = False
######### Other routines in this forever loop can be added such as checking ADC inputs, updating OLED display, making tones, etc,
######### either using the existing timer flags, or create more! ING #########