Author Options:

Easyest way for a arduno interrupt to call a funtion? Answered

Hi, I am trying to build a arduino speedometer for my go kart. I need a function that is called everytime a pin goes from low to high using a reed switch.

The curcumfrence of the wheel is about 1m.
The absoltue maximum this kart will be able to go is about 100km/h (28m/s).
So the arduino pin will need to be able to be read 28 times every second.

What is th best way to make the arduino call a function on a pin that needs to be read at least 28 times per second?


If its not a Due, you can only use external interrupts on Digital pin 2 and 3. You use the AttachInterrupt command to tell the program what to call, and when to call it.


The Due has more interrupts than the other variants.

A reed switch isn't the best choice for a sensor here. You'd be better with a Hall switch, just like the automakers use.

Arduino can interrupt on change of ANY input pin, not only 2 and 3.

The special case of pins 2 and 3 is you can have different interrupt routines for raisng edges (changes from 0 to 1) and a different one on falling edges (change from 1 to 0). The rest of the pins triggers the interrupts on every change and the software must read the input and determine what changed (if you read a 1, you can suppose it was a raising edge because if now there is 1, and there was a change... you can guess...) The only problem with it is that in very very fast changing pins, the program can read the pin after it changed again and fail to determine if it was a raising or falling edge.

I don't think that essentially polled interrupts are a particularly good approach, since the servicing time will be longer, and you should never hang around in an interrupt, but still, its nice to know, and thanks for the correction.

again...+1; darn you for being awake before me!

@any and david:
AttachInterrupt only makes an interrupt call to an ISR within a few clock cycles when using the external hardware interrupts; any other pins will be polled in software and might get missed.
You will virtually never miss a hardware ISR so long as the code within it is simple (set a flag, etc).

The Atmega328 can interrupt by hardware in any pin. They are called "pin change interrupts" and are available in ALL pins.


They ARE polled interrupts though - since 8 pins share one vector, and you have to work out HOW it changed too. They are slower than "proper" hardware interrupts

Yes, if you are monitoring more than one pin with the pin change interrupt, you will need to check which of them triggered it.

I'm making the distinction between true hardware interrupts and the other kinds. IIRC, the ONLY hardware interrupts are on 2 and 3.