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.

Jetbrains image

Don’t Become a Data Breach Headline

57% of organizations have suffered from a security incident related to DevOps toolchain exposures. Is your CI/CD protected? Check out these nine practical tips to keep your CI/CD secure—without adding friction.

Learn more

Top comments (0)

Image of Quadratic

Free AI chart generator

Upload data, describe your vision, and get Python-powered, AI-generated charts instantly.

Try Quadratic free

👋 Kindness is contagious

Dive into this informative piece, backed by our vibrant DEV Community

Whether you’re a novice or a pro, your perspective enriches our collective insight.

A simple “thank you” can lift someone’s spirits—share your gratitude in the comments!

On DEV, the power of shared knowledge paves a smoother path and tightens our community ties. Found value here? A quick thanks to the author makes a big impact.

Okay