How to use a button with Arduino

In this tutorial, we will explain how to use a push button with an Arduino board. We will walk through the correct wiring, provide a simple code example, and explain each step to help you understand how to detect button presses. 

 📝 Required components

  • 1 x Arduino Uno (or compatible board)

  • Push button
  • 10kΩ resistor
  • Jumper wires

  • Breadboard 

Step 1: Wiring the Electronics 

The button has four legs (two pairs connected internally). We only need to use two pins, one on each side. Connect one button pin to digital pin 7 on the Arduino and the one below it to GND via a 10kΩ pull-down resistor. So now connect the bottom right pin directly to 5V. This ensures that the input pin reads LOW when the button is not pressed and HIGH when it is pressed. 

Basic wiring: 

  • Button pin 1 → Arduino digital pin 7
  • Button pin 2 → GND via 10kΩ resistor
  • Button pin 4 → 5V directly

🖥️​Step 2: Writing the Code 

Below is a simple sketch that reads the button state and turns on the built-in LED when the button is pressed: 

📦 Complete Arduino code

This is the complete code to use the button with Arduino:

				
					const int buttonPin = 7;     // Pin connected to the button 
const int ledPin = 13;       // Built-in LED pin 
 
int buttonState = 0;         // Variable to hold the button state 
 
void setup() { 
  pinMode(buttonPin, INPUT); // Set the button pin as input 
  pinMode(ledPin, OUTPUT);   // Set the LED pin as output 
} 
 
void loop() { 
  buttonState = digitalRead(buttonPin); // Read the state of the button 
 
  if (buttonState == HIGH) { 
    digitalWrite(ledPin, HIGH); // Turn on LED if button is pressed 
  } else { 
    digitalWrite(ledPin, LOW);  // Turn off LED otherwise 
  } 
} 

				
			

🔎 Breaking down the Code

Let’s review the code section by section:

				
					const int buttonPin = 7;
				
			

Defines the pin connected to the button. 

				
					const int ledPin = 13;
				
			

Uses the built-in LED on most Arduino boards.

				
					pinMode(...)
				
			

Sets up the pin modes for input and output.

				
					digitalRead(...)
				
			

Reads the current state of the button (HIGH if pressed, LOW otherwise).

				
					digitalWrite(...)
				
			

Turns the LED on or off based on the button state.

🛠️​Step 3: Troubleshooting 

 

The LED never turns on

  • Check the wiring of the button and make sure you’re using a pull-down resistor. 
  • Make sure the correct digital pin number is used in the code. 

 

The LED stays on constantly

  • The button might be wired incorrectly, or creating a short to 5V. 
  • The input pin might be floating if the resistor is missing. 
en_US