Home‎ > ‎Unit 07‎ > ‎

Introduction to the Pushbutton

Arduino Pins 0-13 can be used as inputs or outputs. So far we've only used them as outputs. You set the pin to be an input in a similar fashion to setting the pin
mode to an output as we've done in previous lessons.

You will need to build the circuit shown in the diagram. Pin 2 will be looking for an input of either HIGH or LOW. digitalRead looks to see whether we have positive or negative voltage on the pin of interest. If it is positive it is HIGH or one, if it is negative it is LOW or zero. Technically you don't need the 100 ohm resistor. It's there to protect the Arduino board (and your USB port) from a short circuit.

The size of the two resistors are not critical. They are a rough guide. The 10k resistor can be as small as 4.7k and there is really no maximum, but if it is too big the results can be unpredictable. The presence of the 10K resistor is critical, it is called a pull down resistor. There are three possible states an input can be: High (positive), Low (negative), or nothing. Unfortunately, the Arduino has only two choices, High or Low. If you leave out the pull down resistor the pin can never "see" Low and the results will be totally unpredictable. It might appear to work perfectly one moment and then suddenly not work. If you were to simply put a wire in for the 10k ohm resistor then you'd cause a short circuit any time you pressed the button.

Try out this code:

import processing.serial.*;

import cc.arduino.*;

Arduino arduino; 

int buttonPin = 2;
int buttonState;

void setup() {
  size(200, 200);    
  arduino = new Arduino(this, Arduino.list()[0], 57600);
  arduino.pinMode(buttonPin, Arduino.INPUT);

void draw()
  buttonState = arduino.digitalRead(buttonPin);
  if (buttonState == 1)
    background (255);
    background (0);

New Code
The function arduino.digitalRead(buttonPin) reads the state of buttonPin and returns either Arduino.HIGH or Arduino.LOW These have numerical values of 1 and 0 respectively. Also Notice that the arduino.pinMode is changed to Arduino.INPUT rather than Arduino.OUTPUT as it is for LEDs.
  • Run the program and observe how it works
  • Swap the positions of the wire and the 10k resistor attached to the push button (by this I mean plug the resistor into positive and the wire into negative). Run the program again. What do you see? Why is it different?
  • Add an LED to pin 10 on your Arduino (you should know ho to do this) and modify the program so that the Arduino also turns on and off the LED when the button is pressed.
Assignment 7.1 - Take your code from Assignment 4.4 and modify it. Change the mouse click into a button push.