How to Persist Data in Esp8266 Using Preferences. H

After many hours (days!) I noticed that almost only examples coming with the Preferences.h library are used, but nothing of those actually matches my needs. As I am a complete C NOOB I'm stuck in types, casting and everything horrific that comes with it :-(

So: I am writing code for a battery-driven ESP8266 that reads a sensor and publishes it on an MQTT bus. I want to get rid of hard-coded credentials. The WiFiManager.h library by default supports changing WiFi credentials using a 'ConfigPortal' webinterface. There, I want to add custom fields for MQTT that can be changed and saved to persistant memory as well.

This is the global idea:

#include <Preferences.h>

// Declare vars 
char mqtt_server[40];
char mqtt_port[6];
char mqtt_user[20];
char mqtt_pass[20];

// Read data from persistant memory or else return default
mqtt_server = preferences.getChar("mqtt_server", "default mqtt server");
mqtt_port = preferences.getChar("mqtt_port", "default mqtt port");
mqtt_user = preferences.getChar("mqtt_user", "default mqtt user");
mqtt_pass = preferences.getChar("mqtt_pass", "default mqtt pass");

// Connect to mqtt broker using the vars as just defined

// Pushing a button starts a ConfigPortal webinterface to change these vars
// Write new data to persistant memory
// get the new data from the webform (called "Mqtt_server.
preferences.begin("mqtt_config", false);
preferences.putChar("mqtt_server", new_mqtt_server);
preferences.putChar("mqtt_port", new_mqtt_port);
preferences.putChar("mqtt_user", new_mqtt_user);
preferences.putChar("mqtt_pass", new_mqtt_pass);
preferences.end();

Consider this as pseudo-code which shows what I want to achieve.

I have questions like:

  • How can I get data into the 'mqtt_server'? ( currently only get the first character)
  • Why does getChar only allow an integer as default return value where I expect a default text to be possible? (the example shows the default text but accepts only eg. '0'.

Currently I am lost so this is my last resort... Thank you in advance for thinking along!

7
Sophia Al-Mansoor

Sophia Al-Mansoor

Global Business & E-Commerce Reporter

Sophia analyzes international trade, startup ecosystems, retail transformation, and supply chain logistics for modern digital publications.

Share this article