#include <esp_wifi.h>
#include <esp_event.h>
#include <esp_log.h>
#include <esp_system.h>
#include <nvs_flash.h>
#include <sys/param.h>
#include "nvs_flash.h"
#include "esp_netif.h"
#include "esp_eth.h"
#include "protocol_examples_common.h"
#include "esp_tls_crypto.h"
#include <esp_http_server.h>
#include "driver/gpio.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "driver/mcpwm_prelude.h"
#include "freertos/event_groups.h"
#include "esp_attr.h"
#include "esp_sntp.h"
#include "freertos/timers.h"
#include <stdint.h>
#include <string.h>
#include <stdbool.h>
#include <stdio.h>
#include "nvs.h"
#include <cJSON.h>
#include "esp_http_client.h"
const char *json_string;
#define C 32
uint8_t v_C = 0;
void C_isr(void *);
char strftime_buf[64];
// Tiempo
struct
{
uint8_t SEG;
uint8_t MIN;
uint8_t HOR;
} TIEMPO;
struct
{
uint8_t SEG;
uint8_t MIN;
uint8_t HOR;
} TIEMPOA;
// Timer
void TIMER1_Conf(void);
TimerHandle_t Timer1;
uint8_t Timer1_ID = 1;
void vTimerCallback(TimerHandle_t);
uint8_t deletetask = 0;
#ifndef INET6_ADDRSTRLEN
#define INET6_ADDRSTRLEN 48
#endif
TaskHandle_t xHandle = NULL;
static const char *TAG2 = "Servomotor";
#define SERVO_MIN_PULSEWIDTH_US 500 // Minimum pulse width in microsecond
#define SERVO_MAX_PULSEWIDTH_US 2500 // Maximum pulse width in microsecond
#define SERVO_MIN_DEGREE -90 // Minimum angle
#define SERVO_MAX_DEGREE 90 // Maximum angle
#define SERVO_PULSE_GPIO 14 // GPIO connects to the PWM signal line
#define SERVO_TIMEBASE_RESOLUTION_HZ 1000000 // 1MHz, 1us per tick
#define SERVO_TIMEBASE_PERIOD 20000 // 20000 ticks, 20ms
static inline uint32_t angle_to_compare(int);
#define LED_R 33
static const char *TAG = "Server";
uint8_t contador = 0;
// temperatura
// API key from OpenWeatherMap
char open_weather_map_api_key[] = "21c41f7d9928e35c31c3995f17b9d394";
char city[] = "Merida";
char country_code[] = "VE";
float temp1;
int pressure1;
int humidity1;
#define HTTP_RESPONSE_BUFFER_SIZE 1024
char *response_data = NULL;
size_t response_len = 0;
bool all_chunks_received = false;
void get_temp_pressure_humidity(const char *json_string)
{
cJSON *root = cJSON_Parse(json_string);
cJSON *obj = cJSON_GetObjectItemCaseSensitive(root, "main");
float temp = cJSON_GetObjectItemCaseSensitive(obj, "temp")->valuedouble;
int pressure = cJSON_GetObjectItemCaseSensitive(obj, "pressure")->valueint;
int humidity = cJSON_GetObjectItemCaseSensitive(obj, "humidity")->valueint;
printf("Temperature: %0.00fK\nPressure: %d hPa\nHumidity: %d%%\n", temp, pressure, humidity);
temp1 = temp - 273;
pressure1 = pressure;
humidity1 = humidity;
cJSON_Delete(root);
free(response_data);
}
esp_err_t _http_event_handler(esp_http_client_event_t *evt)
{
switch (evt->event_id)
{
case HTTP_EVENT_ON_DATA:
// Resize the buffer to fit the new chunk of data
response_data = realloc(response_data, response_len + evt->data_len);
memcpy(response_data + response_len, evt->data, evt->data_len);
response_len += evt->data_len;
break;
case HTTP_EVENT_ON_FINISH:
all_chunks_received = true;
ESP_LOGI("OpenWeatherAPI", "Received data: %s", response_data);
get_temp_pressure_humidity(response_data);
break;
default:
break;
}
return ESP_OK;
}
void openweather_api_http(void *pvParameters)
{
char open_weather_map_url[200];
snprintf(open_weather_map_url,
sizeof(open_weather_map_url),
"%s%s%s%s%s%s",
"http://api.openweathermap.org/data/2.5/weather?q=",
city,
",",
country_code,
"&APPID=",
open_weather_map_api_key);
esp_http_client_config_t config = {
.url = open_weather_map_url,
.method = HTTP_METHOD_GET,
.event_handler = _http_event_handler,
};
esp_http_client_handle_t client = esp_http_client_init(&config);
esp_http_client_set_header(client, "Content-Type", "application/x-www-form-urlencoded");
esp_err_t err = esp_http_client_perform(client);
if (err == ESP_OK)
{
int status_code = esp_http_client_get_status_code(client);
if (status_code == 200)
{
ESP_LOGI(TAG, "Message sent Successfully");
}
else
{
ESP_LOGI(TAG, "Message sent Failed");
}
}
else
{
ESP_LOGI(TAG, "Message sent Failed");
}
esp_http_client_cleanup(client);
vTaskDelete(NULL);
}
#define MyHTML "<html><head> <style type=\"text/css\"> \
html { font-family: Arial; display: inline-block; margin: 0px auto; text-align: center;} \
h1{ color: #0F3376; padding: 2vh;}h2{ color: #c81919; padding: 2vh;}\
.button { display: inline-block; background-image: linear-gradient(to bottom right, #d83122, #f18e87, #eb3f32, rgb(255, 122, 89)); //red color border: none; border-radius: 18px; color: #ffffff; padding: 17px 19px; text-decoration: none; font-size: 20px; margin: 0px; cursor: pointer;} \
.button2 { background-image: linear-gradient(to bottom left, #053b81, #378ef2, #1455aa, rgb(2, 122, 89)); //blue color} \
.button3 { background-image: linear-gradient(to bottom left, #bd6019, #f78630, #d88749, rgb(2, 122, 89)); //blue color} \
.content { padding: 50px;} .topnav { overflow: hidden; background-color: #4B1D3F; color: white; font-size: 1.7rem; } \
.cards { max-width: 700px; margin: 0 auto; display: grid; grid-gap: 2rem; grid-template-columns: repeat(auto-fit, minmax(300px, 1fr)); } \
.reading { font-size: 2.8rem; } .card.temperature { color: #0e7c7b; } .card.full { color: #2f0101; } \
.card.humidity { color: #17bebb; } .card.pressure { color: #3fca6b; } .card.gas { color: #d62246; } \
.card-grid { max-width: 800px; margin: 0 auto; display: grid; grid-gap: 2rem; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));} \
.card { background-image: linear-gradient(#FFFFFF,#c1c2cc); box-shadow: 2px 2px 12px 1px rgba(140,140,140,.5);}\
.card-title { font-size: 1.2rem; font-weight: bold; color: #034078} </style> \
<title>PROYECTO MICROPROCESADORES</title> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"> \
<link rel=\"icon\" href=\"data:,\"><link rel=\"stylesheet\" href=\"https://use.fontawesome.com/releases/v5.15.4/css/all.css\" integrity=\"sha384-DyZ88mC6Up2uqS4h/KRgHuoeGwBcD4Ng9SiP4dIRy0EXTlnuz47vAwmeGwVChigm\" crossorigin=\"anonymous\"> <link rel=\"stylesheet\" type=\"text/css\"> </head>\
<body> <h1>Proyecto Microprocesadores</h1><p><i class=\"fas fa-microchip fa-3x\" style=\"color:#0F3376;\"></i></p> <h2>%s</h2> \
<div class=\"content\"> <div class=\"cards\"> <div class=\"card full\"> <p><i class=\"fas fa-cat fa-2x\" style=\"color:#c81919;\"></i> <strong>Alimentador</strong></p> <p> <a href='Servo'><button class=\"button button3\">Servo</button></a> </p> </div>\
<div class=\"card full\"> <p><i class=\"fas fa-lightbulb fa-2x\" style=\"color:#c81919;\"></i> <strong>Luz</strong></p> <p> <a href='ON_LED_R'><button class=\"button\">ON</button></a> <a href='OFF_LED_R'><button class=\"button button2\">OFF</button></a> </p> </div>\
<div class=\"card full\"> <p><i class=\"fas fa-code fa-2x\" style=\"color:#c81919;\"></i> <strong>Contador</strong></p> <p>Contador: <strong> %d</strong></p> </div>\
<div class=\"card full\"> <p><i class=\"fas fa-clock fa-2x\" style=\"color:#c81919;\"></i> <strong>Hora</strong></p> <p>Hora: <strong> %02d:%02d:%02d</strong></p> </div>\
<div class=\"card full\"> <p><i class=\"fas fa-clock fa-2x\" style=\"color:#c81919;\"></i> <strong>Automatico</strong></p> <p>Hora: <strong> %02d:%02d:%02d</strong></p> </div>\
<div class=\"card temperature\"> <h4><i class=\"fas fa-thermometer-half\"></i> TEMPERATURE</h4> <p><span class=\"reading\">%0.00f°C</span></p> </div>\
<div class=\"card humidity\"> <h4><i class=\"fas fa-tint\"></i> HUMIDITY</h4> <p><span class=\"reading\">%d%%</span> %</span> </p> </div>\
<div class=\"card pressure\"> <h4><i class=\"fas fa-angle-double-down\"></i> PRESSURE</h4> <p><span class=\"reading\">%d hPa</span></p> </div>\
<div class=\"card full\"> <p><i class=\"fas fa-clock fa-2x\" style=\"color:#c81919;\"></i> <strong>Cambiar hora automatica</strong></p> <p> <a href='Form'><button class=\"button button3\">Formulario</button></a> </p> </div>\
</div> </div></body></html>"
static const char html_form[] =
"<html>"
"<head>"
"<style>"
"h1{ color: #0F3376; padding: 2vh; margin: 0 auto; width: 400px;}"
"form {margin: 0 auto; width: 400px; padding: 1em; border: 1px solid #CCC; border-radius: 1em;}"
"ul {list-style: none; padding: 0; margin: 0;}"
"form li + li { margin-top: 1em;}"
"label {display: inline-block; width: 90px; text-align: right; }"
"input, textarea {font: 1em sans-serif;width: 300px; box-sizing: border-box; border: 1px solid #999; }"
"input:focus, textarea:focus { border-color: #000;}"
"textarea {vertical-align: top; height: 5em; }"
".button {padding-left: 90px;}"
"button {margin-left: .5em;}"
"</style>"
"</head>"
"<body>"
"<h1>Formulario de alimentador automatico</h1>"
"<form action=\"/echo\" method=\"post\">"
"<ul>"
"<li>"
"<label for=\"hor\"><strong>Hora:</strong></label><br>"
"<input type=\"number\" max=\"23\" min=\"0\" minlength=\"2\" id=\"hor\" name=\"hor\"><br><br>"
"</li>"
"<li>"
"<label for=\"min\"><strong>Minutos:</strong></label><br>"
"<input type=\"number\" max=\"59\" min=\"0\" minlength=\"2\" id=\"min\" name=\"min\"><br><br>"
"</li>"
"<li>"
"<label for=\"seg\"><strong>Segundos:</strong></label><br>"
"<input type=\"number\" max=\"59\" min=\"0\" minlength=\"2\" id=\"seg\" name=\"seg\"><br><br>"
"</li>"
"<button type=\"submit\">Enviar</button>"
"</form>"
"<div>"
"<a href='/'>Inicio</a><br />"
"</div>"
"</body>"
"</html>";
static esp_err_t OFF_LED_R_get_handler(httpd_req_t *req)
{
char *cad;
uint64_t tam;
gpio_set_level(LED_R, 0);
tam = asprintf(&cad, MyHTML, "Luz apagada", contador, TIEMPO.HOR, TIEMPO.MIN, TIEMPO.SEG, TIEMPOA.HOR, TIEMPOA.MIN, TIEMPOA.SEG, temp1, humidity1, pressure1);
if (tam > 0)
{
httpd_resp_set_type(req, "text/html");
httpd_resp_send(req, cad, tam);
}
return ESP_OK;
}
static const httpd_uri_t OFF_LED_R = {
.uri = "/OFF_LED_R",
.method = HTTP_GET,
.handler = OFF_LED_R_get_handler};
static esp_err_t ON_LED_R_get_handler(httpd_req_t *req)
{
char *cad;
uint64_t tam;
gpio_set_level(LED_R, 1);
tam = asprintf(&cad, MyHTML, "Luz encendida", contador, TIEMPO.HOR, TIEMPO.MIN, TIEMPO.SEG, TIEMPOA.HOR, TIEMPOA.MIN, TIEMPOA.SEG, temp1, humidity1, pressure1);
if (tam > 0)
{
httpd_resp_set_type(req, "text/html");
httpd_resp_send(req, cad, tam);
}
return ESP_OK;
}
static const httpd_uri_t ON_LED_R = {
.uri = "/ON_LED_R",
.method = HTTP_GET,
.handler = ON_LED_R_get_handler,
};
static esp_err_t root_get_handler(httpd_req_t *req)
{
char *cad;
uint64_t tam;
tam = asprintf(&cad, MyHTML, "Inicio", contador, TIEMPO.HOR, TIEMPO.MIN, TIEMPO.SEG, TIEMPOA.HOR, TIEMPOA.MIN, TIEMPOA.SEG, temp1, humidity1, pressure1);
if (tam > 0)
{
httpd_resp_set_type(req, "text/html");
httpd_resp_send(req, cad, tam);
}
return ESP_OK;
}
static const httpd_uri_t root = {
.uri = "/",
.method = HTTP_GET,
.handler = root_get_handler,
};
static esp_err_t Servo_get_handler(httpd_req_t *req)
{
char *cad;
uint64_t tam;
v_C = 1;
// contador++;
vTaskDelay(200 / portTICK_PERIOD_MS);
tam = asprintf(&cad, MyHTML, "Alimentado", contador, TIEMPO.HOR, TIEMPO.MIN, TIEMPO.SEG, TIEMPOA.HOR, TIEMPOA.MIN, TIEMPOA.SEG, temp1, humidity1, pressure1);
if (tam > 0)
{
httpd_resp_set_type(req, "text/html");
httpd_resp_send(req, cad, tam);
}
return ESP_OK;
}
static const httpd_uri_t Servo = {
.uri = "/Servo",
.method = HTTP_GET,
.handler = Servo_get_handler};
static esp_err_t Form_get_handler(httpd_req_t *req)
{
/* Enviar el HTML del formulario */
httpd_resp_send(req, html_form, strlen(html_form));
return ESP_OK;
}
static const httpd_uri_t Form = {
.uri = "/Form",
.method = HTTP_GET,
.handler = Form_get_handler};
static esp_err_t echo_post_handler(httpd_req_t *req)
{
char buf[100];
int ret, remaining = req->content_len;
/* Leer los datos enviados en el formulario */
while (remaining > 0)
{
/* Leer el siguiente bloque */
ret = httpd_req_recv(req, buf, MIN(remaining, sizeof(buf)));
if (ret <= 0)
{
/* Error al leer los datos */
if (ret == HTTPD_SOCK_ERR_TIMEOUT)
{
/* Tiempo de espera agotado */
httpd_resp_send_408(req);
}
return ESP_FAIL;
}
/* Actualizar los datos restantes */
remaining -= ret;
}
/* Agregar un carácter nulo al final del mensaje */
buf[sizeof(buf) - 1] = '\0';
/* Imprimir los datos recibidos por el formulario */
ESP_LOGI(TAG, "Datos recibidos");
if ((buf[4] - '0')<10 && (buf[5] - '0')<10 && (buf[11] - '0')<10 && (buf[12] - '0')<10 && (buf[18] - '0')<10 && (buf[19] - '0')<10 )
{
TIEMPOA.HOR = (buf[4] - '0') * 10 + (buf[5] - '0');
TIEMPOA.MIN = (buf[11] - '0') * 10 + (buf[12] - '0');
TIEMPOA.SEG = (buf[18] - '0') * 10 + (buf[19] - '0');
httpd_resp_send(req, "<html><head></head><body><h1>Hora cambiada.</h1> <a href='/'>Inicio</a><br /></body></html>", -1);
}
httpd_resp_send(req, "<html><head></head><body><h1>No se pudo cambiar la hora, son dos digitos por respuesta.</h1> <a href='/'>Inicio</a><br /></body></html>", -1);
return ESP_OK;
}
static const httpd_uri_t echo = {
.uri = "/echo",
.method = HTTP_POST,
.handler = echo_post_handler};
esp_err_t http_404_error_handler(httpd_req_t *req, httpd_err_code_t err)
{
if (strcmp("/hello", req->uri) == 0)
{
httpd_resp_send_err(req, HTTPD_404_NOT_FOUND, "/hello URI is not available");
return ESP_OK;
}
else if (strcmp("/echo", req->uri) == 0)
{
httpd_resp_send_err(req, HTTPD_404_NOT_FOUND, "/echo URI is not available");
/* Return ESP_FAIL to close underlying socket */
return ESP_FAIL;
}
/* For any other URI send 404 and close socket */
httpd_resp_send_err(req, HTTPD_404_NOT_FOUND, "Some 404 error message");
return ESP_FAIL;
}
static httpd_handle_t start_webserver(void)
{
httpd_handle_t server = NULL;
httpd_config_t config = HTTPD_DEFAULT_CONFIG();
config.lru_purge_enable = true;
// Start the httpd server
ESP_LOGI(TAG, "Starting server on port: '%d'", config.server_port);
if (httpd_start(&server, &config) == ESP_OK)
{
// Set URI handlers
ESP_LOGI(TAG, "Registering URI handlers");
httpd_register_uri_handler(server, &OFF_LED_R);
httpd_register_uri_handler(server, &ON_LED_R);
httpd_register_uri_handler(server, &root);
httpd_register_uri_handler(server, &Servo);
httpd_register_uri_handler(server, &Form);
httpd_register_uri_handler(server, &echo);
return server;
}
ESP_LOGI(TAG, "Error starting server!");
return NULL;
}
static esp_err_t stop_webserver(httpd_handle_t server)
{
// Stop the httpd server
return httpd_stop(server);
}
static void disconnect_handler(void *arg, esp_event_base_t event_base,
int32_t event_id, void *event_data)
{
httpd_handle_t *server = (httpd_handle_t *)arg;
if (*server)
{
ESP_LOGI(TAG, "Stopping webserver");
if (stop_webserver(*server) == ESP_OK)
{
*server = NULL;
}
else
{
ESP_LOGE(TAG, "Failed to stop http server");
}
}
}
static void connect_handler(void *arg, esp_event_base_t event_base,
int32_t event_id, void *event_data)
{
httpd_handle_t *server = (httpd_handle_t *)arg;
if (*server == NULL)
{
ESP_LOGI(TAG, "Starting webserver");
*server = start_webserver();
}
}
static void obtain_time(void);
static void initialize_sntp(void);
static const char *TAG3 = "sntp";
void time_sync_notification_cb(struct timeval *tv)
{
ESP_LOGI(TAG3, "Notification of a time synchronization event");
}
void task_time_ntp(void *p)
{
time_t now;
struct tm timeinfo;
time(&now);
localtime_r(&now, &timeinfo);
if (timeinfo.tm_year < (2016 - 1900))
{
ESP_LOGI(TAG3, "Time is not set yet. Connecting to WiFi and getting time over NTP.");
obtain_time();
time(&now);
}
// Set timezone to Eastern Standard Time and print local time
setenv("TZ", "<-04>4", 1);
tzset();
localtime_r(&now, &timeinfo);
strftime(strftime_buf, sizeof(strftime_buf), "%c", &timeinfo);
ESP_LOGI(TAG3, "The current date/time in Merida: %s", strftime_buf);
deletetask = 1;
vTaskDelete(xHandle);
}
static void obtain_time(void)
{
initialize_sntp();
// wait for time to be set
time_t now = 0;
struct tm timeinfo = {0};
int retry = 0;
const int retry_count = 15;
while (sntp_get_sync_status() == SNTP_SYNC_STATUS_RESET && ++retry < retry_count)
{
ESP_LOGI(TAG3, "Waiting for system time to be set... (%d/%d)", retry, retry_count);
vTaskDelay(2000 / portTICK_PERIOD_MS);
}
time(&now);
localtime_r(&now, &timeinfo);
}
static void initialize_sntp(void)
{
ESP_LOGI(TAG3, "Initializing SNTP");
sntp_setoperatingmode(SNTP_OPMODE_POLL);
sntp_setservername(0, "pool.ntp.org");
sntp_setservername(1, "pool.ntp.org"); // set the secondary NTP server (will be used only if SNTP_MAX_SERVERS > 1)
sntp_set_time_sync_notification_cb(time_sync_notification_cb);
sntp_init();
ESP_LOGI(TAG3, "List of configured NTP servers:");
for (uint8_t i = 0; i < SNTP_MAX_SERVERS; ++i)
{
if (sntp_getservername(i))
{
ESP_LOGI(TAG3, "server %d: %s", i, sntp_getservername(i));
}
else
{
// we have either IPv4 or IPv6 address, let's print it
char buff[INET6_ADDRSTRLEN];
ip_addr_t const *ip = sntp_getserver(i);
if (ipaddr_ntoa_r(ip, buff, INET6_ADDRSTRLEN) != NULL)
ESP_LOGI(TAG3, "server %d: %s", i, buff);
}
}
}
void configuracion(void);
void app_main(void)
{
configuracion();
ESP_LOGI(TAG2, "Create timer and operator");
mcpwm_timer_handle_t timer = NULL;
mcpwm_timer_config_t timer_config = {
.group_id = 0,
.clk_src = MCPWM_TIMER_CLK_SRC_DEFAULT,
.resolution_hz = SERVO_TIMEBASE_RESOLUTION_HZ,
.period_ticks = SERVO_TIMEBASE_PERIOD,
.count_mode = MCPWM_TIMER_COUNT_MODE_UP,
};
ESP_ERROR_CHECK(mcpwm_new_timer(&timer_config, &timer));
mcpwm_oper_handle_t oper = NULL;
mcpwm_operator_config_t operator_config = {
.group_id = 0, // operator must be in the same group to the timer
};
ESP_ERROR_CHECK(mcpwm_new_operator(&operator_config, &oper));
ESP_LOGI(TAG2, "Connect timer and operator");
ESP_ERROR_CHECK(mcpwm_operator_connect_timer(oper, timer));
ESP_LOGI(TAG2, "Create comparator and generator from the operator");
mcpwm_cmpr_handle_t comparator = NULL;
mcpwm_comparator_config_t comparator_config = {
.flags.update_cmp_on_tez = true,
};
ESP_ERROR_CHECK(mcpwm_new_comparator(oper, &comparator_config, &comparator));
mcpwm_gen_handle_t generator = NULL;
mcpwm_generator_config_t generator_config = {
.gen_gpio_num = SERVO_PULSE_GPIO,
};
ESP_ERROR_CHECK(mcpwm_new_generator(oper, &generator_config, &generator));
ESP_ERROR_CHECK(mcpwm_comparator_set_compare_value(comparator, angle_to_compare(0)));
ESP_LOGI(TAG2, "Set generator action on timer and compare event");
ESP_ERROR_CHECK(mcpwm_generator_set_actions_on_timer_event(generator,
MCPWM_GEN_TIMER_EVENT_ACTION(MCPWM_TIMER_DIRECTION_UP, MCPWM_TIMER_EVENT_EMPTY, MCPWM_GEN_ACTION_HIGH),
MCPWM_GEN_TIMER_EVENT_ACTION_END()));
ESP_ERROR_CHECK(mcpwm_generator_set_actions_on_compare_event(generator,
MCPWM_GEN_COMPARE_EVENT_ACTION(MCPWM_TIMER_DIRECTION_UP, comparator, MCPWM_GEN_ACTION_LOW),
MCPWM_GEN_COMPARE_EVENT_ACTION_END()));
ESP_LOGI(TAG2, "Enable and start timer");
ESP_ERROR_CHECK(mcpwm_timer_enable(timer));
ESP_ERROR_CHECK(mcpwm_timer_start_stop(timer, MCPWM_TIMER_START_NO_STOP));
static httpd_handle_t server = NULL;
ESP_ERROR_CHECK(nvs_flash_init());
ESP_ERROR_CHECK(esp_netif_init());
ESP_ERROR_CHECK(esp_event_loop_create_default());
ESP_ERROR_CHECK(example_connect());
ESP_ERROR_CHECK(esp_event_handler_register(IP_EVENT, IP_EVENT_STA_GOT_IP, &connect_handler, &server));
ESP_ERROR_CHECK(esp_event_handler_register(WIFI_EVENT, WIFI_EVENT_STA_DISCONNECTED, &disconnect_handler, &server));
server = start_webserver();
xTaskCreate(task_time_ntp, "task_time_ntp", configMINIMAL_STACK_SIZE * 8, NULL, 1000000, &xHandle);
xTaskCreate(&openweather_api_http, "openweather_api_http", 8192, NULL, 6, NULL);
while (deletetask == 0)
{
vTaskDelay(100 / portTICK_PERIOD_MS);
}
TIEMPO.HOR = (strftime_buf[11] - '0') * 10 + (strftime_buf[12] - '0');
TIEMPO.MIN = (strftime_buf[14] - '0') * 10 + (strftime_buf[15] - '0');
TIEMPO.SEG = (strftime_buf[17] - '0') * 10 + (strftime_buf[18] - '0');
TIMER1_Conf();
TIEMPOA.HOR = 12;
TIEMPOA.MIN = 34;
TIEMPOA.SEG = 56;
int angle = 0;
ESP_LOGI(TAG2, "Angulo de rotacion: %d", angle);
ESP_ERROR_CHECK(mcpwm_comparator_set_compare_value(comparator, angle_to_compare(angle)));
vTaskDelay(pdMS_TO_TICKS(500));
while (1)
{
while (v_C == 0)
{
vTaskDelay(100 / portTICK_PERIOD_MS);
if (TIEMPO.SEG == TIEMPOA.SEG && TIEMPO.MIN == TIEMPOA.MIN && TIEMPO.HOR == TIEMPOA.HOR)
{
contador++;
ESP_LOGI(TAG2, "Angulo de rotacion: %d", 45);
ESP_ERROR_CHECK(mcpwm_comparator_set_compare_value(comparator, angle_to_compare(45)));
vTaskDelay(pdMS_TO_TICKS(1000));
ESP_LOGI(TAG2, "Angulo de rotacion: %d", 0);
ESP_ERROR_CHECK(mcpwm_comparator_set_compare_value(comparator, angle_to_compare(0)));
vTaskDelay(pdMS_TO_TICKS(500));
}
}
contador++;
vTaskDelay(500 / portTICK_PERIOD_MS);
v_C = 0;
ESP_LOGI(TAG2, "Angulo de rotacion: %d", 45);
ESP_ERROR_CHECK(mcpwm_comparator_set_compare_value(comparator, angle_to_compare(45)));
vTaskDelay(pdMS_TO_TICKS(2000));
ESP_LOGI(TAG2, "Angulo de rotacion: %d", 0);
ESP_ERROR_CHECK(mcpwm_comparator_set_compare_value(comparator, angle_to_compare(0)));
vTaskDelay(pdMS_TO_TICKS(500));
}
}
static inline uint32_t angle_to_compare(int angle)
{
return (angle - SERVO_MIN_DEGREE) * (SERVO_MAX_PULSEWIDTH_US - SERVO_MIN_PULSEWIDTH_US) / (SERVO_MAX_DEGREE - SERVO_MIN_DEGREE) + SERVO_MIN_PULSEWIDTH_US;
}
void C_isr(void *arg)
{
v_C = 1;
}
void configuracion(void)
{
gpio_reset_pin(LED_R);
gpio_set_direction(LED_R, GPIO_MODE_OUTPUT);
gpio_set_level(LED_R, 0);
// interrupcion C
gpio_config_t C_cfg;
C_cfg.pin_bit_mask = (1ULL << C);
C_cfg.mode = GPIO_MODE_DEF_INPUT;
C_cfg.pull_up_en = GPIO_PULLUP_DISABLE;
C_cfg.pull_down_en = GPIO_PULLDOWN_DISABLE;
C_cfg.intr_type = GPIO_INTR_NEGEDGE;
gpio_config(&C_cfg);
gpio_install_isr_service(0);
gpio_isr_handler_add(C, C_isr, NULL);
}
void TIMER1_Conf(void)
{
Timer1 = xTimerCreate("Timer1",
pdMS_TO_TICKS(1000),
pdTRUE,
(void *)&Timer1_ID,
vTimerCallback);
if (Timer1 == NULL)
{
printf("No puedo crear el Timer\n");
}
else
{
if (xTimerStart(Timer1, 0) != pdPASS)
{
printf("No pudo iniciar el Timer\n");
}
}
}
void vTimerCallback(TimerHandle_t pxTimer)
{
if (TIEMPO.SEG < 59)
TIEMPO.SEG++;
else
{
TIEMPO.SEG = 0;
if (TIEMPO.MIN < 59)
TIEMPO.MIN++;
else
{
TIEMPO.MIN = 0;
if (TIEMPO.HOR < 23)
TIEMPO.HOR++;
else
TIEMPO.HOR = 0;
}
}
}