sábado, 24 de junio de 2017

Tutorial #8 ESP8266 – SPIFFS + JSON

Todos los ESP8266 tienen un “disco rígido” interno, llamado SPIFFS (SPI Flash File System), en el cual podemos leer y grabar archivos desde el código de Arduino o de forma manual. Justamente en este tutorial de IOT (internet de las cosas) vamos a ver cómo acceder al SPIFFS parar leer y guardar datos en un archivo Json (JavaScript Object Notation).


Código Fuente:

// Example: storing JSON configuration file in flash file system
//
// Uses ArduinoJson library by Benoit Blanchon.
// https://github.com/bblanchon/ArduinoJson
//
// Created Aug 10, 2015 by Ivan Grokhotkov.
//
// This example code is in the public domain.

#include <ArduinoJson.h>
#include "FS.h"

bool loadConfig() {
  File configFile = SPIFFS.open("/config.json", "r");
  if (!configFile) {
    Serial.println("Failed to open config file");
    return false;
  }

  size_t size = configFile.size();
  if (size > 1024) {
    Serial.println("Config file size is too large");
    return false;
  }

  // Allocate a buffer to store contents of the file.
  std::unique_ptr<char[]> buf(new char[size]);

  // We don't use String here because ArduinoJson library requires the input
  // buffer to be mutable. If you don't use ArduinoJson, you may as well
  // use configFile.readString instead.
  configFile.readBytes(buf.get(), size);

  StaticJsonBuffer<200> jsonBuffer;
  JsonObject& json = jsonBuffer.parseObject(buf.get());

  if (!json.success()) {
    Serial.println("Failed to parse config file");
    return false;
  }

  const char* serverName = json["serverName"];
  const char* accessToken = json["accessToken"];

  // Real world application would store these values in some variables for
  // later use.

  Serial.print("Loaded serverName: ");
  Serial.println(serverName);
  Serial.print("Loaded accessToken: ");
  Serial.println(accessToken);
  return true;
}

bool saveConfig() {
  StaticJsonBuffer<200> jsonBuffer;
  JsonObject& json = jsonBuffer.createObject();
  json["serverName"] = "api.example.com";
  json["accessToken"] = "128du9as8du12eoue8da98h123ueh9h98";

  File configFile = SPIFFS.open("/config.json", "w");
  if (!configFile) {
    Serial.println("Failed to open config file for writing");
    return false;
  }

  json.printTo(configFile);
  return true;
}

void setup() {
  Serial.begin(115200);
  Serial.println("");
  delay(1000);
  Serial.println("Mounting FS...");

  if (!SPIFFS.begin()) {
    Serial.println("Failed to mount file system");
    return;
  }

  //if (!saveConfig()) {
  //  Serial.println("Failed to save config");
  //} else {
  //  Serial.println("Config saved");
  //}

  if (!loadConfig()) {
    Serial.println("Failed to load config");
  } else {
    Serial.println("Config loaded");
  }
}

void loop() {
}


https://github.com/esp8266/arduino-esp8266fs-plugin

http://esp8266.github.io/Arduino/versions/2.0.0/doc/filesystem.html

1 comentario:

  1. Hola Tengo un ESP8266 NodemCu - cuando le subo el archivo json + sketch lo hace perfectamente, pero en el Serial Monitor me aparece la siguiente leyenda " ets Jan 8 2013,rst cause:2, boot mode:(3,7) ets_main.c " sin embargo la placa no esta conectada a ningún circuito externo y me pasa solamente cuando le cargo archivo json, me paso con el ejemplo del video y con otros programas que utilizan json, Por ejemplo al cargar un programa sin json funciona perfecto, Otro dato es que el Serial Monitor solo muestra la leyenda cuando lo seteo en 74880 baudio ("ets Jan 8 2013,rst cause:2, boot mode:(3,7)

    "), si lo dejo en 115200 no se lee nada ("lld$$??...." ). Gracias nuevamente. Si se te ocurre algo te lo super agradezco. Mi idea es cargar el api de thingspeak en el modo AP? Si me pueden ayudar. agradezco mucho, saludos?

    ResponderEliminar