Sunday, March 1, 2015

Debouncing Switches

Very often we need to connect some type of mechanical switch to an Arduino as an input device. Also very often, there is mechanical slop in a switch, so the arduino sees one activation of the switch as multiple activations. This is called switch bounce. You can write code that looks at the state of the switch, saves it to a variable and waits for a short period of time and looks again to see if the button is still pressed, or you can debounce in hardware and save code space and complexity.

The Ups and Downs of digital inputs - A digital input cannot be left floating (not connected to anything). If you are not activating the switch, it must be pulled down to LOW, or up to HIGH through a resistor. There are pullup resistors in the CPU that can be activated through the pinMode(pin, INPUT_PULLUP) command, or you can add a external resistor to the circuit.

By adding a small capacitor across the resistor, we eliminate switch bounce, as the capacitor charges during the press of the button, then slowly (from the microcontroller's point of view) discharges, enabling the microcontroller to see a single activation of the switch.

In the diagram above, if +5v is connected to the right pin, Gnd to the center, and the Signal is connected to a digital input, you have built a debounced switch in pulldown configuration, meaning the arduino will see a LOW unless the switch is pushed. If Gnd is connected to the right pin, +5v connected to the center, and the signal pin is connected to a digital input, the Arduino will read a HIGH unless the switch is pushed. The capacitor ensures only one activation is read per push.


bool val;
inPin = 3; // Arduino pin "signal" is attached to

void setup() {

  pinMode(inPin, INPUT);      // sets the digital pin inPin as input

}

void loop() {

  val = digitalRead(inPin);   // read input pin inPin
  if (val == HIGH) {  // Check for HIGH if in pulldown, or check for LOW if in pullup.
  //do something
  }

}


Collaborate, and Simulate!

As part of our new technical support service, we have been using a new tool called 123circuits. It's an online circuit and arduino sketch simulator that allowed us to have multiple users online and sharing the same virtual breadboard and arduino. We were able to explain the operation and configuration of a transistor vs. a MOSFET with a working sketch so the customer could see a working motor speed up and slow down according to the sketch being written. It's a very useful tool for one person, or several.