In all of my embedded projects, I like to have what I call a heartbeat LED. So I typically use that as a hello world program.
Here's the basic heartbeat program (not interrupt driven):
Code: Select all
import pyb
tick = 0
led = pyb.LED(4) # 4 = Blue
while True:
if tick <= 3:
led.toggle()
tick = (tick + 1) % 10
pyb.delay(100)
Code: Select all
import heartbeat
This is the interrupt driven version, which I called heartbeat_irq.py:
Code: Select all
import pyb
class Heartbeat(object):
def __init__(self):
self.tick = 0
self.led = pyb.LED(4) # 4 = Blue
tim = pyb.Timer(4)
tim.init(freq=10)
tim.callback(self.heartbeat_cb)
def heartbeat_cb(self, tim):
if self.tick <= 3:
self.led.toggle()
self.tick = (self.tick + 1) % 10
Heartbeat()
When you import heartbeat_irq you'll notice that you get your REPL back, and the blue LED is continuing to blink. You can execute other commands.
While I was coding this up, I noticed that errors in the exception handler aren't being reported properly. I had forgotten the self on the call to led.toggle. So it looked like this:
Code: Select all
def heartbeat_cb(self, tim):
if self.tick <= 3:
led.toggle()
self.tick = (self.tick + 1) % 10
Code: Select all
>>> import heartbeat_irq
Uncaught exception in Timer(4) interrupt handler
MemoryError:
So I commented out the call to tim.callback, and then invoked the callback manually:
Code: Select all
>>> import heartbeat_irq
>>> hb = heartbeat_irq.Heartbeat()
>>> hb.heartbeat_cb(None)
Traceback (most recent call last):
File "<stdin>", line 0, in <module>
File "0://heartbeat_irq.py", line 14, in heartbeat_cb
NameError: name 'led' is not defined
I also noticed that while at the REPL with heartbeat_irq running, if I press Control-D, the REPL tends to lockup, and I have to press RESET to get control back. I think that this is because the IRQ is continuing to run, however, the callback is no longer present. I'll file a bug report to get that fixed.
I'd also like to see uncaught IRQ exceeptions reported like the ones in REPL. I tried the following:
Code: Select all
def heartbeat_cb(self, tim):
try:
if self.tick <= 3:
led.toggle()
self.tick = (self.tick + 1) % 10
except BaseException as err:
print(err.__class__.__name__, ":", str(err))
#raise err