#include <stdio.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "driver/gpio.h"
// 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)
// Function declarations
int readPinStateWithDebounce(int pin);
void writeToPins(uint8_t pins[], uint8_t val);
void app_main() {
uint8_t counter = 0; //Declaring counter and initializing it to zero. (JI)
int lastButtonState = 1; //Delcaring variable to track the last button state to prevent counter from increasing quickly. (JI)
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 (lastButtonState == 1 && btnState == 0) {
counter++;
printf("Counter value: %d\n", counter);
}
writeToPins(led_pins, counter); // Write to LEDs based on button state
lastButtonState = btnState;
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));
int currentState = gpio_get_level(pin);
if (currentState == 0) {
return 0;
} else {
return 1;
}
} else {
return 1;
}
}
void writeToPins(uint8_t pins[], uint8_t val) {
for (int i = 0; i < 8; i++) {
uint8_t bitState = (val >> (7-i)) & 1; //Reading the bits in reverse order to have the LEDs appear from top to botton. (JI)
gpio_set_level(pins[i], bitState); // Set the pin to the bit state (0 or 1)
}
}