Sauvegarder la dernière radio écoutée avant coupure alimentation

Bonjour à tous et meilleurs vœux pour 2022,

J'ai réalisé une webradio sur la base de ce qu'a fait Michele sur ce site :GitHub - michelep/ESP32_WebRadio: An Internet web radio based to ESP32

J'ai modifié le sketch pour utiliser un module I2C, un écran 1.8 " et deux encodeurs rotatifs.

Maintenant j'aimerais pouvoir, lorsque je coupe l'alimentation de la radio, mémoriser la station que je suis en train d'écouter.

Le programme est conçu pour qu'à la mise sous tension, il aille lire un fichier config.json , sous SPIFFS, qui contient le numéro de la station par défaut.
Voici le contenu du fichier config.json :
{"wifi_essid":"Livebox-Bxxx","wifi_password":"xxxxxxxxx","hostname":"esp32-webradio","ntp-server":"time.ien.it","timezone":"1","stream_id":"0","volume":3,"contrast":60}

Existe t'il une solution pour écrire dans ce fichier un numéro de stream_id avant que l'alimentation ne se coupe complétement, à la manière du tuto de Riton-duino qui utilise un condensateur pour écrire des données en EEPROM.

Merci pour votre aide si vous pouvez...

Bien entendu, le principe sera le même : une diode + condensateur réservoir + interruption sur front descendant.
Sauf que le réservoir devra être beaucoup plus gros, car un ESP32 consomme plus qu'un petit ARDUINO.
Ensuite il faut écrire dans un fichier SPIFFS au lieu d'écrire en EEPROM, pas sorcier.
Le seul point à déterminer est le temps nécessaire pour écrire le fichier.
Tout est expliqué sur mon blog.

Bonsoir

il me semble que dans le code, plus précisément dans la fonction NextStream appelée à chaque changement de stationpar appui un bouton poussoir il est possible de récupérer la nouvelle valeur de config.stream_id pour la mémoriser dans le fichier json chargé à la mise sous tension, elle prend la palce de la valeur 0

{"wifi_essid":"Livebox-Bxxx","wifi_password":"xxxxxxxxx","hostname":"esp32-webradio","ntp-server":"time.ien.it","timezone":"1","stream_id":"0","volume":3,"contrast":60}

Il suffit peut être d'appeler la fonction saveConfigFile() en entrant dans la fonction NextStream() pour mettre à jour toute la configuration , N° de webradio inclus ?

Bonsoir Al1fch, bonsoir Henri,

La fonction nextStream ne mets pas à jour le fichier config.json dans l'état actuel du sketch.
J'avais pensé le faire mais est ce que réécrire dans la mémoire SPIFFs à chaque fois que l'on change de station ne va pas la détruire à terme (peut-être est-ce au bout de nombreuses écritures!)?

J'étais en train de lire le tuto de Henri et j'avoue qu'il va me falloir du temps si je veux le mettre en oeuvre. A ce sujet, j'utilise déjà les interruptions pour les rotary encoder, avec : <ESP32Encoder.h>. Pas sur que je puisse en utiliser une autre?
Ci dessous mon sketch qui demande encore à être optimisé et quelque peu mis en ordre mais qui fonctionne en l'état. Je n'ai pas modifié le fichier config.ino ni le webserver.ino

//
// ESP32 WebRadio
//
// Released under GNU General Public License v3.0
//
// Compile with DOIT ESP32 WebKit v1 and burn /data directory into SPIFFS (1M)

//https://github.com/michelep/ESP32_WebRadio
//
//
//  Display 160x128
//  +-------------------------------------------+ _yHeader=0
//  | Header                                    |       _hHeader=20px
//  +-------------------------------------------+ _yName=20
//  |                                           |
//  |              StationName                  |       _hName=35px
//  |                                           |
//  +-------------------------------------------+ _yTitle=55
//  |                                           |
//  |              StreamTitle                  |       _hTitle=63px
//  |                                           |
//  +-------------------------------------------+ _yFooter=116
//  | Footer                                    |       _hFooter=12px
//  +-------------------------------------------+ 128
//                                             160
// system libraries
#include <WiFi.h>
#include <ESPmDNS.h>
#include <WiFiClient.h>
#include <WiFiUdp.h>
#include <ESPmDNS.h>
#include <ArduinoOTA.h>
#include "time.h"
#include <SPI.h>
#include <Adafruit_GFX.h>
#include <Adafruit_ST7735.h>
#include <Fonts/Org_01.h>
#include "Audio.h"
#include <ESP32Encoder.h>
#include <AsyncTCP.h>
#include <ESPAsyncWebServer.h>
#include <ArduinoJson.h>
#include <FS.h>
#include "SPIFFS.h"
#include "soc/soc.h" //disable brownour problems
#include "soc/rtc_cntl_reg.h" //disable brownour problems

// Digital I/O used
#define I2S_DOUT      26
#define I2S_BCLK      27
#define I2S_LRC       25
#define TFT_DC         2
#define TFT_RST        4 // Or set to -1 and connect to Arduino RESET pin  
#define TFT_CS        15

ESP32Encoder encoder;
ESP32Encoder encoder2;
Audio audio;

//global variables
int32_t countVol = encoder.getCount();
int32_t oldCountVol;
int32_t countStreams = encoder2.getCount();
int32_t oldCountStreams;
String streamTitle;
String oldStreamTitle;
boolean  f_1sec = false;        // flag is set every second
boolean  f_1min = false;        // flag is set every minute
boolean  f_has_ST = false;      // has StreamTitle?
String   _station = "", _stationname = "";
String   _title = "";
uint8_t  _commercial_dur = 0;   // duration of advertising
static int last; // millis counter
bool streamIsValid = false;
bool streamChanged = true;
bool streamIsPaused = false;
bool streamIsPlaying = false;
bool deviceIsOTA = false;

// display layout
const uint16_t _width = 160;                    // Display Width
const uint16_t _height = 128;                   // Display Height
const uint16_t _yHeader = 0;                    // yPos Header
const uint16_t _hHeader = 20;                   // height Header
const uint16_t _yName  = _yHeader + _hHeader;   // yPos StationName
const uint16_t _hName  = 35;                    // height Stationname
const uint16_t _yTitle = _yName + _hName;       // yPos StreamTitle
const uint16_t _hTitle = 63;                    // height StreamTitle
const uint16_t _yFooter = _yTitle + _hTitle;    // yPos Footer
const uint16_t _hFooter = 10;                    // height Footer
const uint16_t _yVolBar = _yFooter;             // yPos VolumeBar
const uint16_t _hVolBar = 5;                    // height VolumeBar
const uint16_t _wLogo = 96;                     // width Logo
const uint16_t _hLogo = 96;                     // height Logo

// Color definitions for the TFT screen
// TFT has bits 6 bits (0..5) for RED, 6 bits (6..11) for GREEN and 4 bits (12..15) for BLUE.
#define BLACK   ST7735_BLACK
#define BLUE    ST7735_BLUE
#define RED     ST7735_RED
#define GREEN   ST7735_GREEN
#define CYAN    GREEN | BLUE
#define MAGENTA RED | BLUE
#define YELLOW  RED | GREEN
#define WHITE   RED | BLUE | GREEN

//objects
Adafruit_ST7735 tft = Adafruit_ST7735(TFT_CS,  TFT_DC, TFT_RST);
AsyncWebServer server(80);

#define MAX_VOLUME 21
#define MIN_VOLUME 0

#define __DEBUG__

// Firmware data
const char BUILD[] = __DATE__ " " __TIME__;
#define FW_NAME         "esp32-webradio"
#define FW_VERSION      "0.0.6"


// Icons
#define audio_icon_width 5
#define audio_icon_height 10
static const uint8_t PROGMEM audio_icon_bits[] = {
  0x10, 0x18, 0x1c, 0x1f, 0x1f, 0x1f, 0x1f, 0x1c, 0x18, 0x10
};

#define wifi_icon_width 8
#define wifi_icon_height 8
static const uint8_t PROGMEM wifi_icon_bits[] = {
  0x00, 0x1f, 0x20, 0x4e, 0x50, 0x56, 0x56, 0x40
};

// Format SPIFFS if mount failed
#define FORMAT_SPIFFS_IF_FAILED 1

// Config
struct Config {
  // WiFi config
  char wifi_essid[24];
  //  char wifi_password[16];
  char wifi_password[24];
  // NTP Config
  char ntp_server[16];
  int8_t ntp_timezone;
  // Host config
  char hostname[16];
  bool ota_enable;
  char ota_password[8];
  // Radio podcast
  int8_t stream_id;
  int8_t stream_count;
  char stream_url[64];
  int8_t volume;
  // Display config
  int8_t contrast;
};

#define CONFIG_FILE "/config.json"
File configFile;
Config config; // Global config object

// JSON file contains an array of streams URL
#define DB_FILE "/streams.json"

DynamicJsonDocument env(256);

//   Esternal procedures definition
bool loadConfigFile();
void initWebServer();
void printStreamsDB();
bool getStreamURL(uint8_t);

// ************************************
// DEBUG_PRINT() and DEBUG_PRINTLN()
//
// send message to Serial
// ************************************
void DEBUG_PRINT(String message) {
#ifdef __DEBUG__
  Serial.print(message);
#endif
}

void DEBUG_PRINTLN(String message) {
#ifdef __DEBUG__
  Serial.println(message);
#endif
}
//**************************************************************************************************
//                                        T I M E R                                                *
//**************************************************************************************************
void timer1sec() {
  static volatile uint8_t sec = 0;
  f_1sec = true;
  sec++;
  //log_i("sec=%i", sec);
  if (sec == 60) {
    sec = 0;
    f_1min = true;
  }
}
//**************************************************************************************************
//                                       D I S P L A Y                                             *
//**************************************************************************************************
inline void clearHeader() {
  tft.fillRect(0, _yHeader, _width, _hHeader, BLACK); // y   0...19
}
inline void clearStation() {
  tft.fillRect(0, _yName,   _width, _hName,   BLACK); // y  20...119
}
inline void clearTitle()  {
  tft.fillRect(0, _yTitle,  _width, _hTitle,  BLACK); // y 120...219
}
inline void clearFooter() {
  tft.fillRect(0, _yFooter, _width, _hFooter, BLACK); // y 220...239
}
inline void clearDisplay() {
  tft.fillScreen(BLACK); // y   0...239
}
inline uint16_t txtlen(String str) {
  uint16_t len = 0;
  for (int i = 0; i < str.length(); i++) if (str[i] <= 0xC2) len++;
  return len;
}

void display_info(const char *str, int ypos, int height, uint16_t color, uint16_t indent) {
  tft.fillRect(0, ypos, tft.width(), height, BLACK);  // Clear the space for new info
  tft.setTextColor(color);                                // Set the requested color
  tft.setCursor(indent, ypos);                            // Prepare to show the info
  tft.print(str);                                         // Show the string
}
void showStation(String ST) {
  tft.drawLine(0, _yName, 160, _yName, YELLOW);
  _station =  (ST.c_str());
  _station = _station.substring(0,25);
  //display_info("Station :", _yName, _hName, YELLOW, 0);
  //display_info(ST.c_str(), _yName + 15, _hName, CYAN, 0);
  display_info(_station.c_str(), _yName + 12, _hName, CYAN, 0);
}
void showStreamTitle(String ST) {
  ST.trim();  // remove all leading or trailing whitespaces
  ST.replace(" | ", "\n");   // some stations use pipe as \n or
  ST.replace("| ", "\n");    // or
  ST.replace("|", "\n");
  //    if(txtlen(ST) > 4) f_has_ST=true; else f_has_ST=false;
  String fullStreamTitle = (ST.c_str());
  int index = fullStreamTitle.indexOf('-');
  String singer = fullStreamTitle.substring(0, index - 1);
  singer = singer.substring(0,24);
  String titre = fullStreamTitle.substring(index + 2);

  //display_info("Singer and Title :", _yTitle, _hTitle, YELLOW, 0);
  tft.drawLine(0, _yTitle, 160, _yTitle, YELLOW);
  display_info(singer.c_str(), _yTitle + 10, _hTitle, GREEN, 0);
  display_info(titre.c_str(), _yTitle + 25, _hTitle, CYAN, 0);
  //  display_info(ST.c_str(), _yTitle + 15, _hTitle, CYAN, 0);
  showVolumeBar();
}
inline void updateTime() {
  clearHeader();
  tft.setCursor(2, 6);
  tft.print("FM");
  tft.setCursor(125, 6);
  struct tm timeinfo;
  if (!getLocalTime(&timeinfo)) {
    DEBUG_PRINTLN("[TIME] Failed to obtain time");
  } else {
    tft.println(&timeinfo, "%H:%M");
  }
}
inline void showVolumeBar() {
  clearFooter();
  tft.drawLine(0, _yVolBar-3, 160, _yVolBar-3, YELLOW);
  tft.drawXBitmap(2, _yVolBar, audio_icon_bits, audio_icon_width, audio_icon_height, 0xff);
  uint8_t volume = map(config.volume, 0, 22, 0, 72);
  tft.drawRect(10, _yVolBar, 72, 10, RED);
  tft.fillRect(10, _yVolBar, volume, 10, RED);
}
//#define DISPLAY_BL 27
//#define DISPLAY_BL_DEFAULT 100 // Backlight LEDs PWM duty-cycle

// ************************************
// connectToWifi()
//
// connect to configured WiFi network
// ************************************
bool connectToWifi() {
  uint8_t timeout = 0;

  if (strlen(config.wifi_essid) > 0) {
    DEBUG_PRINT("[INIT] Connecting to " + String(config.wifi_essid) + "...");

    WiFi.begin(config.wifi_essid, config.wifi_password);

    while ((WiFi.status() != WL_CONNECTED) && (timeout < 10)) {
      delay(250);
      timeout++;
    }
    if (WiFi.status() == WL_CONNECTED) {
      DEBUG_PRINTLN("CONNECTED. IP:" + WiFi.localIP().toString() + " GW:" + WiFi.gatewayIP().toString());

      env["ip"] = WiFi.localIP().toString();
      if (MDNS.begin(config.hostname)) {
        DEBUG_PRINTLN("[INIT] MDNS responder started: " + String(config.hostname));
        // Add service to MDNS-SD
        MDNS.addService("http", "tcp", 80);
      }

      configTime(config.ntp_timezone * 3600, config.ntp_timezone * 3600, config.ntp_server);

      return true;
    } else {
      DEBUG_PRINTLN("[ERROR] Failed to connect to WiFi");
      return false;
    }
  } else {
    DEBUG_PRINTLN("[ERROR] Please configure Wifi");
    return false;
  }
}

//
// high priority audioTask on CORE0
//
void audioTask(void *pvParameters) {
  while (1) {
    if (!streamIsPaused) {
      if (streamChanged) {
        playStream(config.stream_id);
        streamChanged = false;
      }
      audio.loop();
      streamIsPlaying = audio.isRunning();
    }
  }
}

//**************************************************************************************************
//                                       S E T U P                                             *
//**************************************************************************************************
void setup() {
  Serial.begin(115200);
  Serial.setDebugOutput(true);
  Serial.println();
  Serial.println();
  Serial.println();
  Serial.print("ESP32 SDK: ");
  Serial.println(ESP.getSdkVersion());
  Serial.println();
  Serial.print(FW_NAME);
  Serial.print(" ");
  Serial.print(FW_VERSION);
  Serial.print(" ");
  Serial.println(BUILD);
  delay(1000);

  ESP32Encoder::useInternalWeakPullResistors = UP;
  encoder.attachSingleEdge (35, 34);
  encoder2.attachSingleEdge (17, 16);
  encoder.setCount(2);
  encoder2.setCount(0);
  oldCountStreams = -1;

  // Initialize SPIFFS
  DEBUG_PRINT("[INIT] Initializing SPIFFS...");
  if (!SPIFFS.begin()) {
    DEBUG_PRINTLN("[ERROR] SPIFFS mount failed. Try formatting...");
    if (SPIFFS.format()) {
      DEBUG_PRINTLN("[INIT] SPIFFS initialized successfully");
    } else {
      DEBUG_PRINTLN("[FATAL] SPIFFS fatal error");
      ESP.restart();
    }
  } else {
    DEBUG_PRINTLN("OK");
  }

  // Load configuration
  loadConfigFile();

  // Initialize DISPLAY
  DEBUG_PRINT("[INIT] Initialize display...");

  tft.initR(INITR_BLACKTAB);      // Init ST7735S chip, black tab
  DEBUG_PRINT("[INIT] ST7735 initialised");
  //Serial.println("ST7735 initialised");
  tft.setRotation(1);
  clearHeader();
  updateTime();

  // Connect to WiFi network
  connectToWifi();

  // Initialize Web Server
  initWebServer();

  // Initialize OTA
  if (config.ota_enable) {
    DEBUG_PRINT("[INIT] Initialize OTA...");
    // ArduinoOTA.setPort(3232);
    //ArduinoOTA.setHostname(config.hostname);
    ArduinoOTA.setHostname("esp32 - webradio");

    ArduinoOTA
    .onStart([]() {
      String type;
      if (ArduinoOTA.getCommand() == U_FLASH)
        type = "sketch";
      else // U_SPIFFS
        type = "filesystem";
      Serial.println("Start updating " + type);
      deviceIsOTA = true;
      streamIsPaused = true;
    })
    .onEnd([]() {
      Serial.println("\nEnd");
      deviceIsOTA = false;
      streamIsPaused = false;
    })
    .onProgress([](unsigned int progress, unsigned int total) {
      Serial.printf("Progress: % u % % \r", (progress / (total / 100)));
      clearDisplay();
      tft.setCursor(2, 30);
      tft.printf("Progress: % u % % \r", (progress / (total / 100)));
    })
    .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");
      deviceIsOTA = false;
    });
    ArduinoOTA.begin();
    DEBUG_PRINTLN("OK");
  }

  //
  DEBUG_PRINT("[INIT] Initialize audio...");

  env["volume"] = config.volume;

  audio.setPinout(I2S_BCLK, I2S_LRC, I2S_DOUT);
  audio.setVolume(env["volume"].as<int>());
  DEBUG_PRINTLN("OK");

  //
  printStreamsDB();

  // let's fly!
  DEBUG_PRINTLN("[INIT] Ready: let's fly!");
  env["status"] = "Ready";

  // Launch audioTask on CORE0 with high priority
  disableCore0WDT(); // Disable watchdog on CORE0
  xTaskCreatePinnedToCore(
    audioTask,   /* Function to implement the task */
    "audioTask", /* Name of the task */
    10000,      /* Stack size in words */
    NULL,       /* Task input parameter */
    15,          /* Priority of the task */
    NULL,       /* Task handle. */
    0);  /* Core where the task should run */
}
//************************************* End SETUP ***************************************

String zeroPadding(int digit) {
  if (digit < 10) {
    return String("0" + String(digit));
  }
  return String(digit);
}

void updateDisplay() {
  // Graphic display of 128x160 pixels
  tft.fillScreen(ST7735_BLACK);
  tft.setTextSize(3);

  // If there's an OTA running...
  if (deviceIsOTA) {
    tft.setCursor(2, 16);
    tft.print("Updating.Please wait!");
    return;
  }

  tft.setTextSize(1);

  tft.setCursor(2, 6);
  tft.print("FM");
  tft.setCursor(125, 6);
  struct tm timeinfo;
  if (!getLocalTime(&timeinfo)) {
    DEBUG_PRINTLN("[TIME] Failed to obtain time");
  } else {
    tft.println(&timeinfo, "%H:%M");
  }

/*
    // Top red BAR with WiFi signal power
    tft.drawXBitmap(0, 0, wifi_icon_bits, wifi_icon_width, wifi_icon_height, 0xff);
    tft.fillRect(10, 0, 84, 8, RED);
    tft.setTextColor(WHITE, BLACK);
    tft.setCursor(100, 0);
    tft.println(String(WiFi.RSSI()) + "dB");
 */
  if (streamIsPlaying) {
    showVolumeBar();
  } else {
    tft.setCursor(4, 80);
    if (streamIsPaused) {
      tft.println("*** PAUSE ***");
    } else {
      tft.println("Loading...");
    }
  }
}

bool playStream(uint8_t stream_id) {
  if (getStreamURL(stream_id)) {
    streamIsPlaying = audio.connecttohost(config.stream_url);
    updateDisplay();
    return true;
  }
  DEBUG_PRINTLN("[AUDIO] No STREAM URL defined!");
  env["status"] = "No stream url defined!";
  return false;
}

//**************************************************************************************************
//                                            E V E N T S                                          *
//**************************************************************************************************

void audio_info(const char *info) {
  Serial.print("info        "); Serial.println(info);
}
void audio_showstation(const char *info) {
  _station = info;
  showStation(info);
}
void audio_showstreamtitle(const char *info) {
  _title = info;
  showStreamTitle(info);
}
void audio_commercial(const char *info) {              // called from I2S
  Serial.print("commercial  "); Serial.println(info);
  _commercial_dur = atoi(info) / 1000;                // info is the duration of advertising in ms
  _title = "Advertising " + (String) _commercial_dur + "s";
  showStreamTitle(_title);
}
//**************************************************************************************************
//                                            S T R E A M S   A C T I O N S                                         *
//**************************************************************************************************
void nextStream() {
  //config.stream_id++;
  config.stream_id = countStreams;
  if (config.stream_id >= config.stream_count) {
    config.stream_id = 0;
  }
  streamChanged = true;
}
void nextStreamWeb() {
  config.stream_id++;
  if (config.stream_id >= config.stream_count) {
    config.stream_id = 0;
  }
  updateDisplay();
  streamChanged = true;
}

void togglePlay() {
  streamIsPlaying = audio.pauseResume();
  DEBUG_PRINT("[AUDIO] pauseResume(): ");
  if (streamIsPlaying) {
    DEBUG_PRINTLN("PLAY");
    streamIsPaused = false;
    env["status"] = "Playing " + config.stream_id;
  } else {
    DEBUG_PRINTLN("PAUSE");
    streamIsPaused = true;
    env["status"] = "Pause";
  }
}
uint8_t tickCounter = 0;

//**************************************************************************************************
//                                            L O O P                                          *
//**************************************************************************************************
void loop() {
  if (config.ota_enable) {
    ArduinoOTA.handle();
  }

  if ((millis() - last) > 1100) {

    streamsControl();

    if (WiFi.status() != WL_CONNECTED) {
      // Not connected? RETRY!
      connectToWifi();
    }
    tickCounter++;
    if ((tickCounter % 10) == 0) {
      if (!streamIsPlaying) {
        playStream(config.stream_id);
      }
    }
    volumeControl();
    timer1sec();
    if (f_1min == true) {
      updateTime();
      f_1min = false;
    }
    last = millis();
  }
}
//******************************** FIN LOOP **************************************

void volumeControl() {
  countVol = (encoder.getCount());
  if (countVol < 1) {
    countVol = 1;
    encoder.setCount(countVol);
  }
  if (countVol > 21) {
    countVol = 21;
    encoder.setCount(countVol);
  }
  if (countVol != oldCountVol) {
    config.volume = countVol;
    oldCountVol = countVol;
    audio.setVolume(config.volume);
    env["volume"] = config.volume;
    showVolumeBar();
  }
}

void streamsControl() {
  countStreams = (encoder2.getCount());
  if (countStreams < 0) {
    countStreams = config.stream_count - 1;
    encoder2.setCount(countStreams);
  }
  if (countStreams >= config.stream_count) {
    countStreams = 0;
    encoder2.setCount(countStreams);
  }
  if (countStreams != oldCountStreams) {
    nextStream();
    oldCountStreams = countStreams;
    updateDisplay();
  }
}

L'ESP32 dispose de plus de broches avec interruption qu'un ARDUINO.

SPIFFS comporte un peu de 'wear levelling' = répartition d'usure, ll'usure est 'étalée' ('diluée') sur l'ensemble de la zone de mémoire Flash dédiée à SPIFFS et non concentrée sur un seul secteur de mémoire Flash... bien entedu ça ferait sans doute un peu plus d'écrirures en Flash que pour une sauvegarde unique à la coupure de l'alimentation mais avec une répartition d'usure , vu le peu d'info à écrire à chaque fois......

La fonction nextStream ne mets pas à jour le fichier config.json dans l'état actuel du sketch.

oui, je proposais de modifier cette fonction pour qu'elle le fasse en appelant la fonction externe saveConfigFile() qui, comme loadConfigFile() se trouve dans config.ino

Oui, 100K effacements de secteur en théorie, sans compter le wear levelling.
Tu as le temps de voir venir ...

Bonjour

Pour une solution hardware de détection de coupure d'alimentation et sauvegarde de la dernière station écoutée il faudrait dimensionner largement le 'condensateur réservoir'

Avec un récepteur Webradio basé sur un autre code , un ESP32 et un MAX98357A, montage dépourvu d'afficheur , je mesure un courant autour de 140mA. (WiFi fortement sollicité pour le maintien du flux)

Par ailleurs SPIIFS est réouté pur corrompre le système de ficheir en cas de coupure d'alim pendant l'écriture

D'où le nécessité de bien calculer la capacité du 'réservoir' !!

Bonjour,
Merci pour vos réponses à tous les deux.

Je vais m'attacher à coder la solution d'écriture dans la mémoire Spiffs à chaque changement de flux radio si celui-ci reste au moins une minute, ceci pour ne pas écrire les données quand on recherche une station.
Ensuite, si le résultat ne me parait pas satisfaisant, je m'orienterai sur la solution écriture si perte d'alimentation.
Cordialement.