Digital Inputs, Floating Pins and Tactile Switch
Investigate raw digital readings, floating pins and reliable pull resistors before wiring and checking a tactile button. Finish by counting presses.
Lesson 5 · Read a digital input in Serial Monitor
Start with pin D2 configured as INPUT and no switch connected. Print the reading at 9600 baud.
const int inputPin = 2;
void setup() {
pinMode(inputPin, INPUT);
Serial.begin(9600);
}
void loop() {
Serial.println(digitalRead(inputPin));
delay(200);
}Lesson 6 · Why a disconnected pin floats
Remove the test jumper completely and watch Serial Monitor. A disconnected INPUT has no defined voltage, so it may show changing or apparently stable values. Neither is a reliable button reading.
External pull-down
Built-in pull-up
The UNO can hold the input HIGH internally, saving the external resistor. Now the switch goes between D2 and GND, and the meanings reverse.
void setup() {
pinMode(2, INPUT_PULLUP);
Serial.begin(9600);
}
void loop() {
Serial.println(digitalRead(2));
delay(200);
}Lesson 7 · Place and test the tactile switch
On a common four-leg tactile switch, the two legs on each side are permanently connected. Pressing joins the sides. Check your own switch with a continuity tester if its pin layout is unclear. Put it across the breadboard centre trench so the two sides sit on different sets of connected rows.
A ↔ B
Run the INPUT_PULLUP sketch above. Released should repeatedly print 1; pressed should print 0. If it always reads 0, inspect the breadboard rows and switch orientation.
Lesson 8 · Count presses in Serial Monitor
Once the input works, count new HIGH-to-LOW changes instead of repeatedly counting the entire time the switch is held.
const int buttonPin = 2;
int count = 0;
int previous = HIGH;
void setup() {
pinMode(buttonPin, INPUT_PULLUP);
Serial.begin(9600);
}
void loop() {
int current = digitalRead(buttonPin);
if (current == LOW && previous == HIGH) {
delay(30); // brief bounce check
if (digitalRead(buttonPin) == LOW) {
count++;
Serial.println(count);
}
}
previous = current;
}