/*
save an unsigned integer in Preferences instead of a String/string
de: uint statt string speichern und ausgeben.
based on https://forum.arduino.cc/t/preferences-string-array-lesen-und-speichern/1444522/8 by Kai-R
2026-05-17 by noiasca https://forum.arduino.cc/t/preferences-string-array-lesen-und-speichern/1444522/11
Code in forum
to be deleted here 2026-11
*/
#include <Preferences.h>
#include <iostream>
#include "button.h" // simplified class to debounce a button (see separate tab)
Preferences prefs;
constexpr unsigned maxBufferLen {10};
char buffer[maxBufferLen];
Button btnIncreaseVolume(18);
uint16_t volume; // @todo tbd if needed as global, value is anyway in the preferences.
// sends the volume to the destination
void volumeSend() {
std::cout << std::endl; // debug only (otherwise you don't see the last line here in the demo imidiately)
sprintf(buffer, "VOL:%02d;", volume);
std::cout << buffer; // output to destination - this MVP just uses the Serial
std::cout << std::endl; // debug only (otherwise you don't see the last line here in the demo imidiately)
}
// increase volume, persist to preferences and send to destination
void volumeIncrease() {
std::cout << std::endl << "vol inc" << std::endl; // debug only
volume++;
if (volume > 99) volume = 99;
prefs.putUInt("volume", volume);
volumeSend();
}
// timer to check if volume needs to be sent to destination
void volumeTimer(uint32_t currentMillis = millis()) {
static uint32_t previousMillis = 0;
if (currentMillis - previousMillis > 5 * 1000UL) {
previousMillis = currentMillis;
volumeSend();
}
}
void setup() {
Serial.begin(115200);
prefs.begin("Prefs", false);
btnIncreaseVolume.begin();
// Wenn Key noch nicht vorhanden ist, lege ihn an
if (!prefs.isKey("volume")) {
std::cout << "Create key volume" << std::endl;
prefs.putUInt("volume", 0);
}
// Lese Daten aus Preferences
prefs.getUInt("volume", volume);
std::cout << "Current volume as number: " << volume << std::endl;
}
void loop() {
if (btnIncreaseVolume.wasPressed()) volumeIncrease();
volumeTimer();
}
//