#include <Keypad.h>
#include <Adafruit_NeoPixel.h>
const byte ROWS = 4; //four rows
const byte COLS = 4; //four columns
const byte NUM_LEDS = 16;
const byte LED_PIN = 10;
int position;
unsigned long lastMillis, currentMillis;
Adafruit_NeoPixel pixel(NUM_LEDS, LED_PIN, NEO_GRB + NEO_KHZ800);
char keys[ROWS][COLS] = {
{'A', 'B', 'C', 'D'},
{'E', 'F', 'G', 'H'},
{'I', 'J', 'K', 'L'},
{'M', 'N', 'O', 'P'},
};
int state[ROWS*COLS] = {0}; // Initialize all to 0
byte rowPins[COLS] = {2, 3, 4, 5}; //connect to the column pinouts of the kpd
byte colPins[ROWS] = {6, 7, 8, 9}; //connect to the row pinouts of the kpd
Keypad kpd = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );
// Function to get the index of the key in the keys array
int getKeyIndex(char key){
for(int r = 0; r < ROWS; r++){
for(int c = 0; c < COLS; c++){
if(keys[r][c] == key) {
return r * COLS + c; // Calculate the index
}
}
}
return -1; // Return -1 if the key is not found
}
// Function to turn on/off the LED at the given index
void setLED(int index, int r, int g, int b){
if(index >= 0 && index < NUM_LEDS){
pixel.setPixelColor(index, pixel.Color(r, g, b));
pixel.show();
}
}
void keypadRoutine(){
if (kpd.getKeys()) {
for (int i=0; i<16; i++) {
if (kpd.key[i].stateChanged) {
switch (kpd.key[i].kstate) {
case PRESSED:
position = getKeyIndex(kpd.key[i].kchar); // Get the index of the pressed key
if(position != -1 && state[position] == 0){
state[position] = 1; // Set the state to 1
setLED(position, 255, 0, 0); // Turn the LED on
Serial.printf("button %c at index %d is pressed, state is now ON\n", kpd.key[i].kchar, position);
}
break;
case RELEASED:
position = getKeyIndex(kpd.key[i].kchar); // Get the index of the released key
if(position != -1 && state[position] == 1){
state[position] = 0; // Set the state to 0
setLED(position, 0, 0, 0); // Turn the LED off
Serial.printf("button %c at index %d is released, state is now OFF\n", kpd.key[i].kchar, position);
}
break;
}
}
}
}
}
// void keypadRoutine(){
// if (kpd.getKeys()) {
// for (int i=0; i<LIST_MAX; i++) {
// if (kpd.key[i].stateChanged) {
// switch (kpd.key[i].kstate) {
// case RELEASED:
// case PRESSED:
// position = getKeyIndex(kpd.key[i].kchar); // Get the index of the pressed key
// if(position != -1){
// state[position] = !state[position]; // Toggle the state
// setLED(position, 255, 0, 0); // Set the LED color based on the state
// Serial.printf("button %c at index %d is pressed, state is %d, %d key is pressed\n", kpd.key[i].kchar, position, state[position], sizeof(kpd.key)/sizeof(kpd.key[0]));
// }
// break;
// // You can handle the RELEASED state if needed
// break;
// }
// }
// }
// }
// }
void setup() {
Serial.begin(115200);
pinMode(LED_PIN, OUTPUT);
pixel.begin();
pixel.clear(); pixel.show();
}
int i = 0;
void loop() {
// keypadRoutine();
pixel.setPixelColor(i, pixel.Color(0, 0, 255));
i++;
pixel.show();
delay(200);
}
Loading
esp32-s2-devkitm-1
esp32-s2-devkitm-1