const uint8_t ROWS = 4;
const uint8_t COLS = 4;
char keys[ROWS][COLS] = {
{ '1', '2', '3', 'A' },
{ '4', '5', '6', 'B' },
{ '7', '8', '9', 'C' },
{ '*', '0', '#', 'D' }
};
uint8_t colPins[COLS] = { 5, 4, 3, 2 }; // Pins connected to C1, C2, C3, C4
uint8_t rowPins[ROWS] = { 9, 8, 7, 6 }; // Pins connected to R1, R2, R3, R4
void setup() {
Serial.begin(9600);
// Set row pins as INPUT_PULLUP and column pins as OUTPUT (initially LOW)
init_kaypad();
int aa = map(50,10,20,100,200);
Serial.println(aa);
}
void loop() {
loop_keypad();
}
void init_kaypad() {
// Set row pins as INPUT_PULLUP and column pins as OUTPUT (initially LOW)
for (byte i = 0; i < ROWS; i++) {
pinMode(rowPins[i], INPUT_PULLUP);
}
for (byte i = 0; i < COLS; i++) {
pinMode(colPins[i], OUTPUT);
digitalWrite(colPins[i], LOW);
}
}
void loop_keypad() {
static uint32_t prev = 0;
char pressedKey = getKey();
if (pressedKey == '\0') { // '\0' indicates no key pressed
return;
}
if (millis() - prev < 500) { // debounce it
return;
}
prev = millis();
Serial.print("pressed: ");
Serial.println(pressedKey);
}
char getKey() {
for (int col = 0; col < COLS; col++) {
digitalWrite(colPins[col], HIGH); // Activate current column
for (int row = 0; row < ROWS; row++) {
if (digitalRead(rowPins[row]) == LOW) { // Check if a row is pulled low (key pressed)
digitalWrite(colPins[col], LOW); // Deactivate current column before returning
return keys[row][col];
}
}
digitalWrite(colPins[col], LOW); // Deactivate current column
}
return '\0'; // No key pressed
}