Arduino Basics: Digital Input (Buttons, Switches, and Sensors)
Table of Contents
Digital inputs allow your Arduino to read the state of external devices, such as buttons, switches, or sensors, which can be either HIGH (ON) or LOW (OFF).
Reading Digital Inputs
Use the digitalRead()
function to check the state of a pin:
HIGH
– The input pin is receiving voltage (usually 5V).LOW
– The input pin is connected to ground (0V).
Example:
int buttonPin = 2;
int buttonState = 0;
void setup() {
pinMode(buttonPin, INPUT); // Set pin as input
Serial.begin(9600); // Optional: for debugging
}
void loop() {
buttonState = digitalRead(buttonPin); // Read the button
Serial.println(buttonState); // Print HIGH or LOW
delay(100);
}
Floating Inputs and Pull-up / Pull-down Resistors
If a digital input pin is not connected to HIGH or LOW, it may "float," causing unpredictable readings. To prevent this, use pull-up or pull-down resistors:
- Pull-up resistor: Connects the pin to VCC (HIGH by default). Pressing a button connects it to GND (LOW).
- Pull-down resistor: Connects the pin to GND (LOW by default). Pressing a button connects it to VCC (HIGH).
Arduino provides internal pull-up resistors that can be enabled in code:
pinMode(buttonPin, INPUT_PULLUP);
This eliminates the need for an external resistor.
Example: Button-Controlled LED
int ledPin = 13;
int buttonPin = 2;
int buttonState = 0;
void setup() {
pinMode(ledPin, OUTPUT);
pinMode(buttonPin, INPUT_PULLUP); // Enable internal pull-up resistor
}
void loop() {
buttonState = digitalRead(buttonPin);
if (buttonState == LOW) { // Button pressed (active low)
digitalWrite(ledPin, HIGH); // Turn LED on
} else {
digitalWrite(ledPin, LOW); // Turn LED off
}
}
Tips for Digital Input
- Always label pins clearly for readability.
- Use pull-up or pull-down resistors to avoid floating pins and false readings.
- Debounce buttons in software if rapid presses cause multiple readings.
- Test input with Serial Monitor to confirm proper behavior before connecting other devices.
Mastering digital inputs allows your Arduino to interact with the environment, respond to user actions, and make decisions in your projects based on sensor or button states.