Bounce Count


If you are a little rusty on your bounce technology, check out XXXX's YYY.

The task

Count the number of times a switch bounces and try to de-bounce it using the timing routines of the Arduino.

Subtask 0 -- the board

Wire up your Arduino with a single input switch. If you already have your Arduino working on another job, just choose one of its input switches for this task. You only need to use on pin for this assignment.

Subtask 1 -- the state of the pin

Add a single variable, that keeps up with the last input of your switch

int lastInput ;

Initialize lastInput within the setup routine, where you also need to call Serial.begin to initialize the serial I/O package.

Within the loop routine, check if the switch has changed, and print a message if it has.

You can maximize bounces by making a switch with a couple of wires that you touch and hold together. I've seen as many as 250 bounces on one switch change this way.

Subtask 2 -- Counting bounces

Now add another variable, let's say numBounces, that will count the number of bounces made by your switch. Print this number whenever, the switch changes.

Subtask 3 -- Really counting bounces

Do a little calculation to figure out how long it takes to print out 5 characters on a 9600 baud line. (Keep in mind that ASCII uses 7 bits to encode a single character.) That is a lot of computer cycles and, since your program prints out the bounce count whenever there is an input change, it will miss many bounces while executing Serial.println.

To fix this problem 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, of type unsigned long. In setup call millis to give timeLastPrinted an initial value. On every call of loop, 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.

By the way, this time-driven programming technique is very common in programming embedded systems and is sometimes called the "super-loop." We will return to it later in the course.

Test out your improved counting code. If you are not seeing several bounces each time you change the switch, something is probably wrong with your code.

Subtask 4 -- Software de-bouncing

Modify your program to implement software de-bouncing. There are certainly several ways to do this, but how about simply modifying your program so that it only recognizes switch changes that have been stable for a certain number of milliseconds. Have your program count only these stable changes.