Interrupt not working on Arduino Mega

Hi all,

I'm using rotary encoders for my project. Firstly, I wanted to test if the encoders work. However, it seems that the interrupt is not working as it just displays "0" and hence not changing states. This is the code I'm running. I've also tried using the other interrupt pins but it results in the same problem.

const int enc_pin = 18;
unsigned long ticks = 0;

void setup(){
	pinMode(enc_pin, INPUT_PULLUP);
	attachInterrupt(digitalPinToInterrupt(enc_pin), countTicks, CHANGE);

void loop(){

void (countTicks){
	ticks ++;

ticks needs defining as volatile as it's being shared between the interrupt code and the main loop.

volatile unsigned long ticks = 0;

Thanks for the reply Riva.

I tried using Volatile but its still stuck on 0.


void (countTicks){

This is not valid code. It should be:

void countTicks(){

Accessing the unsigned long won't be atomic on an 8-bit AVR. You need to protect it with a critical section:

void loop() {
  unsigned long localTicks;

  localTicks = ticks;

Thanks for the replies.

I tried your methods, but it was still stuck on "0". However, once I changed the:

pinMode(enc_pin, INPUT_PULLUP); to pinMode(enc_pin, INPUT); it works. But I'm not sure why this makes it work.

But I'm not sure why this makes it work.

It's about the wiring which you chose to make us try to guess about. I guess we didn't guess correctly how you had your encoder connected. Next time show it.