#include <stdio.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "driver/gpio.h"
int readPinStateWithDebounce(int pin); //Function declaration (JI)
// Pin definitions
#define BUTTON_PIN 4 // Button connected to GPIO 4
uint8_t led_pins[] = {38, 37, 36, 35, 0, 45, 48, 47}; //8-bit unsigned int array for LEDs w/ their GPIO pins. Uint8 array saves memory. (JI)
void app_main() {
gpio_set_direction(BUTTON_PIN, GPIO_MODE_INPUT); //Setting the button as an input. (JI)
for (int i = 0; i < 8; i++) { //For-loop to initialize all LEDs as outputs. (JI)
gpio_set_direction(led_pins[i], GPIO_MODE_OUTPUT); //"i" iterates through each LED. (JI)
}
while (1) {
int btnState = readPinStateWithDebounce(BUTTON_PIN); //Reading the button state through the function and storing the value in a variable. (JI)
if (btnState == 1) { //If the button is not pressed, set all the LEDs to low. (JI)
for (int i = 0; i < 8; i++) {
gpio_set_level(led_pins[i], 0);
}
} else {
for (int i = 0; i < 8; i++) { //If the button pressed, set all the LEDs to high. (JI)
gpio_set_level(led_pins[i], 1);
}
}
vTaskDelay(pdMS_TO_TICKS(200)); // Small delay to prevent excessive looping
}
}
int readPinStateWithDebounce(int pin) { //Debounce function definition. (JI)
int initialState = gpio_get_level(pin); //Read the level of the button and store the value in a variable. (JI)
if (initialState == 0) { //If the button is pressed, proceed with the code below. (JI)
vTaskDelay(pdMS_TO_TICKS(50));
printf("Button pressed. Pin state 1 = %d\n", initialState); //Print the value of initialState to validate button is not or IS pressed. (JI)
int currentState = gpio_get_level(pin);
if (currentState == 0){
printf("Button pressed. Pin state 2 = %d\n\n", currentState); //Print the value of currentState to validate is not or IS pressed. (JI)
} else {
printf("Button not pressed. Pin state high = 1\n\n"); //If not the button is not pressed, print a message to validate. (JI)
return 1;
}
return 0;
} else {
printf("Button not pressed. Pin state high = 1\n\n"); //If the button is not pressed, print a message to validate. (JI)
return 1;
}
}