Tambem tenho o mesmo problema consigo enviar codigo via web mais não recebo a varialvel analogica do mega Use esta tag para formatar o código para o fórum segue codigo do master #include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>
// --- Configuração WiFi ---
const char* ssid = " ";
const char* password = "";
ESP8266WebServer server(80);
// --- Variáveis de LED e Comunicação ---
const int ledPin = 2;
const long blinkDuration = 5000;
unsigned long previousMillis = 0;
bool ledState = false;
bool communicationEnabled = false;
// --- Variáveis para Valor Analógico do Mega ---
String megaAnalogString = "N/A";
int megaAnalogPercentage = -1;
String megaStatusMessage = "Aguardando valor...";
unsigned long lastRequestTime = 0;
const long requestInterval = 2000;
// --- Buffer Serial ---
String receivedDataBuffer = "";
bool newDataAvailable = false;
// --- Página HTML estilizada ---
void handleRoot() {
String html = R"=====(ESP8266 Master Control
body { font-family: Arial; background: #f0f4f8; color: #333; margin: 0; padding: 0; }
.container { max-width: 600px; margin: 40px auto; padding: 20px; background: #fff; border-radius: 10px; box-shadow: 0 4px 10px rgba(0,0,0,0.1); }
h1 { text-align: center; color: #0077cc; }
.status, .analog { margin: 20px 0; padding: 15px; background: #eaf6ff; border-left: 6px solid #0077cc; border-radius: 6px; }
.buttons { text-align: center; margin-top: 20px; }
.buttons a button { margin: 10px; padding: 12px 20px; font-size: 16px; border: none; border-radius: 5px; cursor: pointer; transition: background 0.3s; }
.start { background-color: #4CAF50; color: white; } .start:hover { background-color: #45a049; }
.stop { background-color: #f44336; color: white; } .stop:hover { background-color: #d32f2f; }
.request { background-color: #008CBA; color: white; } .request:hover { background-color: #007bb5; }
.footer { margin-top: 30px; font-size: 14px; color: #555; text-align: center; }
ESP8266 Master Control
Comunicação: <span style="font-weight:bold; color:)=====";
html += (communicationEnabled ? "#4CAF50">ATIVA" : "#f44336">INATIVA");
html += R"=====(
Status do Potenciômetro (A0)
)=====";
html += megaStatusMessage + " — ";
if (megaAnalogPercentage != -1) {
html += String(megaAnalogPercentage) + "%";
} else {
html += "N/A";
}
html += R"=====(
Verifique o Monitor Serial do Mega2560 para detalhes da comunicação.
)=====";
server.send(200, "text/html", html);
}
// --- Handlers Web ---
void handleStart() {
communicationEnabled = true;
Serial.write('S');
server.sendHeader("Location", "/", true);
server.send(302, "text/plain", "");
}
void handleStop() {
communicationEnabled = false;
digitalWrite(ledPin, LOW);
Serial.write('P');
server.sendHeader("Location", "/", true);
server.send(302, "text/plain", "");
}
void handleRequestAnalog() {
Serial.write('R');
delay(100); // Permite tempo para resposta antes da próxima requisição
lastRequestTime = millis();
server.sendHeader("Location", "/", true);
server.send(302, "text/plain", "");
}
void handleNotFound() {
server.send(404, "text/plain", "Not found");
}
void updateStatusMessage(int percentage) {
if (percentage >= 0 && percentage <= 25) {
megaStatusMessage = "Lento";
} else if (percentage > 25 && percentage <= 50) {
megaStatusMessage = "Tamo Indo";
} else if (percentage > 50 && percentage <= 90) {
megaStatusMessage = "Ai Sim";
} else if (percentage > 90 && percentage <= 95) {
megaStatusMessage = "Ta Bão";
} else if (percentage > 95 && percentage <= 100) {
megaStatusMessage = "Se Doido";
} else {
megaStatusMessage = "Valor Fora do Alcance";
}
}
// --- Setup ---
void setup() {
Serial.begin(9600);
while (Serial.available()) Serial.read(); // Limpa buffer
pinMode(ledPin, OUTPUT);
digitalWrite(ledPin, LOW);
WiFi.begin(ssid, password);
int attempts = 0;
while (WiFi.status() != WL_CONNECTED && attempts < 20) {
delay(500);
attempts++;
}
server.on("/", handleRoot);
server.on("/start", handleStart);
server.on("/stop", handleStop);
server.on("/request_analog", handleRequestAnalog);
server.onNotFound(handleNotFound);
server.begin();
}
// --- Loop ---
void loop() {
server.handleClient();
while (Serial.available()) {
char inChar = Serial.read();
if (inChar == '\n') {
newDataAvailable = true;
break;
} else {
receivedDataBuffer += inChar;
}
}
if (newDataAvailable) {
int value = receivedDataBuffer.toInt();
if (value >= 0 && value <= 100) {
megaAnalogPercentage = value;
updateStatusMessage(megaAnalogPercentage);
} else {
megaAnalogPercentage = -1;
megaStatusMessage = "Valor inválido recebido!";
}
receivedDataBuffer = "";
newDataAvailable = false;
}
if (communicationEnabled) {
unsigned long currentMillis = millis();
if (currentMillis - previousMillis >= blinkDuration) {
previousMillis = currentMillis;
ledState = !ledState;
digitalWrite(ledPin, ledState);
Serial.write(ledState ? 'H' : 'L');
}
if (currentMillis - lastRequestTime >= requestInterval) {
Serial.write('R');
lastRequestTime = currentMillis;
}
} else {
if (digitalRead(ledPin) == HIGH) {
digitalWrite(ledPin, LOW);
}
ledState = false;
}
}
segue codigo do slave `// Arduino Mega2560 (Slave) Code - REVISÃO FINAL E DEFINITIVA PARA COMUNICAÇÃO TOTALMENTE LIMPA
// Inclui leitura do A0, conversão para porcentagem, e lógica de LED alternada
const int ledPin = 8; // LED conectado ao pino digital 8
const long blinkDuration = 10000; // Duração de 10 segundos para o LED do Mega (ON)
unsigned long previousMillis = 0;
bool ledState = false; // Rastreia o estado do LED do Mega
// Variáveis para Leitura Analógica
const int analogInputPin = A0; // Potenciômetro conectado ao A0
int analogValue = 0; // Variável para guardar o valor bruto do A0 (0-1023)
int percentageValue = 0; // Variável para guardar o valor convertido em porcentagem (0-100)
void setup() {
Serial.begin(9600); // <<== ESTE É APENAS PARA O MONITOR SERIAL DO SEU PC (VIA USB)
// Todas as mensagens de debug para VOCÊ devem usar 'Serial.print' ou 'Serial.println'
Serial3.begin(9600); // <<== ESTE É APENAS PARA COMUNICAÇÃO COM O ESP8266
// NENHUMA MENSAGEM DE DEBUG DEVE SER ENVIADA POR AQUI, EXCETO OS DADOS NECESSÁRIOS.
pinMode(ledPin, OUTPUT);
pinMode(analogInputPin, INPUT);
digitalWrite(ledPin, HIGH); // Inicia o LED do Mega LIGADO, pois o LED do ESP iniciará DESLIGADO
ledState = true;
previousMillis = millis(); // Inicializa o timer para o LED do Mega
// Mensagem de depuração inicial APENAS para o Monitor Serial do seu PC (via USB)
Serial.println("Mega2560 Slave inicializado. Aguardando comandos do ESP8266.");
}
void loop() {
unsigned long currentMillis = millis();
if (Serial3.available()) {
char receivedChar = Serial3.read();``