0% found this document useful (0 votes)
1 views12 pages

Iot Meu Codigo Final

This document contains an Arduino code for an ESP8266-based temperature monitoring system using a DHT11 sensor. It connects to WiFi, reads temperature data, controls a relay based on temperature thresholds, and serves a web interface to display the temperature and relay status. The web interface includes a gauge for temperature visualization and updates every two seconds.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views12 pages

Iot Meu Codigo Final

This document contains an Arduino code for an ESP8266-based temperature monitoring system using a DHT11 sensor. It connects to WiFi, reads temperature data, controls a relay based on temperature thresholds, and serves a web interface to display the temperature and relay status. The web interface includes a gauge for temperature visualization and updates every two seconds.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 12

#include <ESP8266WiFi.

h>
#include <ESP8266WebServer.h>
#include <DHT11.h>

#define DHTPIN D4
#define RELAY_PIN D3

const char* ssid = "ESPwifi";


const char* password = "12345678";

DHT11 dht11(DHTPIN);
ESP8266WebServer server(80);

float temperature = 0;

unsigned long relayOnTime = 0;


bool relayActive = false;

bool cooldown = false;


unsigned long cooldownStart = 0;

void setup() {
Serial.begin(9600);
pinMode(RELAY_PIN, OUTPUT);
digitalWrite(RELAY_PIN, HIGH); // RELÉ desligado inicialmente

WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Conectando ao WiFi...");
}
Serial.println("Conectado ao WiFi");
Serial.println(WiFi.localIP());
server.on("/", HTTP_GET, handleRoot);
server.on("/data", HTTP_GET, handleData);

server.begin();
Serial.println("Servidor HTTP iniciado");
}

void loop() {
server.handleClient();

float newTemp = dht11.readTemperature();


if (newTemp != DHT11::ERROR_CHECKSUM && newTemp !=
DHT11::ERROR_TIMEOUT) {
temperature = newTemp;
Serial.print("Temperatura lida: ");
Serial.println(temperature);
} else {
Serial.println("Erro na leitura do DHT11!");
}

unsigned long now = millis();

if (cooldown) {
if (now - cooldownStart >= 30000) {
cooldown = false;
Serial.println("Descanso finalizado, pode ligar novamente.");
} else {
digitalWrite(RELAY_PIN, HIGH); // Desliga
relayActive = false;
}
} else {
if (temperature >= 24) {
if (!relayActive) {
relayOnTime = now;
relayActive = true;
digitalWrite(RELAY_PIN, LOW); // Liga
Serial.println("Relé LIGADO!");
} else if (now - relayOnTime >= 60000) {
digitalWrite(RELAY_PIN, HIGH); // Desliga após 1 minuto
relayActive = false;
cooldown = true;
cooldownStart = now;
Serial.println("Relé DESLIGADO após 1 minuto. Iniciando descanso de 30
segundos.");
}
} else {
digitalWrite(RELAY_PIN, HIGH); // Desliga se temperatura < 24
relayActive = false;
}
}

delay(2000);
}

void handleRoot() {
server.send(200, "text/html", webpage());
}

void handleData() {
bool relayStatus = digitalRead(RELAY_PIN);
String json = "{\"temperature\":" + String(temperature) +
",\"status\":\"" + (relayStatus == LOW ? "Ligado" : "Desligado") + "\"}";
server.send(200, "application/json", json);
}

String webpage() {
String html = R"=====(<!DOCTYPE html>
<html lang="pt-BR">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Monitoramento de Temperatura</title>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<style>
body { font-family: Arial, sans-serif; background-color: #121212; color: white; text-
align: center; }
.gauge-container { position: relative; width: 300px; height: 300px; margin: auto; }
#temperatureDisplay { position: absolute; top: 45%; left: 50%; transform: translate(-
50%, -50%); font-size: 24px; font-weight: bold; }
.status-box {
display: inline-block;
margin-top: 20px;
padding: 10px 20px;
border-radius: 10px;
font-size: 20px;
font-weight: bold;
}
.ligado {
background-color: #00cc00;
color: #fff;
border: 2px solid #00cc00;
}
.desligado {
background-color: #cc0000;
color: #fff;
border: 2px solid #cc0000;
}
</style>
</head>
<body>
<h1>Sistema de Monitoramento de Temperatura</h1>
<div class="gauge-container">
<canvas id="temperatureGauge"></canvas>
<div id="temperatureDisplay">-- °C</div>
</div>
<div id="statusBox" class="status-box desligado">Aparelho: Desligado</div>

<script>
const ctx = document.getElementById('temperatureGauge').getContext('2d');
const gauge = new Chart(ctx, {
type: 'doughnut',
data: {
labels: ['Temperatura'],
datasets: [{ data: [0, 50], backgroundColor: ['blue', 'lightgray'] }]
},
options: {
circumference: 270, rotation: 225, cutout: '80%', plugins: { legend: { display:
false } }
}
});

function updateGauge(temp) {
gauge.data.datasets[0].data = [temp, 50 - temp];
gauge.update();
document.getElementById("temperatureDisplay").innerText = temp + " °C";
}

function updateStatus(status) {
const box = document.getElementById("statusBox");
if (status === "Ligado") {
box.textContent = "Aparelho: Ligado";
box.className = "status-box ligado";
} else {
box.textContent = "Aparelho: Desligado";
box.className = "status-box desligado";
}
}

async function fetchData() {


try {
const response = await fetch('/data');
const data = await response.json();
updateGauge(data.temperature);
updateStatus(data.status);
} catch (error) {
console.error("Erro ao buscar dados:", error);
}
}

setInterval(fetchData, 2000);
fetchData();
</script>
</body>
</html>)=====";
return html;
}
#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>
#include <DHT11.h>

#define DHTPIN D4
#define RELAY_PIN D3

const char* ssid = "Anastácio Walker";


const char* password = "12345678";

DHT11 dht11(DHTPIN);
ESP8266WebServer server(80);
float temperature = 0;

void setup() {
Serial.begin(115200);
pinMode(RELAY_PIN, OUTPUT);
digitalWrite(RELAY_PIN, LOW);

WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Conectando ao WiFi...");
}
Serial.println("Conectado ao WiFi");
Serial.println(WiFi.localIP());

server.on("/", HTTP_GET, handleRoot);


server.on("/data", HTTP_GET, handleData);
server.begin();
Serial.println("Servidor HTTP iniciado");
}

void loop() {
server.handleClient();

float newTemp = dht11.readTemperature();


if (newTemp != DHT11::ERROR_CHECKSUM && newTemp !=
DHT11::ERROR_TIMEOUT) {
temperature = newTemp;
Serial.print("Temperatura lida: ");
Serial.println(temperature);
} else {
Serial.println("Erro na leitura do DHT11!");
}
if (temperature >= 25) {
digitalWrite(RELAY_PIN, HIGH);
} else {
digitalWrite(RELAY_PIN, LOW);
}

delay(2000);
}

void handleRoot() {
server.send(200, "text/html", webpage());
}

void handleData() {
bool relayStatus = digitalRead(RELAY_PIN);
String json = "{\"temperature\":" + String(temperature) +
",\"status\":\"" + (relayStatus ? "Ligado" : "Desligado") +
"\"}";
server.send(200, "application/json", json);
}

String webpage() {
String html = R"=====(
<!DOCTYPE html>
<html lang="pt-BR">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Climatização Inteligente</title>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<style>
body {
font-family: 'Arial', sans-serif;
background-color: #121212;
color: white;
text-align: center;
padding: 20px;
}
h1 {
font-size: 28px;
margin-bottom: 10px;
}
.gauge-container {
position: relative;
width: 300px;
height: 300px;
margin: auto;
}
#temperatureDisplay {
position: absolute;
top: 45%;
left: 50%;
transform: translate(-50%, -50%);
font-size: 64px;
font-weight: bold;
color: #00BFFF;
}
.status {
font-size: 28px;
margin-top: 20px;
padding: 10px;
border-radius: 10px;
display: inline-block;
font-weight: bold;
}
.status.ligado {
background-color: #28a745;
color: white;
}
.status.desligado {
background-color: #dc3545;
color: white;
}
</style>
</head>
<body>
<h1>Sistema de Monitoramento de Temperatura</h1>
<div class="gauge-container">
<canvas id="temperatureGauge"></canvas>
<div id="temperatureDisplay"></div>
</div>
<div id="systemStatus" class="status desligado">Aparelho: Desligado</div>

<script>
const ctx = document.getElementById('temperatureGauge').getContext('2d');
const gauge = new Chart(ctx, {
type: 'doughnut',
data: {
labels: ['Temperatura'],
datasets: [{ data: [0, 50], backgroundColor: ['blue', 'lightgray'] }]
},
options: {
circumference: 270,
rotation: 225,
cutout: '80%',
plugins: { legend: { display: false } }
}
});

function updateGauge(temp) {
gauge.data.datasets[0].data = [temp, 50 - temp];
gauge.update();
document.getElementById("temperatureDisplay").innerText = temp + " °C";
}

function updateStatus(status) {
const statusDiv = document.getElementById('systemStatus');
statusDiv.innerText = 'Aparelho: ' + status;
statusDiv.className = status === 'Ligado' ? 'status ligado' : 'status desligado';
}

async function fetchData() {


try {
const response = await fetch('/data');
const data = await response.json();
updateGauge(data.temperature);
updateStatus(data.status);
} catch (error) {
console.error("Erro ao buscar dados:", error);
}
}

setInterval(fetchData, 2000);
fetchData();
</script>
</body>
</html>
)=====";
return html;
}

You might also like