#include <Key.h>
#include <Keypad.h>

const int numRows = 4; // Number of rows in the keypad and LED matrix
const int numCols = 4; // Number of columns in the keypad and LED matrix

// Define the pins for rows and columns of keypad
const int rowPins[numRows] = {23, 22, 1, 3}; // Example row pins
const int colPins[numCols] = {21, 19, 18, 5}; // Example column pins

// Define the pins for rows and columns of LED matrix
const int ledRowPins[numRows] = {17, 16, 4, 0}; // Example LED row pins
const int ledColPins[numCols] = {12, 14, 27, 26}; // Example LED column pins

// Define the characters associated with each key in the keypad matrix
char keypadKeys[numRows][numCols] = {
  {'1', '2', '3', 'A'},
  {'4', '5', '6', 'B'},
  {'7', '8', '9', 'C'},
  {'*', '0', '#', 'D'}
};

void setup() {
  // Initialize pins for keypad
  for (int i = 0; i < numRows; i++) {
    pinMode(rowPins[i], OUTPUT);
    digitalWrite(rowPins[i], HIGH); // Initially set all rows to HIGH
  }
  for (int i = 0; i < numCols; i++) {
    pinMode(colPins[i], INPUT_PULLUP);
  }

  // Initialize pins for LEDs
  for (int i = 0; i < numRows; i++) {
    pinMode(ledRowPins[i], OUTPUT);
  }
  for (int i = 0; i < numCols; i++) {
    pinMode(ledColPins[i], OUTPUT);
  }
}

void loop() {
  // Keypad scanning
  char pressedKey = '\0'; // Initialize pressedKey to null character
  
  for (int row = 0; row < numRows; row++) {
    // Activate the current row
    digitalWrite(rowPins[row], LOW);
    
    // Check each column
    for (int col = 0; col < numCols; col++) {
      // If a key is pressed
      if (digitalRead(colPins[col]) == LOW) {
        // Store the pressed key
        pressedKey = keypadKeys[row][col];
      }
    }
    
    // Deactivate the current row
    digitalWrite(rowPins[row], HIGH);
  }
  
  // LED control
  // Turn off all LEDs first
  for (int row = 0; row < numRows; row++) {
    digitalWrite(ledRowPins[row], LOW);
  }
  for (int col = 0; col < numCols; col++) {
    digitalWrite(ledColPins[col], HIGH);
  }
  
  // Turn on the LED corresponding to the pressed key
  if (pressedKey != '\0') {
    // Find the position of the pressed key in the keypadKeys array
    for (int row = 0; row < numRows; row++) {
      for (int col = 0; col < numCols; col++) {
        if (keypadKeys[row][col] == pressedKey) {
          // Turn on the corresponding LED
          digitalWrite(ledRowPins[row], HIGH);
          digitalWrite(ledColPins[col], LOW);
          // Exit the loop since we found the key
          break;
        }
      }
    }
  }
  
  // Optional: Print the pressed key to the serial monitor
  if (pressedKey != '\0') {
    Serial.print("Key pressed: ");
    Serial.println(pressedKey);
  }
  
  // Optional: Add a small delay to avoid rapid LED switching if the key is held down
  delay(100);
}


$abcdeabcde151015202530fghijfghij
$abcdeabcde151015202530fghijfghij