I recently bought a mega 2560 to toy around with as a hobby. It's pretty fun so far, but I've recently gotten stuck while trying to use attachInterrupt with a button. I'm using the CHANGE mode, and have read the documentation pretty thoroughly ( I think ).

I've looked up multiple questions and tried to fix my setup and I still can't seem to make it work.

Here's my code:

int buttonPin = 18;
int ledPin1 = 11;
int ledPin2 = 9;
int ledPin3 = 5;

int value = 0;

void setup() {
  //declare inputs and outputs

  //create interrupt for button


void loop(){
  if(value == 0){ digitalWrite(ledPin1,HIGH);}
  else{ digitalWrite(ledPin1,LOW); }

  if(value == 1){ digitalWrite(ledPin2,HIGH);}
  else{ digitalWrite(ledPin2,LOW); }

  if(value == 2){ digitalWrite(ledPin3,HIGH);}  
  else{ digitalWrite(ledPin3,LOW); }



//count occurs when button is pressed
void count(){
  //incremement a counter
  //reset counter from 3 to 0
  if(value >= 2){ value = 0; }

It's a pretty simple sketch. I'd attach a picture of my current setup but I don't really think It's needed. The button is indeed working as I'm debugging using serial.print().

If not clear, the objective of the sketch is to change the LED lit when the button is pressed. Currently, the variable value is stuck at 0.


1 Answer 1

//create interrupt for button

The code does not match the comment.

  • Thanks. This doesn't quite make sense to me though, the documentation for attachInterrupt says I should use 5 instead of 18... arduino.cc/reference/en/language/functions/external-interrupts/…
    – Howard P
    Commented May 29, 2018 at 1:47
  • I'd like to upvote your answer but I'm not high enough in reputation
    – Howard P
    Commented May 29, 2018 at 1:47
  • It says if you are going to use the interrupt number instead, that you should use 5. But then you wouldn't use digitalPinToInterrupt(), since that is already the interrupt number. It also recommends that you don't use the interrupt number. Commented May 29, 2018 at 1:52
  • Silly mistake for me to make. Thanks again for the help!
    – Howard P
    Commented May 29, 2018 at 1:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.