// 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 - reads pin with a debounce
* Return type - int
* Parameters -integer -pin
*/
int readPinStateWithDebounce(int pin) {
int btnstate = gpio_get_level(pin);
if (btnstate == 0) {
vTaskDelay(pdMS_TO_TICKS(50));
printf("Button state 1 = 0 \n");
if (btnstate == 0) {
printf("Button state 2 = 0 \n");
return 0;
}
return 1;
}
else{
printf("Button not pressed. ");
printf("Button state = 1 \n");
return 1;
}
}