#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}; // LED pins
// Function declarations
int readPinStateWithDebounce(int pin);
void writeToPins(uint8_t pins[], uint8_t val);
void printBin8(uint8_t val);
void app_main() {
// Configure button pin as input
gpio_set_direction(BUTTON_PIN, GPIO_MODE_INPUT);
gpio_set_pull_mode(BUTTON_PIN, GPIO_PULLUP_ONLY);
// Configure LED pins as output
for (int i = 0; i < 8; i++) {
gpio_set_direction(led_pins[i], GPIO_MODE_OUTPUT);
}
uint8_t counter = 0; // Binary counter variable
while (1) {
int btnState = readPinStateWithDebounce(BUTTON_PIN);
if (btnState == 0) { // Button is pressed
counter++; // Increment the counter
writeToPins(led_pins, counter); // Display on LEDs
printBin8(counter); // Print binary value to serial monitor
vTaskDelay(pdMS_TO_TICKS(200)); // Debounce delay
}
}
}
/* Function Name -readPinstateWithdebounce
* Description - This function reads the
* Return type -
* Parameters - -
*/
/* Function to debounce and read button state */
int readPinStateWithDebounce(int pin) {
int btnState = gpio_get_level(pin);
if (btnState == 0) { // Button pressed
vTaskDelay(pdMS_TO_TICKS(50)); // Debounce delay
int newState = gpio_get_level(pin);
if (newState == 0) { // Still pressed
printf("Button Pressed\n");
return 0;
}
}
printf("waiting to be pressed\n");
return 1; // Default state (not pressed)
}
/* Function Name -
* Description -
* Return type -
* Parameters - -
*/
/* Function to write binary value to LED pins */
void writeToPins(uint8_t pins[], uint8_t val) {
for (int i = 0; i < 8; i++) {
int bit = (val >> i) & 1; // Extract bit value
gpio_set_level(pins[i], bit); // Write to corresponding LED pin
}
}
/* Function Name -
* Description -
* Return type -
* Parameters - -
*/
/* Function to print binary representation of val */
void printBin8(uint8_t val) {
printf("Binary Count: ");
for (int i = 7; i >= 0; i--) { // Print MSB to LSB
printf("%d", (val >> i) & 1);
}
printf("\n");
}