Saturday, May 04, 2013

Using Switches with Arduino and Processing

The short story here is you can use INPUT_PULLUP when coding switches in Arduino but this is not available at the time of this post in the Arduino library for Processing if you want to code your switch that way. In the latter case you have to wire your switch with a pull-up or pull-down resistor.

Now the long story. The Arduino IDE 1.0.1 forward has added a very convenient argument to the pinMode() function for using switches. Instead of just setting a switch pin to pinMode(switchPin, INPUT) you can use pinMode(switchPin, INPUT_PULLUP). This uses the Arduino's internal resistors to pull a switch pin HIGH by default so you don't get fluctuating readings on your switch. The switch is really easy to wire this way, just wire from the input pin to the switch, then to ground. When you want to read whether the switch is pressed, use the condition if(digitalRead(switchPin==LOW)).
Image source:
But the INPUT_PULLUP option is not available in the current arduino library for Processing, which allows Processing to talk to the Arduino through the Firmata firmware running on the Arduino. The Processing arduino library hasn't been updated since 2011 (11/11/11 to be exact--weird).

Without the use of the INPUT_PULLUP argument a switch has to be wired with a pull-up or pull-down configuration, which is a bit more complicated. This Ladyada tutorial covers the wiring of pull-up and pull-down resistors very nicely. The image below uses a pull-up resistor, in which the switch is connected on one side to its input pin with a 100 ohm resistor and to Vin with a 10K ohm resistor, and then to ground on its other side, pulling it high by default.
Image source:
All of this came up in my classroom because I have a couple students working on a project where they want to press buttons to play audio files on their computer. So the Processing/Arduino configuration is necessary.