how can my ESP32 be programmed with a .bin file on its SPIFFS

406 Views Asked by At

I have an idea to download the .bin file from a server and save in the SPIFFS and upload the file on my ESP32.
My problem has two parts as I am not much experienced in working with ESP32. First, how to store the .bin file I've downloaded in the SPIFFS and second, how to get the ESP32 programmed with the .bin downloaded file with no user interference and all automatically by code.
The second part is more challenging that I couldn't find any solution for it.

I looked for a solution specially for the second part I stated, but found no solution.

1

There are 1 best solutions below

0
abdullah-1307 On

Please follow this code snippet, i hope this will help you in resolving the issue:

#include <Arduino.h>
#include <WiFi.h>
#include <HTTPClient.h>
#include <SPIFFS.h>
#include <Update.h>

const char* ssid = "YourWiFiSSID";
const char* password = "YourWiFiPassword";
const char* binUrl = "http://example.com/path/to/your/file.bin"; // URL of the .bin file

void setup() {
  Serial.begin(115200);
  
  // Connect to Wi-Fi
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.println("Connecting to WiFi...");
  }
  Serial.println("Connected to WiFi");
  
  // Initialize SPIFFS
  if (!SPIFFS.begin(true)) {
    Serial.println("SPIFFS Mount Failed");
    return;
  }
  
  // Check for and perform firmware update
  checkAndPerformFirmwareUpdate();
  
  // Your setup code here
}

void loop() {
  // Your main loop code here
}

void checkAndPerformFirmwareUpdate() {
  HTTPClient http;
  http.begin(binUrl);

  int httpCode = http.GET();
  if (httpCode == HTTP_CODE_OK) {
    Serial.println("Downloading .bin file...");
    File firmwareFile = SPIFFS.open("/firmware.bin", FILE_WRITE);
    if (firmwareFile) {
      size_t contentLength = http.getSize();
      http.writeToStream(&firmwareFile);
      firmwareFile.close();
      Serial.println("Download complete.");

      // Perform firmware update
      if (Update.begin(contentLength)) {
        if (Update.writeStream(http.getStream())) {
          if (Update.end(true)) {
            Serial.println("Firmware update successful. Rebooting...");
            ESP.restart();
          } else {
            Serial.println("Firmware update failed!");
          }
        } else {
          Serial.println("Write to firmware update stream failed!");
        }
      } else {
        Serial.println("Begin firmware update failed!");
      }
    } else {
      Serial.println("Unable to create firmware file!");
    }
  } else {
    Serial.println("HTTP GET failed!");
  }
  http.end();
}