Hi, I want know what's is wrong my code here. What I want is to have the first button click to add then revert back to last value on the second click. However when I do the first button click it also prints/run the second statement outputting "1 0" where it should 1 first then 0. Thank you
const int buttonPin = 2;
int buttonState = 0;
int currentState = 0;
it's more convention to have a single block of code the detects a button press which then performs whatever action if required depending on state versus having separate blocks for each state.
enum { Off = HIGH, On = LOW };
#undef MyHW
#ifdef MyHW
const int buttonPin = A1;
#else
const int buttonPin = 2;
#endif
int buttonState = Off;
int currentState;
void setup() {
pinMode(buttonPin, INPUT_PULLUP);
Serial.begin(115200);
}
void loop() {
byte but = digitalRead(buttonPin);
// detect change in state
if (buttonState != but) {
buttonState = but;
// process button press
if (On == buttonState) {
// toggle state
currentState = ! currentState;
Serial.println(currentState);
}
delay (10); // debounce
}
}
Thank you for the response GCJR code works fine. However how can I insert my command that If currentState = 0 then do this if currentState = 1 then do this. I want to dit it with one button only that's why I have this currentState++; and currentState--; so it would increment and decrement after successful click. Please help thank you
void loop() {
buttonState = digitalRead(buttonPin); // Read the button, save in buttonState.
if (buttonState != HIGH) { // If its not high.. Or if its LOW (grounded)
if (currentState == 0) { // If current state = 0..
currentState++; // Bump up current state.
Serial.println(currentState); // Let the user see what we have.
} else { // Else, current state was = 1..
currentState--; // Pop one off current state.
Serial.println(currentState); // Show Mrs user what we got.
}
while (!digitalRead(buttonPin)) { // While the button is being held down..
delay(500); // Waste a 1,000 years.
if (!digitalRead(buttonPin)) { // Are they done yet?
Serial.println("Let go of the damn button!"); // Yell at the user.
}
}
}
}