Arduino Button Reading Experiment

Difficulty Level: Beginner

In this experiment, you will learn how to read the state of a button using Arduino. This tutorial includes step-by-step instructions for wiring, code, and testing, perfect for those new to Arduino.

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:

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:

  1. Connect your Arduino to your PC using the Micro USB cable.
  2. Open the Arduino IDE and paste the code provided above.
  3. Select your board and the correct port in the Arduino IDE.
  4. Click the upload button to send the code to the Arduino.
  5. 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

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.