// code segment 3.2
#include <stdio.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "driver/gpio.h"
int readPinStateWithDebounce(int pin);
// Button and LED pin definitions
#define BUTTON_PIN 4
#define LED_PIN 2
void app_main() {
// Configure button as input
gpio_set_direction(BUTTON_PIN, GPIO_MODE_INPUT);
// Configure LED as output
gpio_set_direction(LED_PIN, GPIO_MODE_OUTPUT);
while (1) {
// read the button pin with debounce
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
}
}
}
/* Function Name -readPinStateWithDebounce
* Description -checks the state of the Button repeatedly while printing the variables
* Return type - int
* Parameters - pin
*/
int readPinStateWithDebounce(int pin) {
int istate = gpio_get_level(pin);
if (istate == 0) {
vTaskDelay(pdMS_TO_TICKS(50));
printf("The 1st state is %d\n", istate);
int cstate = gpio_get_level(pin);
if (cstate == 0) {
printf("the 2nd state is %d\n", cstate);
return 0;
}
else {
printf("button not pressed. Pinstate high = %d\n", istate);
return 1;
}
}
else {
printf("button not pressed. Pinstate high = %d\n", istate);
return 1;
}
}