Blinking LED with Button Control Project with Arduino UNO R4 WiFi

Project Introduction

This project demonstrates a simple application where an LED can be controlled by a button using an Arduino UNO R4 WiFi board. It's a great way for beginners to understand how to handle inputs and outputs with Arduino.

Project Principle

The principle behind this project is to use the Arduino's digital input pin to read the state of a button. When the button is pressed, the Arduino toggles the state of an LED connected to a digital output pin.

Project Setup Method

Materials Needed

  • Arduino UNO R4 WiFi board
  • 1 x LED
  • 1 x 220-ohm resistor
  • 1 x Push button
  • 1 x Push button cap
  • 1 x 220-ohm resistor (for pull-down resistor)
  • Breadboard
  • Jumper wires

Circuit Setup

  • Insert the long leg (anode) of the LED into a breadboard row, and place the 220-ohm resistor next to it.
  • Connect the other end of the resistor to the breadboard row, ensuring they share the same electrical connection.
  • Insert the short leg (cathode) of the LED into another breadboard row.
  • Connect one end of a jumper wire to the cathode's breadboard row.
  • Connect the other end of the jumper wire to one of the Arduino's digital output pins (e.g., pin 13).
  • Connect the anode's breadboard row to the Arduino's ground (GND) through another jumper wire.
  • Connect one pin of the push button to another digital input pin on the Arduino (e.g., pin 2).
  • Connect the other pin of the push button to the 5V pin on the Arduino.
  • Connect a 220-ohm resistor between the digital input pin and the ground (GND) to create a pull-down resistor.

Code

// Define the pins where the LED and button are connected
int ledPin = 13;
int buttonPin = 2;

// Variable to store the LED state
int ledState = LOW;

void setup() {
  // Set the LED pin as an output
  pinMode(ledPin, OUTPUT);

  // Set the button pin as an input
  pinMode(buttonPin, INPUT);
}

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

  // Check if the button is pressed
  if (buttonState == HIGH) {
    // Toggle the LED state
    ledState = !ledState;
    delay(200); // Debounce delay
  }

  // Set the LED according to its state
  digitalWrite(ledPin, ledState);
}

Line-by-Line Code Explanation

  • Line 1-2: Define the pin numbers where the LED and button are connected.
  • Line 4: Define a variable to store the state of the LED.
  • Line 7-8: The setup() function initializes the Arduino. It sets the LED pin as an output and the button pin as an input.
  • Line 11: Inside loop(), read the state of the button.
  • Line 13-15: If the button is pressed (HIGH), toggle the LED state and add a delay to debounce the button.
  • Line 18: Set the LED pin to the current state of the LED.

This simple code allows you to control the LED's brightness by pressing the button, toggling the LED on and off each time the button is pressed.