nvco
May 24, 2020, 7:51am
1
Dear Users,
I just wanted to code an Button, which counts how often it gets pressed.
Code:
void setup()
{
pinMode(4, INPUT_PULLUP);
Serial.begin(9600);
int ButtonCounter = 0;
}
void loop()
{
int ButtonStatus4 = digitalRead(4);
if (ButtonStatus4 == 0){
int ButtonCounter + 1;
Serial.println(ButtonCounter);
}
}
And I get the error message:
In function 'void loop()':
14:23: error: expected initializer before '+' token
15:20: error: 'ButtonCounter' was not declared in this scope
Can someone help me?
Best regards,
Nvco
nvco
May 24, 2020, 7:56am
2
I found a solution for the error message but now I have another problem
My Code:
int ButtonCounter = 0;
void setup()
{
pinMode(4, INPUT_PULLUP);
Serial.begin(9600);
}
void loop()
{
int ButtonStatus4 = digitalRead(4);
if (ButtonStatus4 == 0){
ButtonCounter + 1;
Serial.println(ButtonCounter);
}
}
If I press the Button I just get 0 in the output until I stop pressing it.
Hope somebody can help me
It will work as written but won't do what you want because you are detecting when the input is LOW rather than when it becomes LOW
Take a look at the StateChangeDetection example in the IDE
And you also need 'ButtonCounter = ButtonCounter + 1' (or the short form 'ButtonCounter += 1').
If you just say 'ButtonCounter + 1' that adds 1 but then throws the result away.
Steve
nvco:
Thanks, I fixed it.
For the sake of anyone with a similar problem finding this thread in future please post your fixed sketch and maybe an explanation of the changes that you made and why
You had better debounce for button . If not, it may count wrongly.