Can't get simplest pin change interrupts working on Nano V3

This is a really basic question.

I can't get the simplest pin change interrupt code working. I'm using an Elegoo Nano V3. I'm trying to detect a pin change on D4, but seeing conflicting info online.

Does the Nano have PCIE0, PCIE1 and PCIE2?
Do I need to enable the pin as an input first?
Am I using the correct pin numbers? (Board numbers that go up to about 30 vs printed numbers like D4 vs PCINT numbers)

void setup() { 

  // Input pin
  pinMode(4, INPUT_PULLUP);

  // Enable pin change interrupts on PCIE2 (Port B)
  PCICR |= B00000100;

  // Monitor PCINT20 (D4)
  PCMSK2 |= B00010000;

 } 

 void loop() { 
  
 }

 ISR (PCINT2_vect) {
  Serial.println("Interrupt!");
 }

This code doesn't even try to differentiate which pin was changed. But absolutely nothing happens. Is Serial available from ISR. I've experimented with different combinations of pins and ports.

What basic thing am I missing?

1 Like

You're at least missing a Serial.begin(), so printing will not work. Printing should work after that. You can also simply flash the built-in LED in the ISR.

Notes:

  1. Comments that don't match the statement are not useful (PCICR 0x04 is for port D, not port B) and confusing :wink:
  2. Just in case, Arduino Pin Change Interrupts – The Wandering Engineer
1 Like

You could start with something that works: https://github.com/GreyGnome/EnableInterrupt

The Wokwi simulation seems to have implemented the PCINT. It works with the EnableInterrupt library.

// Inspiration from the "Simple.ino" example from 
// the EnableInterrupt library.

#include <EnableInterrupt.h>

const int buttonPin = 7;
volatile unsigned long interruptCount;

void interruptFunction() 
{
  interruptCount++;
}

void setup() 
{
  Serial.begin(115200);
  Serial.println("Does the button really bounce ?");
  pinMode(buttonPin, INPUT_PULLUP);
  enableInterrupt(buttonPin, interruptFunction, CHANGE);
}

void loop() 
{
  Serial.print("Pin was interrupted: ");
  Serial.print(interruptCount, DEC);
  Serial.println(" times so far.");
  delay(1000);
}

Try it yourself in Wokwi:

Serial from an interrupt is asking for trouble.

Thanks all. Chopped and changed way too many things at once while forgetting Serial.begin()

@shaciaran
Have you removed the Serial.println() from the ISR() routine? If yes, then do you know the reason?

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