header
Back to Tutorials Page
  

 
 
DIGITAL INPUT TUTORIAL::

This Demo uses the circuit from the LED BLINK Example, but replaces the Delay Function code control of the LED with the use of a N/O (normally open) pushbutton switch to turn the LED on and off. When the button is pressed, the Digital Input is set LOW and the LED is turned on (by setting the DIGITAL OUTPUT pin HIGH). When the button rests in its normally open state, the Digital Input is HIGH and the LED is turned off (by setting the DIGITAL OUTPUT pin LOW).

To wire this circuit, we connect one leg of the pushbutton switch to Pin 8 on the ARDUINO board. This same leg of the pushbutton is connected to one leg of a 10K OHM resistor and the other leg of the resistor is connected to +5VDC. The other leg of the switch is connected directly to GROUND. In our code, we will set Pin 8 to be an INPUT and we will continuously scan and read the state of this pin. When the button is at rest in its Normally Open State, Pin 8 is connected to +5VDC through our pull-up resistor. Input 8 is now HIGH and will tell the ARDUINO to leave the LED OFF.

When the Button is pressed, a connection between Pin 8 and GROUND will be made and the Input will be in a LOW State. The connection to +5VDC through the pull-up resistor will be ignored, because electricity will always follow the path of least resistance. Without the use of the pull-up resistor to +5VDC, when the button was not pressed, Input Pin 8 would be in a floating state (neither HIGH nor LOW) and could cause erratic readings of its state.

Connect the Anode (Long Lead) of the LED to Digital Pin 13, with the other lead of the LED connected to a 270 OHM Resistor to Ground (Reference the LED Blink Tutorial for additional information).

CODE:

// BUTTON: Digital In/Out DEMO

// This example turns an LED connected to PIN 13 on the ARDUINO on when Button
// connected to Pin 8 is pressed and turns off LED when Button is released

int ledPin = 13; // declare variable for Digital Pin LED is connected to
int buttonPin = 8; // declare variable for Digital Pin Button is connected to
int buttonState = 0; // declare variable for reading Input Pin status

void setup(){
pinMode(ledPin, OUTPUT); // sets Digital Pin 13 as an OUTPUT
pinMode(buttonPin, INPUT); // sets Digital Pin 8 as an INPUT
}

void loop()
{
  buttonState = digitalRead(buttonPin); // read state of buttonPin
  if (buttonState == HIGH) // check if the input is HIGH (button not pressed)
  {
    digitalWrite(ledPin, LOW); // turn off the LED
  }
  else   // button is pressed and buttonState==LOW
  {
    digitalWrite(ledPin, HIGH); // turn on the LED
  }
}


References:
www.arduino.cc/en/Tutorial/Button

 

DIGITAL INPUT BREADBOARD CIRCUIT

digital input breadboard circuit

 

 

DIGITAL INPUT SCHEMATIC

digital input schematic