// Carrega a biblioteca Wi-Fi
#include <WiFi.h>
// Associa as variáveis de saída aos pinos GPIO
#define output26 26
#define output27 27
//const char* ssid = "Smartenergy"; //<----------Mude para o seu
//const char* password = "SmartEnergy"; //<----------Mude para o seu
//const char* ssid = "sala203"; //<----------Mude para o seu
//const char* password = "s@l@203#"; //<----------Mude para o seu
//const char* ssid = "NPITI-IoT"; //<----------Mude para o seu
//const char* password = "NPITI-IoT"; //<----------Mude para o seu
const char* ssid = "Wokwi-GUEST";
const char* password ="";
// Define o número da porta do servidor web como 80
WiFiServer server(80);
// Variável para armazenar a requisição HTTP
String header;
// Variáveis auxiliares para armazenar o estado atual da saída
String output26State = "off";
String output27State = "off";
// Tempo atual
unsigned long currentTime = millis();
// Tempo anterior
unsigned long previousTime = 0;
// Define o tempo de timeout em milissegundos (exemplo: 2000ms = 2s)
const long timeoutTime = 2000;
void setup() {
Serial.begin(115200);
// Inicializa as variáveis de saída como saídas (OUTPUT)
pinMode(output26, OUTPUT);
pinMode(output27, OUTPUT);
// Define as saídas como LOW (desligadas)
digitalWrite(output26, LOW);
digitalWrite(output27, LOW);
// Conecta à rede Wi-Fi com SSID e senha
Serial.print("Conectando a ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
// Imprime o endereço IP local e inicia o servidor web
Serial.println("");
Serial.println("WiFi conectado.");
Serial.println("Endereço IP: ");
Serial.println(WiFi.localIP());
server.begin();
}
void loop(){
WiFiClient client = server.available(); // Aguarda por clientes se conectando
if (client) { // Se um novo cliente se conectar,
currentTime = millis();
previousTime = currentTime;
Serial.println("Novo Cliente."); // imprime uma mensagem na porta serial
String currentLine = ""; // cria uma String para armazenar os dados recebidos do cliente
while (client.connected() && currentTime - previousTime <= timeoutTime) { // repete enquanto o cliente estiver conectado
currentTime = millis();
if (client.available()) { // se houver bytes para ler do cliente,
char c = client.read(); // lê um byte, e então
Serial.write(c); // o imprime no monitor serial
header += c;
if (c == '\n') { // se o byte for um caractere de nova linha
// se a linha atual estiver em branco, você tem dois caracteres de nova linha seguidos.
// esse é o fim da requisição HTTP do cliente, então envie uma resposta:
if (currentLine.length() == 0) {
// Cabeçalhos HTTP sempre começam com um código de resposta (ex. HTTP/1.1 200 OK)
// e um content-type para que o cliente saiba o que está vindo, seguido de uma linha em branco:
client.println("HTTP/1.1 200 OK");
client.println("Content-type:text/html");
client.println("Connection: close");
client.println();
// liga e desliga os GPIOs
if (header.indexOf("GET /26/on") >= 0) {
Serial.println("GPIO 26 ligado");
output26State = "on";
digitalWrite(output26, HIGH);
} else if (header.indexOf("GET /26/off") >= 0) {
Serial.println("GPIO 26 desligado");
output26State = "off";
digitalWrite(output26, LOW);
} else if (header.indexOf("GET /27/on") >= 0) {
Serial.println("GPIO 27 ligado");
output27State = "on";
digitalWrite(output27, HIGH);
} else if (header.indexOf("GET /27/off") >= 0) {
Serial.println("GPIO 27 desligado");
output27State = "off";
digitalWrite(output27, LOW);
}
// Exibe a página web HTML
client.println("<!DOCTYPE html><html>");
client.println("<head><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">");
client.println("<link rel=\"icon\" href=\"data:,\">");
// CSS para estilizar os botões de ligar/desligar
// Sinta-se à vontade para alterar os atributos background-color e font-size para adequar às suas preferências
client.println("<style>html { font-family: Helvetica; display: inline-block; margin: 0px auto; text-align: center;}");
client.println(".button { background-color: #4CAF50; border: none; color: white; padding: 16px 40px;");
client.println("text-decoration: none; font-size: 30px; margin: 2px; cursor: pointer;}");
client.println(".button2 {background-color: #555555;}</style></head>");
// Cabeçalho da Página Web
client.println("<body><h1>Servidor Web ESP32</h1>");
// Exibe o estado atual e os botões LIGA/DESLIGA para o GPIO 26
client.println("<p>GPIO 26 - Estado " + output26State + "</p>");
// Se o estado do output26 for "off", exibe o botão LIGA
if (output26State=="off") {
client.println("<p><a href=\"/26/on\"><button class=\"button\">LIGA</button></a></p>");
} else {
client.println("<p><a href=\"/26/off\"><button class=\"button button2\">DESLIGA</button></a></p>");
}
// Exibe o estado atual e os botões LIGA/DESLIGA para o GPIO 27
client.println("<p>GPIO 27 - Estado " + output27State + "</p>");
// Se o estado do output27 for "off", exibe o botão LIGA
if (output27State=="off") {
client.println("<p><a href=\"/27/on\"><button class=\"button\">LIGA</button></a></p>");
} else {
client.println("<p><a href=\"/27/off\"><button class=\"button button2\">DESLIGA</button></a></p>");
}
client.println("</body></html>");
// A resposta HTTP termina com outra linha em branco
client.println();
// Sai do loop while
break;
} else { // se receber uma nova linha, limpa a currentLine
currentLine = "";
}
} else if (c != '\r') { // se receber qualquer outra coisa que não seja um caractere de retorno de carro,
currentLine += c; // adiciona ao final da currentLine
}
}
}
// Limpa a variável header
header = "";
// Fecha a conexão
client.stop();
Serial.println("Cliente desconectado.");
Serial.println("");
}
}