Escrever e ler na eeprom

Preciso que ao ligar o esp ele imprima o que esta gravado na memoria, no caso no void setup ( ), o que eu havia tentado estava imprimindo um dado nao condizente com o que estava na memoria EEPROM.

33
SSID
GET /: ola HTTP/1.1TP/1.12:05:477

[code]
#include <ESP8266WiFi.h>
#include <ESP8266mDNS.h>
#include <ESP8266WebServer.h>
#include <WiFiUdp.h>
#include <ArduinoOTA.h>
#include <Ticker.h>
#include <TimeLib.h>
#include <EEPROM.h>

const char* ssid = “PR-LINK”;
const char* pass = “35280000”;

WiFiServer server (80);

String s;
String esid;
int i = 0;
String request;
int _addrByte = 0;
String str;
int value;

#define LEAP_YEAR(_year) ((_year%4)==0)
static byte monthDays[] = {31, 28, 31, 30 , 31, 30, 31, 31, 30, 31, 30, 31};

void localTime(unsigned long *timep, byte *psec, byte *pmin, byte *phour, byte *pday, byte *pwday, byte *pmonth, byte pyear) {
unsigned long long epoch =
timep;
byte year;
byte month, monthLength;
unsigned long days;

*psec = epoch % 60;
epoch /= 60; // now it is minutes
*pmin = epoch % 60;
epoch /= 60; // now it is hours
*phour = epoch % 24;
epoch /= 24; // now it is days
*pwday = (epoch+4) % 7;

year = 70;
days = 0;
while((unsigned)(days += (LEAP_YEAR(year) ? 366 : 365)) <= epoch) { year++; }
*pyear=year; // *pyear is returned as years from 1900

days -= LEAP_YEAR(year) ? 366 : 365;
epoch -= days; // now it is days in this year, starting at 0

for (month=0; month<12; month++) {
monthLength = ( (month==1) && LEAP_YEAR(year) ) ? 29 : monthDays[month]; // month==1 -> february
if (epoch >= monthLength) { epoch -= monthLength; } else { break; }
}

*pmonth = month; // jan is month 0
*pday = epoch+1; // day of month
}

String zero(int a){ if(a>=10) {return (String)a+"";} else { return “0”+(String)a;} }

String diaSemana(byte dia){
String str[] = {“Domingo”, “Segunda-feira”, “Terça-feira”, “Quarta-feira”, “Quinta-feira”, “Sexta-feira”, “Sabado”};
return str[dia];
}

void webpage()
{

WiFiClient client = server.available();
if (!client) {
return;
}

Serial.println(“new client”);
while(!client.available()){
delay(1);
}

// Read the first line of the request
esid = “”;
String request = client.readStringUntil(’\r’);
Serial.println(request);
client.flush();

// Match the request

int value = LOW;
if (request.indexOf("/LED=ON") != -1) {
digitalWrite(2, HIGH);
value = HIGH;
}
if (request.indexOf("/LED=OFF") != -1){
digitalWrite(2, LOW);
value = LOW;
}
if (request.indexOf ("/: ")!=-1){
for (int i = 0; i < request.length(); ++i)
{
EEPROM.write(i, request[i]);

          }

}
for (int i = 0; i < request.length(); ++i)
{
esid += char(EEPROM.read(i));
}
Serial.println(esid.length());
Serial.println(“SSID”);
Serial.println(esid);

}

char timeServer[] = “a.st1.ntp.br”;
const int timeZone = -2;

WiFiUDP Udp;
unsigned int localPort = 8888;
const int NTP_PACKET_SIZE = 48;
byte packetBuffer[NTP_PACKET_SIZE];

void setup()
{
pinMode (2, OUTPUT);
digitalWrite (2, 0);
Serial.begin(115200);
EEPROM.begin(512);
delay(10);

Serial.println();
Serial.println();

// We start by connecting to a WiFi network
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, pass);
IPAddress subnet (255, 255, 255, 0);
WiFi.config (IPAddress(192, 168, 0, 110),
IPAddress(192 ,168, 0, 1), subnet);

while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}

Serial.println("");

Serial.println(“WiFi connected”);

Serial.println(“Starting UDP”);
Udp.begin(localPort);
Serial.print("Local port: ");
Serial.println(Udp.localPort());

delay (1000);

// Port defaults to 8266
// ArduinoOTA.setPort(8266);

// Hostname defaults to esp8266-[ChipID]
// ArduinoOTA.setHostname(“myesp8266”);

// No authentication by default
// ArduinoOTA.setPassword((const char *)“123”);

ArduinoOTA.onStart( {
Serial.println(“Start”);
});
ArduinoOTA.onEnd( {
Serial.println("\nEnd");
});
ArduinoOTA.onProgress([](unsigned int progress, unsigned int total) {
Serial.printf(“Progress: %u%%\r”, (progress / (total / 100)));
});
ArduinoOTA.onError([](ota_error_t error) {
Serial.printf("Error[%u]: ", error);
if (error == OTA_AUTH_ERROR) Serial.println(“Auth Failed”);
else if (error == OTA_BEGIN_ERROR) Serial.println(“Begin Failed”);
else if (error == OTA_CONNECT_ERROR) Serial.println(“Connect Failed”);
else if (error == OTA_RECEIVE_ERROR) Serial.println(“Receive Failed”);
else if (error == OTA_END_ERROR) Serial.println(“End Failed”);
});
ArduinoOTA.begin();
Serial.println(“Ready”);
server.begin();
Serial.println(“Server started”);
Serial.print("IP address: ");
Serial.println(WiFi.localIP());

}
void loop()
{
ArduinoOTA.handle();

sendNTPpacket(timeServer); // send an NTP packet to a time server

// wait to see if a reply is available

if ( Udp.parsePacket() ) {
// We’ve received a packet, read the data from it
Udp.read(packetBuffer, NTP_PACKET_SIZE); // read the packet into the buffer

//the timestamp starts at byte 40 of the received packet and is four bytes,
// or two words, long. First, esxtract the two words:

unsigned long highWord = word(packetBuffer[40], packetBuffer[41]);
unsigned long lowWord = word(packetBuffer[42], packetBuffer[43]);
// combine the four bytes (two words) into a long integer
// this is NTP time (seconds since Jan 1 1900):
unsigned long secsSince1900 = highWord << 16 | lowWord;
Serial.print("Seconds since Jan 1 1900 = " );
Serial.println(secsSince1900);

// now convert NTP time into everyday time:
Serial.print("Unix time = ");
// Unix time starts on Jan 1 1970. In seconds, that's 2208988800:
const unsigned long seventyYears = 2208988800UL;
// subtract seventy years:
unsigned long epoch = secsSince1900 - seventyYears + timeZone * SECS_PER_HOUR;
// print Unix time:
Serial.println(epoch);  



 byte ano, mes, dia, dia_semana, hora, minuto, segundo;            
localTime(&epoch, &segundo, &minuto, &hora, &dia, &dia_semana, &mes, &ano); //extrai data e hora do unix time
 
String s ="GET /: " + diaSemana(dia_semana) + ", " + zero(dia) + "/" + zero(mes+1) + "/" + (ano+1900) + " " + zero(hora) + ":" + zero(minuto) + ":" + zero(segundo) + " HTTP/1.1";
 
Serial.println(s);
Serial.println(" ");

 if (esid == s) digitalWrite(2, HIGH);

}
// wait ten seconds before asking for the time again
delay(875);
}

// send an NTP request to the time server at the given address
unsigned long sendNTPpacket(char* address)
{
// set all bytes in the buffer to 0
memset(packetBuffer, 0, NTP_PACKET_SIZE);
// Initialize values needed to form NTP request
// (see URL above for details on the packets)
packetBuffer[0] = 0b11100011; // LI, Version, Mode
packetBuffer[1] = 0; // Stratum, or type of clock
packetBuffer[2] = 6; // Polling Interval
packetBuffer[3] = 0xEC; // Peer Clock Precision
// 8 bytes of zero for Root Delay & Root Dispersion
packetBuffer[12] = 49;
packetBuffer[13] = 0x4E;
packetBuffer[14] = 49;
packetBuffer[15] = 52;

// all NTP fields have been given values, now
// you can send a packet requesting a timestamp:
Udp.beginPacket(address, 123); //NTP requests are to port 123
Udp.write(packetBuffer, NTP_PACKET_SIZE);
Udp.endPacket();

webpage();
}[/code]

O que o código está imprimindo são informações do startup do programa, que aparentemente se conecta ao servidor de Hora Legal Brasileira (NTP.br) e liga ou desliga um LED de acordo com isso (não sei, não li todo o código).

O que é gravado e lido na EEPROM é um log de cada request feito, não há, em nenhum local deste código, a leitura da EEPROM sendo impressa na saída Serial.

Então, eu tentei fazer a leitura mas imprime GET /: ola HTTP/1.1TP/1.12:05:477 sempre, independente do que eu gravar na EEPROM, por isso retirei o código de leitura do void setup ( ) pois todos que tentei resultam nisso. Pelo método convencional de leitura ele le memoria por memoria e eu preciso que ele leia tudo (no caso a frase gravada) e imprima assim que eu ligar o ESP.

Ele salva o request e ja faz a leitura em seguida, imprimindo no serial. Mas isso é quando eu recebo informação do cliente, por isso necessito que a ultima informação mandada pelo cliente e salva seja imprimida ao ligar o ESP. O projeto final tem como base comparar a informação salva na EEPROM com a hora gerada pelo servidor NTP para acionar uma carga por horario.

Foi você quem escreveu esse código? Esse SSID e essa senha são do seu Wi-Fi? É estranho porque essa não devia ser a primeira informação a ser enviada para a saída e sim: “new client”, já que ao fim da função sendNTPPacket, o código executa a função webpage.

Aparentemente, essas linhas lêem a EEPROM caractere por caractere:

  for (int i = 0; i < request.length(); ++i)
    {
      esid += char(EEPROM.read(i));
    }
    Serial.println(esid.length());

Mas envia para a saída Serial a largura do request, talvez se você adicionar a linha:

Serial.print(esid)

Você veja o conteúdo completo, ficando assim:

  for (int i = 0; i < request.length(); ++i)
    {
      esid += char(EEPROM.read(i));
    }
  Serial.println(esid.length());
  Serial.print(esid);

Eu que estou fazendo ele, mas tem partes copiadas e modificadas de acordo com a minha ideia. So falta isso pra terminar meu projeto. Só preciso imprimir ao iniciar o esp o que esta salvo na memoria. Esse codigo que colocou nao funciona, ja tentei. Ao iniciar o esp ele aguarda o request do client, então se nao chegar nada do cliente ele vai imprimir nada, pois não chegou informação do client, ai esse e o problema não quero esperar o request do cliente sendo que ja tem o request do cliente salvo na memoria, so preciso apenas ler ele ao iniciar.

WiFiClient client = server.available();
  if (!client) {
    return;
  }
  Serial.println("new client");
  while(!client.available()){
    delay(1);
  }

Este código, quando executado ele imprime na saída serial new client? Ou não imprime nada?

Imprimi sim, imprime new client e depois da continuidade ao código.

Pode me mostrar toda a saída impressa? Para facilitar aqui, tô tentando encontrar a falha…