Try   HackMD

Reading a button press with Arduino is a fundamental skill in embedded programming. Here’s how to do it step by step:

FHRC2ZEGSLEWL2O

What You Need:

Wiring the Button (with Pull-Down Resistor):

企业微信截图_20250709164507

Add a 10kΩ resistor between pin 2 and GND
→ When the button is pressed, pin 2 reads HIGH

Basic Code: Detect Button Press

cpp

const int buttonPin = 2;  // Connected to the button
const int ledPin = 13;    // Built-in LED

void setup() {
  pinMode(buttonPin, INPUT);   // Set button pin as input
  pinMode(ledPin, OUTPUT);     // Set LED pin as output
}

void loop() {
  int buttonState = digitalRead(buttonPin);  // Read button

  if (buttonState == HIGH) {
    digitalWrite(ledPin, HIGH);  // Turn LED on if pressed
  } else {
    digitalWrite(ledPin, LOW);   // Turn LED off if not
  }
}

Alternate Wiring: Internal Pull-Up (No Resistor Needed)

  • Connect one side of the button to GND
  • Connect the other to pin 2
  • Use internal pull-up:
cpp

void setup() {
  pinMode(buttonPin, INPUT_PULLUP); // Activates internal pull-up resistor
}

Note: Now LOW = pressed, HIGH = unpressed (inverted logic)

Summary:

  • Use digitalRead() to check button state
  • Use pull-down (external) or pull-up (internal) to avoid floating inputs
  • Buttons can control LEDs, trigger events, or navigate menus