// Code segment 3.1
#include <stdio.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "driver/gpio.h"
// Function declaration
int readPinStateWithDebounce(int pin);
// Button and LED pin definitions
#define BUTTON_PIN 4
#define LED_PIN 2
void app_main() {
// Configure button pin as input
gpio_set_direction(BUTTON_PIN, GPIO_MODE_INPUT);
// Configure LED pin as output
gpio_set_direction(LED_PIN, GPIO_MODE_OUTPUT);
while (1) {
// read the button pin
int btnVal = readPinStateWithDebounce(BUTTON_PIN);
// display the button state.
// Not pressed while state = 1, Pressed while state = 0
if (btnVal == 1) { // not pressed
vTaskDelay(pdMS_TO_TICKS(200));
gpio_set_level(LED_PIN, 0); // Turn off LED
}
else { // pressed
vTaskDelay(pdMS_TO_TICKS(200));
gpio_set_level(LED_PIN, 1); // Turn on LED
}
}
}
int readPinStateWithDebounce(int pin) {
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. (JI)
int currentState = gpio_get_level(pin);
if (currentState == 0){
printf("Button pressed. Pin state 2 = %d\n\n", currentState);
} else {
printf("Button not pressed. Pin state high = 1\n\n");
return 1;
}
return 0;
} else {
printf("Button not pressed. Pin state high = 1\n\n");
return 1;
}
}