here, instead of a push button though, i am using a toggle switch(not by choice, i was asked to use a toggle switch instead of a push button) but every time i press it, one starts to get added rapidly non stop until i change the state of the switch. so i want to change it to so that 1 gets added only once every time the switch is pressed, what should i add/change in my code?
thank you. but i want it to be so that no matter what kind of switch is used, every time i press the button, 1 gets added only once. will State Change Detection work regardless for it all?
Normally with state change of a push button, you would increase the counter when the state changes either from high to low, or from low to high, but not both. With a toggle switch you would increment the counter when the switch state changes from high to low and from low to high.
With your toggle swich connected at DPin-4 with external pull-down resistor, you read the switch for closed condition, wait for the bouncing time and read it again to see that it is still closed and them add 1 with your counter.
Now, check that the swtch is opened and wait until the switch is settled at opened condition.
Repaet.
Exercise the following sketch to understand the above principle: (You must make the sketch non-blocking if you have some other tasks to do simultaneously.)
byte count = 0;
void setup()
{
Serial.begin(9600);
pinMode(4, INPUT); //with 2k externalpull-down
while (true)
{
while (digitalRead(4) != HIGH)
{
; //wait
}
delay(20); //bouncing time, theoretically it is 20 - 50 ms
if (digitalRead(4) == HIGH)
{
Serial.print(++count);
}
while (digitalRead(4) != LOW)
{
; //wait
}
}
}
void loop() {}
That's a good point. For old timers, among whom I must now think seriously about numbering myself cough!, there's lotsa stuff that should be learned and struggled with before (if ever) switching to someone else's code or library.
State change detection and switch debouncing may not need to be struggled with, but both do drag you over some of the things that will come up in many disgraces with this kind of small scale or embedded programming.
Where programmers who know all there is to need to know about some things but are baffled at turning on and off an LED with a pushbutton.