When you turn on a switch, it rarely just goes from off to on. Instead it "bounces" between off and on a few times before settling down to on. If you are "clicking" your switch by touching a wire to one end of a resistor, you should expect to see many bounces.
Let's try to measure the number of bounces for a switch change. You'll need to add at least two variables. One would keep up with the present state of the input and the other with the number of bounces.
int lastInput ; int bounces = 0 ;
You'll need to initialize the lastInput
variable within the
setup
routine,
where you also need to call Serial.begin
to initialize the serial I/O package.
Within the loop
routine
you can increment bounces
whenever
the input changes and occasionally print out the updated bounce count.
You'll maximize bounces by touching (and then holding) the ground wire to the resistor leg connected to the input port. Pushing the write into a breadboard hole is far less bouncy. I've seen as many as 250 bounces on one switch change.
If your code is detecting very few bounces, it probably isn't working correctly.
In particular, if your program prints out the bounce count whenever there is an input change,
it will miss many bounces while executing Serial.println
.
A better way to do this is to call
millis
every time loop
is run and only print the bounce count once a second.
To do this, declare a new global variable, say timeLastPrinted
.
In setup
call millis
to give
timeLastPrinted
an initial value.
On every call of setup
, call millis
again and see if the present time is 1000 millisecond greater than
the time stored in timeLastPrinted
.
If it is, print the bounce count and update timeLastPrinted
.
As it turns out, the use of SPST switches are so common, the ATmega chip
allows you to
eliminate the resistor. Go ahead and remove it!
Now do something that seems odd. After calling
pinMode
to place your switch pin into
INPUT
mode,
call digitalWrite
to set the
"output" of the pin HIGH
.
pinMode(swtchPin, INPUT) ; digitalWrite(swtchPin, HIGH) ;
Writing HIGH
to an INPUT
pin, "connects" the pin to an
20k Ω resistor that is inside the ATmega chip.
That was thoughtful of those chip designers at ATmega.
Run your program again to convince yourself that the resistor is no longer needed.