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
pinMode(buttonPin,INPUT_PULLUP);
pinMode(ledPin1,OUTPUT);
pinMode(ledPin2,OUTPUT);
pinMode(ledPin3,OUTPUT);
//create interrupt for button
attachInterrupt(digitalPinToInterrupt(5),count,CHANGE);
Serial.begin(9600);
}
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); }
delay(500);
Serial.print(digitalRead(buttonPin));
}
//count occurs when button is pressed
void count(){
//incremement a counter
value++;
//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.