Hi, I've written a small sketch which increments the value of an integer (known as scene) every time a button is pressed. once the value of scene reaches <5 it loops back round to zero.
here is the sketch (which works)...
int scene = 0;
int buttonState = 1;
int lastButtonState = 1;
int buttonPin = 19;
void setup() {
Serial.begin(9600);
pinMode(buttonPin, INPUT_PULLUP);
}
void loop() {
buttonState = digitalRead(buttonPin);
if(buttonState != lastButtonState && buttonState == 0){
scene++;
}
lastButtonState = buttonState;
if(scene == 5){
scene = 0;
}
Serial.println(scene);
delay(20);
}
I would now like to put this into a function as I would like to use it many times for buttons on different pins. However, I'm new to functions and am struggling. For some reason instead of the value of scene incrementing once each time i press the button, it rapidly loops through values: 0 - 4 for the entire time that I hold the button down... and then stops again when I let go
here is my attempt at the function (not working): -
int scene = 0; // i would like scene to remain global as other functions need to access this later
int getScene(int buttonPin){
int buttonState = 1;
int lastButtonState = 1;
buttonState = digitalRead(buttonPin);
if(buttonState != lastButtonState && buttonState == 0){
scene++;
}
lastButtonState = buttonState;
if(scene == 5){
scene = 0;
}
}
void setup(){
Serial.begin(9600);
pinMode(19, INPUT_PULLUP);
}
void loop(){
getScene(19);
Serial.println(scene);
delay(20);
}
any help here would be massively appreciated.
Thanks