I'm very new to Arduino, and programming in general, in fact.
I wanted a toggle switch, but all I have are some push-to-break momentary buttons.
Did lots of searching and couldn't find anyone else skint enough to not be able to afford a toggle switch.
My biggest problem was that more than one value is returned during the time the button is being pushed.
I came up with this:
int buttonState = 1;
int lastButtonState = 1;
int changed = 0;
int amount = 1;
void setup(){
pinMode(13, INPUT);
Serial.begin(9600);
}
void loop(){
lastButtonState = buttonState;
buttonState = digitalRead(13);
if (lastButtonState == 0 & buttonState ==1){
if (changed == 0){ amount = 1; }
else { amount = -1; }
changed += amount;
}
Serial.println(changed);
}
It works well enough, and seems pretty solid, but it feels awfully convoluted.
What can I change to make it simpler?
Thanks
boolean latch = false;
void loop()
{
if(digitalRead(buttonPin) == HIGH) // Look at button state
{
latch = !latch; // Changing state
latch ? digitalWrite(13,HIGH) : digitalWrite(13,LOW); // If latch is true, on board LED is ON, else OFF
}
}
You need to detect transitions on the input state and only toggle the latched state when the input changes from high to low - or vice versa if you prefer.
As it is, the latched state will keep flipping each time loop runs, and will probably flip thousands of times when you just hold the button down briefly.
You need to detect transitions on the input state and only toggle the latched state when the input changes from high to low - or vice versa if you prefer.
As it is, the latched state will keep flipping each time loop runs, and will probably flip thousands of times when you just hold the button down briefly.
This is true, I did not include a way to detect "button state change". That example is provided to you in your IDE. It is only a few more lines though.