#include <Arduino.h>
#include <WiFi.h>
#include <freertos/FreeRTOS.h>
#include <freertos/task.h>
#include <freertos/semphr.h>
#include <math.h>
#define BLYNK_TEMPLATE_ID "TMPL2dJBoN1Rh"
#define BLYNK_TEMPLATE_NAME "Aula 4"
#define BLYNK_AUTH_TOKEN "nkYKZ-U_USPlQRbgPY_Ar0cWh1lA1ArJ"
#include <BlynkSimpleEsp32.h>
char auth[] = BLYNK_AUTH_TOKEN;
char ssid[] = "Wokwi-GUEST";
char pass[] = "";
#define PIN_GAS 34
#define PIN_TEMP 33
#define PIN_RELE 18
#define ALERTA 2
#define BETA 3950.0 // constante do termistor
#define TEMP_INI 25.0
volatile float valor_temp = 0;
volatile int valor_gas = 0;
volatile bool alertaSilenciado = false;
const float BETA = 3950;
const float TEMP_INI = 25.0;
float valor_temp;
SemaphoreHandle_t semaforoLCD;
void TaskSensorGas(void *pvParameters);
void TaskSensorTemp(void *pvParameters);
void Taskserial(void *pvParameters);
void setup() {
Serial.begin(115200);
Blynk.begin(auth, ssid, pass);
semaforoLCD = xSemaphoreCreateMutex();
xSemaphoreGive(semaforoLCD);
analogSetAttenuation(ADC_11db);
pinMode(PIN_RELE, OUTPUT);
digitalWrite(PIN_RELE, LOW);
xTaskCreatePinnedToCore(TaskSensorGas, "GasTask", 10000, NULL, 1, NULL, 0);
xTaskCreatePinnedToCore(TaskSensorTemp, "TempTask", 10000, NULL, 1, NULL, 1);
xTaskCreate(Taskserial, "IHM_Task", 10000, NULL, 2, NULL);
}
void TaskSensorGas(void *pvParameters) {
for (;;) {
int adc = analogRead(PIN_GAS);
if (xSemaphoreTake(semaforoLCD, (TickType_t)5) == pdTRUE) {
if (valor_gas > 1800) {
digitalWrite(PIN_RELE, HIGH);
digitalWrite(ALERTA, HIGH);
} else {
digitalWrite(PIN_RELE, LOW);
digitalWrite(ALERTA, LOW);
}
Blynk.virtualWrite(V1, valor_gas);
xSemaphoreGive(semaforoLCD);
}
vTaskDelay(pdMS_TO_TICKS(400));
}
}
void TaskSensorTemp(void *pvParameters) {
for (;;) {
int analogValue = analogRead(PIN_TEMP);
if (xSemaphoreTake(semaforoLCD, (TickType_t)5) == pdTRUE) {
float celsius = 1.0 / (log(1.0 / (4095.0 / analogValue - 1.0)) / BETA +
1.0 / (273.15 + TEMP_INI)) - 273.15;
valor_temp = celsius;
Blynk.virtualWrite(V2, valor_temp);
xSemaphoreGive(semaforoLCD);
}
vTaskDelay(pdMS_TO_TICKS(600));
}
}
void Taskserial(void *pvParameters) {
for (;;) {
int adc = analogRead(PIN_GAS);
valor_gas = map(adc, 0, 4095, 400, 5000);
Serial.printf("PPM: %d | Core: %d\n", valor_gas, xPortGetCoreID());
Serial.printf("TEMP %.1f C | Core: %d\n", valor_temp, xPortGetCoreID());
vTaskDelay(pdMS_TO_TICKS(100));
}
}
void loop() {
Blynk.run();
}