2.Controlling LEDs with a Keypad and Arduino

 Controlling LEDs with a Keypad and Arduino



Components Needed:

  1. Arduino board
  2. 4x4 or 4x3 Keypad
  3. LEDs (e.g., 3 LEDs)
  4. Resistors (e.g., 220Ω for each LED)
  5. Jumper wires
  6. Breadboard (optional)

Connections:

  1. Keypad: Connect the keypad pins to digital pins on your Arduino (e.g., rows to pins 9, 8, 7, 6 and columns to pins 5, 4, 3, 2).
  2. LEDs: Connect the LEDs to digital pins (e.g., LED1 to pin 13, LED2 to pin 12, LED3 to pin 11). Don’t forget to add a current-limiting resistor in series with each LED.

Example Code:

C++ Code


#include <Keypad.h> const byte ROWS = 4; // Number of rows const byte COLS = 4; // Number of columns char keys[ROWS][COLS] = { {'1', '2', '3', 'A'}, {'4', '5', '6', 'B'}, {'7', '8', '9', 'C'}, {'*', '0', '#', 'D'} }; byte rowPins[ROWS] = {9, 8, 7, 6}; // Connect to row pins of keypad byte colPins[COLS] = {5, 4, 3, 2}; // Connect to column pins of keypad Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS); // Define LED pins const int LED1 = 13; const int LED2 = 12; const int LED3 = 11; void setup() { // Set LED pins as outputs pinMode(LED1, OUTPUT); pinMode(LED2, OUTPUT); pinMode(LED3, OUTPUT); Serial.begin(9600); } void loop() { char key = keypad.getKey(); if (key) { Serial.println(key); // Control LEDs based on key press switch (key) { case '1': digitalWrite(LED1, HIGH); // Turn LED1 on break; case '2': digitalWrite(LED2, HIGH); // Turn LED2 on break; case '3': digitalWrite(LED3, HIGH); // Turn LED3 on break; case '4': digitalWrite(LED1, LOW); // Turn LED1 off break; case '5': digitalWrite(LED2, LOW); // Turn LED2 off break; case '6': digitalWrite(LED3, LOW); // Turn LED3 off break; default: break; } } }

Explanation:

  1. Library Import: The Keypad library is included for interfacing with the keypad.
  2. Define Rows and Columns: Set the number of rows and columns of the keypad.
  3. Key Mapping and Pin Assignments: Assign the keypad pins and map the keys.
  4. LED Pins Setup: Define and set up LED pins as outputs.
  5. Loop Logic:
    • Use keypad.getKey() to detect key presses.
    • Depending on the key pressed, turn on or off specific LEDs:
      • Pressing '1', '2', or '3' turns on LED1, LED2, or LED3, respectively.
      • Pressing '4', '5', or '6' turns off LED1, LED2, or LED3, respectively.

Tips:

  • You can expand the code to use more keys for different functions.
  • Ensure your keypad and LED wiring are correct to avoid short circuits.

Comments

Popular posts from this blog

4.Keypad-Controlled Lock System with Servo and I2C LCD Using Arduino

Measuring and Displaying Solar Panel Voltage on an LCD using Arduino