Interrupt handler behaviour

The official pyboard running MicroPython.
This is the reference design and main target board for MicroPython.
You can buy one at the store.
Target audience: Users with a pyboard.
Post Reply
markp
Posts: 2
Joined: Sun Jul 27, 2014 11:24 am

Interrupt handler behaviour

Post by markp » Sun Jul 27, 2014 11:48 am

Hi,
The following code causes an error

Code: Select all

x1_pin = pyb.Pin.board.X1
x1 = pyb.Pin(pyb.Pin.board.X1)
counter = 0

def x1_callback(line):
  print(x1.value())
  counter += 1

extint = pyb.ExtInt(x1_pin, pyb.ExtInt.IRQ_RISING_FALLING, pyb.Pin.PULL_UP, x1_callback)
>>> 0
Uncaught exception in ExtInt interrupt handler line 0
NameError:

If the counter increment is removed the code works. Is this a bug?
If not, how do you access variables from inside the callback?

User avatar
dhylands
Posts: 3821
Joined: Mon Jan 06, 2014 6:08 pm
Location: Peachland, BC, Canada
Contact:

Re: Interrupt handler behaviour

Post by dhylands » Sun Jul 27, 2014 5:36 pm

There is, in fact, an error in your script. If you try to run x1_callback directly:

Code: Select all

import pyb

x1_pin = pyb.Pin.board.X1
x1 = pyb.Pin(pyb.Pin.board.X1)
counter = 0

def x1_callback(line):
  print(x1.value())
  counter += 1

x1_callback(3)
#extint = pyb.ExtInt(x1_pin, pyb.ExtInt.IRQ_RISING_FALLING, pyb.Pin.PULL_UP, x1_callback)
then you'll get the following error:

Code: Select all

>>> import irq_var
0
Traceback (most recent call last):
  File "<stdin>", line 0, in <module>
  File "1://irq_var.py", line 11, in <module>
  File "1://irq_var.py", line 9, in x1_callback
NameError: local variable referenced before assignment
You need a "global counter" statement in your callback. I modified your script to use the global and to use SW instead of X1 (just so I could use the user switch for testing):

Code: Select all

import pyb

x1_pin = pyb.Pin.board.SW
x1 = pyb.Pin(pyb.Pin.board.SW)
counter = 0

def x1_callback(line):
  global counter
  counter += 1
  print("val:", x1.value(), "counter:", counter)

extint = pyb.ExtInt(x1_pin, pyb.ExtInt.IRQ_RISING_FALLING, pyb.Pin.PULL_UP, x1_callback)
and now I get this output:

Code: Select all

Micro Python v1.2-37-gea37daf-dirty on 2014-07-26; PYBv1.0 with STM32F405RG
Type "help()" for more information.
>>> import irq_var
>>> val: 0 counter: 1
val: 1 counter: 2
val: 0 counter: 3
val: 1 counter: 4
val: 0 counter: 5
val: 0 counter: 6
val: 1 counter: 7
val: 0 counter: 8
val: 0 counter: 9
val: 0 counter: 10
val: 1 counter: 11

markp
Posts: 2
Joined: Sun Jul 27, 2014 11:24 am

Re: Interrupt handler behaviour

Post by markp » Mon Jul 28, 2014 9:23 am

Thanks for the python lesson, my code now works as it should.

Post Reply