// 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) {
gpio_get_level(BUTTON_PIN);
if (BUTTON_PIN == 1) {
vTaskDelay(pdMS_TO_TICKS(50));
printf("Button state = %d \n", BUTTON_PIN);
return 0;
}
else{
printf(" not Button pressed. ");
printf("Button state = %d\n", BUTTON_PIN);
gpio_set_level(LED_PIN, 1); // Turn on LED
return 1;
}
}