Arduino Mega Interrupt pins

Hello,
I am a bit confused about the pins for interrupting with Arduino Mega 2560 R3 board. I need only one interrupt for my flow sensor. Examples show interrupt 0 and pin 2, so the part of the code would be :

byte FM_1_Interrupt = 0;                // 0 = digital pin 2

// and in the void setup
void setup(){

    // The Hall-effect sensor is connected to pin 2, which uses interrupt 0.
    // Configured to trigger on a FALLING state change (transition from HIGH state to LOW state)

    attachInterrupt(digitalPinToInterrupt(2), FM_1_PulseCount, FALLING);

here interrupt 0 triggers by pin 2 while the pinout diagram shows pin 21 for INT0.

Would you please clarify?
Thanks

The purpose of calling digitalPinToInterrupt() is to convert a given pin number to an interrupt number. Whether the returned interrupt is INT0 or INT4 is unimportant. If you would run the code on a UNO/NANO it would still work, but the interrupt would be INT0 instead of INT4.

In your snippet, you could replace digitalPinToInterrupt() with the interrupt number (4), and it would not make any difference - until the code is moved to a UNO/NANO, then it would break. It is about portability.

1 Like

That's what digitalPinToInterrupt() maps correctly. You can show the result of that function in the Serial monitor. It should be INT(4) on the Mega.

1 Like

Understood now. Thank you so much for your explanation.

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.