#include <Arduino.h>
#define DATA_PIN 5 // SER pin of the 74HC595
#define CLOCK_PIN 19 // SRCLK pin of the 74HC595
#define LATCH_PIN 18 // RCLK pin of the 74HC595
// Define row pins connected directly to the ESP32
#define ROW1_PIN 35
#define ROW2_PIN 32
#define ROW3_PIN 33
void setup() {
// Initialize shift register pins
pinMode(DATA_PIN, OUTPUT);
pinMode(CLOCK_PIN, OUTPUT);
pinMode(LATCH_PIN, OUTPUT);
// Initialize row pins as inputs with internal pull-ups
pinMode(ROW1_PIN, INPUT_PULLUP);
pinMode(ROW2_PIN, INPUT_PULLUP);
pinMode(ROW3_PIN, INPUT_PULLUP);
Serial.begin(115200);
}
void loop() {
// Loop through each column
for (int col = 0; col < 8; col++) {
setColumn(col); // Set the specific column LOW
// Check each row to detect key presses
for (int row = 0; row < 3; row++) {
int rowPin = getRowPin(row); // Get the specific row pin
if (isKeyPressed(rowPin)) { // Use the helper function to check if key is pressed
int keyNumber = (row * 8) + col + 1; // Calculate key number
Serial.printf("Key %d is pressed\n", keyNumber);
}
}
}
delay(50); // Small delay for debounce
}
void setColumn(int col) {
byte data = 0xFF; // Start with all HIGH
// Set the specific column to LOW
data &= ~(1 << col);
shiftOutData(data); // Send the data to the shift register
}
void shiftOutData(byte data) {
digitalWrite(LATCH_PIN, LOW);
shiftOut(DATA_PIN, CLOCK_PIN, MSBFIRST, data); // Send data to shift register
digitalWrite(LATCH_PIN, HIGH);
}
bool isKeyPressed(int rowPin) {
return digitalRead(rowPin) == LOW; // Return true if the key is pressed (LOW)
}
int getRowPin(int row) {
switch (row) {
case 0: return ROW1_PIN;
case 1: return ROW2_PIN;
case 2: return ROW3_PIN;
default: return -1; // Invalid row
}
}