Button and LED Basics with Arduino

This project introduces fundamental concepts of Arduino programming by demonstrating how to control an LED with a pushbutton.

You can simulate this project online using Wokwi: Button and LED Simulation


What You'll Learn

This project will guide you through the following essential Arduino concepts:

  1. Declaring Variables: Learn how to create and use variables in your Arduino sketches.
  2. Reading Digital Input: Understand how to read the state of a digital input pin connected to a button.
  3. Writing Digital Output: Learn how to control a digital output pin connected to an LED.
  4. Using the Serial Monitor: Discover how to use the Serial Monitor for debugging and displaying information.

Project Diagram

Here is the circuit setup for this project.

Button and LED Diagram

Code Breakdown

Let's dive deeper into the code elements, explaining each part of the program.

Declaring Variables

We start by declaring variables to represent our components. This makes our code easier to read and modify.

int button = 3;
int LED1 = 10;

The setup() Function

The setup() function runs just once when the Arduino board is powered on or reset. We use it to initialize our pins and serial communication.

void setup()
{
  Serial.begin(9600);
  pinMode(button, INPUT_PULLUP);
  pinMode(LED1, OUTPUT);
}

The loop() Function

The loop() function runs continuously after the setup() function has finished. This is where the main logic of our program resides.

void loop()
{
  int Button1Pressed = digitalRead(button);

  if (Button1Pressed == LOW)
  {
    Serial.println("Button pressed!");
    digitalWrite(LED1, HIGH);
  }
  else
  {
    digitalWrite(LED1, LOW);
  }
}

Full Code

Here's the complete code, ready to upload to your Arduino board.


int button = 3;
int LED1 = 10;

void setup()
{
  Serial.begin(9600);
  pinMode(button, INPUT_PULLUP);
  pinMode(LED1, OUTPUT);
}

void loop()
{
  int Button1Pressed = digitalRead(button);

  if (Button1Pressed == LOW)
  {
    Serial.println("Button pressed!");
    digitalWrite(LED1, HIGH);
  }
  else
  {
    digitalWrite(LED1, LOW);
  }
}