Components Needed
To complete this project, you'll need the following components:
Step-by-Step Wiring Instructions
Follow these instructions to wire the button correctly:
- Connect one leg of the button to
pin 2
on the Arduino. - Connect the other leg of the button to
GND
(ground). - Add a 10kΩ pull-up resistor between pin 2 and
5V
.
Arduino Code
Here is the Arduino code to read the state of the button:
// Button Reading Experiment
// Variables
int buttonPin = 2; // Pin connected to the button
int buttonState = 0; // Variable to hold button state
// Setup function
void setup() {
// Initialize pin 2 as an input for the button
pinMode(buttonPin, INPUT);
// Start serial communication for output
Serial.begin(9600);
}
// Main loop function
void loop() {
// Read the state of the button
buttonState = digitalRead(buttonPin);
// If button is pressed
if (buttonState == LOW) {
Serial.println("Button Pressed!");
} else {
Serial.println("Button Released!");
}
delay(500); // Short delay to avoid bouncing issues
}
Testing the Code
To test the code, follow these steps:
- Connect your Arduino to your PC using the Micro USB cable.
- Open the Arduino IDE and paste the code provided above.
- Select your board and the correct port in the Arduino IDE.
- Click the upload button to send the code to the Arduino.
- Open the Serial Monitor (Tools > Serial Monitor) and observe the output as you press and release the button.
How the Code Works
This code reads the state of the button. When the button is pressed, it connects pin 2 to GND, setting it to LOW
. When released, the pin is pulled HIGH
by the resistor.
Main Functions Explained
pinMode()
: Configures pin 2 as an input pin to read the button’s state.digitalRead()
: Reads the state of the button, returning eitherHIGH
orLOW
.if
: A conditional statement used to check the button’s state and determine whether it is pressed or released.
Conclusion
Congratulations! You've successfully completed the Arduino button reading experiment. This simple project introduces you to digital input and basic Arduino programming. Experiment further by adding more buttons or modifying the code to perform different actions based on button presses.