#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "driver/gpio.h"
#include "esp_log.h"
//deining the functions the program uses
char readKeyPadSingleScan(char _keys[4][4], int _scanColPins[4], int _rowPins[4]);
void setup_gpio();
char scan_keypad();
//defining the two main variables
#define ROWS 4
#define COLS 4
//defining two arrays, one horizontal and oone vertiacal
int scanRowPins[ROWS] = {10, 9 , 46, 3};
int colPins[COLS] = {8, 18, 17, 16};
//combing rows and colums o make a two dimensional array
char keys[ROWS][COLS] = {
{'1', '2', '3', 'A'},
{'4', '5', '6', 'B'},
{'7', '8', '9', 'C'},
{'*', '0', '#', 'D'}
};
void app_main() {
setup_gpio();
//main loop
while (1) {
//setting key to the scan_keypad function
// char key = scan_keypad();
//works unless key doesn't equal the null character
char k = readKeyPadSingleScan(keys, colPins, scanRowPins);
if (k != '\0') {
printf("You pressed: %c\n", k);
}
vTaskDelay(pdMS_TO_TICKS(50)); //slight delay
}
}
/**
setup_gpio
sets all the pins to input and makes them use pullup resistor logic
void
*/
void setup_gpio() {
for (int i = 0; i < ROWS; i++) {
gpio_set_direction(scanRowPins[i], GPIO_MODE_OUTPUT);
gpio_set_level(scanRowPins[i], 1);
}
for (int i = 0; i < COLS; i++) {
gpio_set_direction(colPins[i], GPIO_MODE_INPUT);
gpio_set_pull_mode(colPins[i], GPIO_PULLUP_ONLY); // all buttons are set as pullup configuration using the internal pullup resistor in the microcontroller
}
}
/**
scan_keypad
scans all of the rows and colums contineously checking for an input
char
*/
char scan_keypad() {
uint8_t scanVal;
for (int i = 0; i < ROWS; i++) {
scanVal = ~(1 << i);
for (int j = 0; j < ROWS; j++) {
gpio_set_level(scanRowPins[j], (scanVal >> j) & 1); // here, 'pins' can be either row pins or column pins. Select the correct one
}
vTaskDelay(pdMS_TO_TICKS(5)); //slight delay
for (int k = 0; k < COLS; k++) {
if (gpio_get_level(colPins[k]) == 0) { // pullup configuration
while (gpio_get_level(colPins[k]) == 0) {
vTaskDelay(pdMS_TO_TICKS(50));
}
return keys[k][i];
}
}
}
return '\0';
}
/**
readKeyPadSingleScan
continiously checks the value of the keypad
char
char _keys[4][4], int _scanColPins[4], int _rowPins[4]
*/
char readKeyPadSingleScan(char _keys[4][4], int _scanColPins[4], int _rowPins[4]) {
uint8_t scanVal;
char retVal = '\0';
//loops permanently until any is pressed, then it stops and starts anew after
do {
for (int i = 0; i < ROWS; i++) {
scanVal = ~(1 << i);
printf("scanning in process\n");
for (int j = 0; j < ROWS; j++) {
gpio_set_level(scanRowPins[j], (scanVal >> j) & 1); // here, 'pins' can be either row pins or column pins. Select the correct one
}
vTaskDelay(pdMS_TO_TICKS(5)); //slight delay
for (int k = 0; k < COLS; k++) {
if (gpio_get_level(colPins[k]) == 0) { // pullup configuration
while (gpio_get_level(colPins[k]) == 0) {
vTaskDelay(pdMS_TO_TICKS(50));
}
return keys[k][i];
}
}
}
}while(retVal == '/0');
return '\0';
}