#include <stdio.h>
#include <stdbool.h>
#include <freertos/FreeRTOS.h>
#include <freertos/task.h>
#include <esp_err.h>
#include "ultrasonic.h"
#include "driver/gpio.h"
#define ECHO_GPIO 12
#define TRIGGER_GPIO 13
#define MAX_DISTANCE_CM 500 // Maximum of 5 meters
// Pinos dos LEDs
#define LED_RED GPIO_NUM_21
#define LED_YEL GPIO_NUM_19
#define LED_GRE GPIO_NUM_18
//Setando os bits relativos aos pinos que serão configurados como
entrada
#define GPIO_OUTPUT_PIN_SEL ((1ULL<<LED_RED) | (1ULL<<LED_YEL) |
(1ULL<<LED_GRE))
//definição dos estados dos leds
enum estados_leds {RED, YELLOW, GREEN};
enum estados_leds *state = RED;
//declaração dos handles
static TaskHandle_t xtask_handle_leds = NULL;
void init_leds(){
//Configura os leds
gpio_config_t led_conf = {};
led_conf.intr_type = GPIO_INTR_DISABLE;
led_conf.mode = GPIO_MODE_OUTPUT;
led_conf.pin_bit_mask = GPIO_OUTPUT_PIN_SEL;
led_conf.pull_down_en = GPIO_PULLDOWN_DISABLE;
led_conf.pull_up_en = GPIO_PULLUP_DISABLE;
gpio_config(&led_conf);
}
int update_leds(int *state){
//atualiza os estados do led
if(*state == RED){
gpio_set_level(LED_GRE, 0);
gpio_set_level(LED_YEL, 0);
gpio_set_level(LED_RED, 1);
*state = GREEN;
return 5;
}
else if(*state == GREEN){
gpio_set_level(LED_GRE, 1);
gpio_set_level(LED_YEL, 0);
gpio_set_level(LED_RED, 0);
*state = YELLOW;
return 10;
}
else{
gpio_set_level(LED_GRE, 0);
gpio_set_level(LED_YEL, 1);
gpio_set_level(LED_RED, 0);
*state = RED;
return 1;
}
}
void control_leds (void *pvParameters){
while(true){
printf("Current State: %d\n", state);
int time = update_leds(&state);
vTaskDelay((1000*time)/portTICK_RATE_MS);
}
}
void ultrasonic_test(void *pvParameters)
{
float distance;
ultrasonic_sensor_t sensor = {
.trigger_pin = TRIGGER_GPIO,
.echo_pin = ECHO_GPIO
};
ultrasonic_init(&sensor);
int pause = 0;
while (true) {
esp_err_t res = ultrasonic_measure(&sensor,
MAX_DISTANCE_CM, &distance);
if (res == ESP_OK) {
printf("Distance: %0.04f m\n", distance);
//verifica a distância lida pelo sensor ultrassônico
if(distance <= 1 && pause == 0){
gpio_set_level(LED_GRE, 0);
gpio_set_level(LED_YEL, 0);
gpio_set_level(LED_RED, 1);
vTaskSuspend(xtask_handle_leds);
state = RED;
pause = 1;
}
else if(distance > 1 && pause == 1){
vTaskResume(xtask_handle_leds);
pause = 0;
}
} // Print error
else {
printf("Error %d: ", res);
switch (res) {
case ESP_ERR_ULTRASONIC_PING:
printf("Cannot ping (device is in invalidstate)\n");
break;
case ESP_ERR_ULTRASONIC_PING_TIMEOUT:
printf("Ping timeout (no device found)\n");
break;
case ESP_ERR_ULTRASONIC_ECHO_TIMEOUT:
printf("Echo timeout (i.e. distance toobig)\n");
break;
default:
printf("%s\n", esp_err_to_name(res));
}
}
vTaskDelay(pdMS_TO_TICKS(500));
}
}
void app_main()
{
init_leds();
xTaskCreate(ultrasonic_test, "ultrasonic_test",
configMINIMAL_STACK_SIZE * 3, NULL, 5, NULL);
xTaskCreate(control_leds, "LEDS", 2048, NULL, 5,
&xtask_handle_leds);
}