Skip to main content

Read Digital Input with Pushbutton

🔰 Introduction​

In this project, you’ll learn how to use a pushbutton to read a digital input on Arduino UNO or ESP32. This project helps beginners understand how microcontrollers detect HIGH or LOW signals from components like buttons or switches.


🔧 Components Needed​

ComponentQuantityNotes
Arduino UNO or ESP321Any compatible board
Pushbutton1Momentary type
Resistor110kΩ for pull-down resistor
Breadboard1Optional but helpful
Jumper Wires4

📷 Circuit Diagram​

Pushbutton Circuit Diagram

🧩 Schematic Diagram​

Pushbutton Schematic Diagram

🛠️ Wiring Instructions​

  1. Place the pushbutton on the breadboard.
  2. Connect one leg of the pushbutton to digital pin 2.
  3. Connect the other leg of the pushbutton to GND.
  4. Place a 10kΩ pull-down resistor between digital pin 2 and GND.
  5. Plug the Arduino or ESP32 into your PC via USB.

🔍 What is digitalRead()?​

digitalRead() is a built-in Arduino function used to read the digital signal from a specified pin. It detects whether the pin is receiving a HIGH or LOW voltage.

➤ Syntax​

Syntax
int state = digitalRead(pin);
  • pin: The digital pin number to read
  • Returns: HIGH (1) or LOW (0)

🧾 Code​

digital-read-pushbutton.ino
#define BUTTON (2)

void setup() {
pinMode(BUTTON, INPUT); // Set pin 2 as input
Serial.begin(9600); // Start serial communication
}

void loop() {
int buttonState = digitalRead(BUTTON); // Read pin 2 state
Serial.println(buttonState); // Print state to Serial Monitor
delay(100); // Delay for stability
}

🧠 Code Breakdown​

void setup()
Runs once when the microcontroller starts.

Configures pin 2 as an **input**
pinMode(2, INPUT);

— Configures pin 2 as an input.

  • Serial.begin(9600); — Starts serial communication at 9600 baud to print messages to the Serial Monitor.

void loop()
Runs continuously.

  • int buttonState = digitalRead(2); — Reads the state of pin 2 (HIGH or LOW) and stores it in buttonState.
  • Serial.println(buttonState); — Prints the state to the Serial Monitor (1 for HIGH, 0 for LOW).
  • delay(100); — Waits for 100ms before reading again (adds stability and acts as basic debounce).

💡 Applications of Digital Read​

Reading digital input is widely used in real-world applications such as:

  • 🕹️ Game controllers – detect button presses
  • 🚪 Security systems – monitor door or motion sensors
  • 🤖 Robotics – read limit switches or triggers
  • 📟 User interfaces – control via keypads or pushbuttons
  • 🛠️ Industrial automation – detect machine states
  • 🧠 IoT sensors – handle smart triggers

If you need to detect ON/OFF, pressed/released, or open/closed states, digitalRead() is your go-to function.



Comments​