0

i am trying to save IP address and password in NODE MCU EEPROM. Here is the code snippet. The problem is the first time i am reading, i am getting garbage values because there were no values set earlier, so how do i determine if there were values set earlier so that i can place default values.

#include <Arduino.h>
#include <EEPROM.h>
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>

const char* ssid_default = "NodeMCU";
const char* pass_default = "1234";

uint addr = 0;
ESP8266WebServer server(80);

struct
{
  int was_set = 9090; // already Set = 9090, other numbers  =  not set
  char ssid_default[40] = "NODEMCU";
  char pass_default[40] = "1234";
  int step = 0;
  /* data */
}creds;


void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  EEPROM.begin(512);

  delay(5000);
  EEPROM.get(addr, creds);
  Serial.print("Default SSID: ");
  Serial.println(String(creds.ssid_default));

  Serial.print("Default Pass:");
  Serial.println(String(creds.pass_default));

  Serial.print("Times Executed: ");
  Serial.println(String(creds.step));


  creds.step = creds.step + 1;

  EEPROM.put(addr, creds);
  Serial.println("Times Executed Incremented, Re-plug Devise to see changes");

  EEPROM.commit();
}

void loop() {
  delay(1000);
  // put your main code here, to run repeatedly:
}

1 Answers1

0

You already have a magic element in your struct that you could check for its special value after reading the EEPROM.

/*...*/
EEPROM.get(addr, creds);
if (creds.was_set != 9090) {
    /* set default values */
}
/*...*/

Most application implement a checksum to not only check for unset data, but also for changed data. The algorithm depends on your needs, but don't invent something new, use well-known ones like CRC.


Edit:

Depending on the size of your magic number or checksum, there will always be a small probability that a random set of bits will be recognized as correct/initialized. With a 32-bit value this probability can never be smaller than 2^(-32), which is about 1 in 4 billions.

A checksum has the advantage over a magic value that all values are taken into account.

There is no such thing like 100% safety.

the busybee
  • 10,755
  • 3
  • 13
  • 30
  • Yes, but the problem is, the first time initialization sets a random number, and there is a chance that the randomly intialized number is same as the number inside magic element. How can i make it fail safe? May be CRC is the answer as you mentioned. Ill take a look – Piyush jain Jun 22 '20 at 08:23