DEV Community

Cover image for That Arduino Pin Can't Interrupt
xtofl
xtofl

Posted on

That Arduino Pin Can't Interrupt

I thought it would be easy to couple a button to my Arduino Gemma.

However, it just didn't work. I've read the whole page on attachInterrupt but apart from a hunch that maybe some pins can't be used for interrupts, I got nothing.

So I had to dive into the code, where I found this little snippet (Arduino.h)

#define NOT_AN_INTERRUPT -1
Enter fullscreen mode Exit fullscreen mode

And in $HOME/.arduino15/packages/arduino/hardware/avr/1.8.5/variants/gemma/pins_arduino.h, I read this:

#define digitalPinToInterrupt(p) \
   ((p) == 2 ? 0 : NOT_AN_INTERRUPT)
Enter fullscreen mode Exit fullscreen mode

So here's an idea for you: add a little snippet to your sketch:

template<int PIN>
constexpr int interruptFor() {
  constexpr auto i = digitalPinToInterrupt(PIN);
  static_assert(i != NOT_AN_INTERRUPT,
     "board can't use this pin for an interrupt");
  return i;
}
Enter fullscreen mode Exit fullscreen mode

And use this function instead:

namespace my_wiring {
  constexpr auto BUTTON_PIN = 2;
}

constexpr auto BUTTON_INTERRUPT =
  interruptFor<my_wiring::BUTTON_PIN>();
Enter fullscreen mode Exit fullscreen mode

Now, on my Gemma (with an ATtiny85), when I change my BUTTON_PIN to e.g. 1:

sketch_aug14a.ino: In instantiation of
  'constexpr int interruptFor() [with int PIN = 1]':
sketch_aug14a/sketch_aug14a.ino:19:70:   required from here
sketch_aug14a/sketch_aug14a.ino:11:3: error: static assertion failed:
   board can't use this pin for an interrupt

   static_assert(i != NOT_AN_INTERRUPT,
   ^~~~~~~~~~~~~
Enter fullscreen mode Exit fullscreen mode

That would have been a time saver! Maybe I'll propose to introduce this in the arduino headers, too. When I have time.

Top comments (0)