Digital Input Pull-Up resistor
This example demonstrates the use of pinMode(INPUT_PULLUP). It reads a digital input on pin 2 and prints the results to the serial monitor.
Hardware Required
Arduino Board
pushbutton
hook-up wires
breadboard
Circuit
Connect the pushbutton between pin 2 and ground, without any resistor as reference to 5V thanks to the internal pull-up.
click the image to enlarge
Schematic
click the image to enlarge
image developed using Fritzing. For more circuit examples, see the Fritzing project page
Code
/*
Input Pull-up Serial
This example demonstrates the use of pinMode(INPUT_PULLUP). It reads a digital
input on pin 2 and prints the results to the Serial Monitor.
The circuit:
- momentary switch attached from pin 2 to ground
- built-in LED on pin 13
Unlike pinMode(INPUT), there is no pull-down resistor necessary. An internal
20K-ohm resistor is pulled to 5V. This configuration causes the input to read
HIGH when the switch is open, and LOW when it is closed.
created 14 Mar 2012
by Scott Fitzgerald
This example code is in the public domain.
http://www.arduino.cc/en/Tutorial/InputPullupSerial
*/
void setup() {
//start serial connection
Serial.begin(9600);
//configure pin 2 as an input and enable the internal pull-up resistor
pinMode(2, INPUT_PULLUP);
pinMode(13, OUTPUT);
}
void loop() {
//read the pushbutton value into a variable
int sensorVal = digitalRead(2);
//print out the value of the pushbutton
Serial.println(sensorVal);
// Keep in mind the pull-up means the pushbutton's logic is inverted. It goes
// HIGH when it's open, and LOW when it's pressed. Turn on pin 13 when the
// button's pressed, and off when it's not:
if (sensorVal == HIGH) {
digitalWrite(13, LOW);
} else {
digitalWrite(13, HIGH);
}
}
See Also
pinMode()
BlinkWithoutDelay - Blink an LED without using the delay() function.
Button - Use a pushbutton to control an LED.
Debounce - Read a pushbutton, filtering noise.
StateChangeDetection - Count the number of button pushes.
toneKeyboard - A three-key musical keyboard using force sensors and a piezo speaker.
toneMelody - Play a melody with a Piezo speaker.
toneMultiple - Play tones on multiple speakers sequentially using the tone() command.
tonePitchFollower - Play a pitch on a piezo speaker depending on an analog input.
Last revision 2015/08/11 by SM