30. Creating LED Patterns with Arduino Using a Push Button

Introduction:

    In this tutorial, we will learn how to create different LED patterns using an Arduino and a push button. We will use the push button to cycle through different patterns, such as blinking, fading, and chasing LEDs. This project is a great way to learn about Arduino programming and basic electronics.

Materials Required:
  • Arduino board (e.g., Arduino Uno)
  • Breadboard
  • LEDs (any color)
  • Push button 
  • Resistors (220 ohms for LEDs, 10k ohms for the pull-down resistor)
  • Jumper wires
Circuit Diagram:


Step-by-Step Instructions:

1. Setup the Circuit:

- Connect the push button to pin 2 of the Arduino with a 10k ohm pull-down resistor.

- Connect the LEDs to pins 3, 4, and 5 of the Arduino with 220 ohm resistors.

2. Upload the Code:

- Use the following Arduino sketch to create different LED patterns when the push button is pressed:

C++
// Define the pins for the push button and LEDs

int buttonPin = 2; // Push button connected to digital pin 2
int ledPins[] = {3, 4, 5}; // LEDs connected to digital pins 3, 4, 5
int numLEDs = 3; // Number of LEDs
int pattern = 0; // Variable to store the current LED pattern
int buttonState; // Variable to store the state of the button
int lastButtonState = LOW; // Variable to store the previous state of the button
void setup() {
// Initialize the button pin as input
pinMode(buttonPin, INPUT);
// Initialize the LED pins as outputs
for (int i = 0; i < numLEDs; i++) {
pinMode(ledPins[i], OUTPUT);
}
}
void loop() {
// Read the state of the button
buttonState = digitalRead(buttonPin);
// Check if the button is pressed and released
if (buttonState == HIGH && lastButtonState == LOW) {
// Increase the pattern variable
pattern++;
if (pattern >= numLEDs) {
pattern = 0; // Reset the pattern to 0 if it exceeds the number of LEDs
}
}
// Update the last button state
lastButtonState = buttonState;
// Display the current LED pattern
switch (pattern) {
case 0:
allOn();
break;
case 1:
chase();
break;
case 2:
blink();
break;
}
}
// Function to turn all LEDs on
void allOn() {
for (int i = 0; i < numLEDs; i++) {
digitalWrite(ledPins[i], HIGH);
}
}
// Function to create a chasing pattern
void chase() {
for (int i = 0; i < numLEDs; i++) {
digitalWrite(ledPins[i], HIGH);
delay(100);
digitalWrite(ledPins[i], LOW);
}
}
// Function to blink all LEDs simultaneously
void blink() {
for (int i = 0; i < numLEDs; i++) {
digitalWrite(ledPins[i], HIGH);
}
delay(500);
for (int i = 0; i < numLEDs; i++) {
digitalWrite(ledPins[i], LOW);
}
delay(500);
}

Conclusion:

    By following this tutorial, you have learned how to create different LED patterns using an Arduino and a push button. Experiment with different patterns and timings to create your own unique LED displays!
Post a Comment (0)
Previous Post Next Post