Components Needed:
- Arduino board
- 4x4 or 4x3 Keypad
- LEDs (e.g., 3 LEDs)
- Resistors (e.g., 220Ω for each LED)
- Jumper wires
- Breadboard (optional)
Connections:
- 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).
- 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; 
const byte COLS = 4; 
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};    
byte colPins[COLS] = {5, 4, 3, 2};     
Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS);
const int LED1 = 13;
const int LED2 = 12;
const int LED3 = 11;
void setup() {
  
  pinMode(LED1, OUTPUT);
  pinMode(LED2, OUTPUT);
  pinMode(LED3, OUTPUT);
  Serial.begin(9600);
}
void loop() {
  char key = keypad.getKey();
  if (key) {
    Serial.println(key);
    
    switch (key) {
      case '1':
        digitalWrite(LED1, HIGH);  
        break;
      case '2':
        digitalWrite(LED2, HIGH);  
        break;
      case '3':
        digitalWrite(LED3, HIGH);  
        break;
      case '4':
        digitalWrite(LED1, LOW);   
        break;
      case '5':
        digitalWrite(LED2, LOW);   
        break;
      case '6':
        digitalWrite(LED3, LOW);   
        break;
      default:
        break;
    }
  }
}
Explanation:
- Library Import: The Keypadlibrary is included for interfacing with the keypad.
- Define Rows and Columns: Set the number of rows and columns of the keypad.
- Key Mapping and Pin Assignments: Assign the keypad pins and map the keys.
- LED Pins Setup: Define and set up LED pins as outputs.
- 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
Post a Comment