#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include <WiFi.h>
#include <PubSubClient.h>
const char* ssid = "Wokwi-GUEST";
const char* password = "";
const char* mqtt_server = "broker.hivemq.com";
WiFiClient espClient;
PubSubClient client(espClient);
unsigned long lastMsg = 0;
#define MSG_BUFFER_SIZE (50)
// Define o pino GPIO para o LED vermelho e o botão
#define LED_PIN_RED GPIO_NUM_21
#define BUTTON_RED GPIO_NUM_15
// Define os estados do botão
#define BTN_PRESSED (1)
#define BTN_NOT_PRESSED (0)
// Configuração da Tarefa 2
#define TASK_2_NAME "ligar led"
#define TASK_2_STACK_SIZE (configMINIMAL_STACK_SIZE * 4)
#define TASK_2_PRIORITY (tskIDLE_PRIORITY + 1)
// Configuração da Tarefa 3
#define TASK_3_NAME "botao"
#define TASK_3_STACK_SIZE (configMINIMAL_STACK_SIZE * 4)
#define TASK_3_PRIORITY (tskIDLE_PRIORITY + 2)
//....................................................//
void setup_wifi() {
delay(10);
// We start by connecting to a WiFi network
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
randomSeed(micros());
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}
//....................................................//
void callback(char* topic, byte* payload, unsigned int length) {
Serial.print("Message arrived [");
Serial.print(topic);
Serial.print("] ");
for (int i = 0; i < length; i++) {
Serial.print((char)payload[i]);
}
Serial.println();
// Switch on the LED if an 1 was received as first character
if ((char)payload[0] == '1') {
digitalWrite(2, LOW); // Turn the LED on (Note that LOW is the voltage level
// but actually the LED is on; this is because
// it is active low on the ESP-01)
} else {
digitalWrite(2, HIGH); // Turn the LED off by making the voltage HIGH
}
}
void reconnect() {
// Loop until we're reconnected
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
// Create a random client ID
String clientId = "ESP8266Client-";
clientId += String(random(0xffff), HEX);
// Attempt to connect
if (client.connect(clientId.c_str())) {
Serial.println("Connected");
// Once connected, publish an announcement...
client.publish("iotfrontier/mqtt", "iotfrontier");
// ... and resubscribe
client.subscribe("iotfrontier/mqtt");
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
}
}
}
//....................................................//
//....................................................////....................................................//
//....................................................////....................................................//
//....................................................////....................................................//
// Declaração das funções
static void task_2(void *arg);
static void task_3(void *arg);
// Declaração dos identificadores das tarefas
static TaskHandle_t xtask_handle_2 = NULL;
static TaskHandle_t xtask_handle_3 = NULL;
void setup()
{
setup_wifi();
client.setServer(mqtt_server, 1883);
client.setCallback(callback);
BaseType_t xReturn = pdPASS;
// Cria a Tarefa 2
xReturn = xTaskCreate(&task_2,
TASK_2_NAME,
TASK_2_STACK_SIZE,
NULL,
TASK_2_PRIORITY,
&xtask_handle_2);
if (xReturn != pdPASS || xtask_handle_2 == NULL) {
printf("Erro ao criar a tarefa 2\n");
}
// Cria a Tarefa 3
xReturn = xTaskCreate(&task_3,
TASK_3_NAME,
TASK_3_STACK_SIZE,
NULL,
TASK_3_PRIORITY,
&xtask_handle_3);
if (xReturn != pdPASS || xtask_handle_3 == NULL) {
printf("Erro ao criar a tarefa 3\n");
}
// Suspende a Tarefa 2 inicialmente
vTaskSuspend(xtask_handle_2);
}
// Tarefa 2: Pisca o LED
static void task_2(void *arg)
{
// Configura o pino GPIO para o LED vermelho
gpio_pad_select_gpio(LED_PIN_RED);
gpio_set_direction(LED_PIN_RED, GPIO_MODE_OUTPUT);
while (true) {
// Alterna o estado do LED vermelho
gpio_set_level(LED_PIN_RED, 1);
vTaskDelay(100 / portTICK_RATE_MS);
}
}
// Tarefa 3: Monitora o estado do botão vermelho e controla a Tarefa 2 conforme necessário
static void task_3(void *arg)
{
while (true) {
// Atraso para evitar verificações excessivas
vTaskDelay(pdMS_TO_TICKS(500));
// Lê o estado do botão vermelho
int val = gpio_get_level(BUTTON_RED);
if (val == BTN_PRESSED) {
// Se o botão estiver pressionado, retoma a Tarefa 2 e registra a ação
vTaskResume(xtask_handle_2);
ESP_LOGE("main", "LED LIGADO");
client.publish("iotfrontier/led", "on");
} else {
// Se o botão não estiver pressionado, suspende a Tarefa 2, desliga o LED e registra a ação
vTaskSuspend(xtask_handle_2);
gpio_set_level(LED_PIN_RED, 0);
ESP_LOGE("main", "LED DESLIGADO");
client.publish("iotfrontier/led", "off");
}
}
}
void loop() {
if (!client.connected()) {
reconnect();
}
client.loop();
unsigned long now = millis();
if (now - lastMsg > 1000) {
lastMsg = now;
}
}Loading
franzininho-wifi
franzininho-wifi