Categories

ESP8266 SPIFFS example

In this example we will look at SPIFFS , SPIFFS, or spiffs (Serial Peripheral Interface Flash File System) is a method for creating a file system in NOR-type flash memory

File system object (SPIFFS)

begin

SPIFFS.begin()

This method mounts SPIFFS file system. It must be called before any other FS APIs are used. Returns true if file system was mounted successfully, false otherwise.

format

SPIFFS.format()

Formats the file system. May be called either before or after calling begin. Returns true if formatting was successful.

open

SPIFFS.open(path, mode)

Opens a file. path should be an absolute path starting with a slash (e.g. /dir/filename.txt). mode is a string specifying access mode. It can be one of “r”, “w”, “a”, “r+”, “w+”, “a+”. Meaning of these modes is the same as for fopen C function.

Returns File object. To check whether the file was opened successfully, use the boolean operator.

File f = SPIFFS.open("/f.txt", "w");
if (!f) {
    Serial.println("file open failed");
}

exists

SPIFFS.exists(path)

Returns true if a file with given path exists, false otherwise.

openDir

SPIFFS.openDir(path)

Opens a directory given its absolute path. Returns a Dir object.

remove

SPIFFS.remove(path)

Deletes the file given its absolute path. Returns true if file was deleted successfully.

rename

SPIFFS.rename(pathFrom, pathTo)

Renames file from pathFrom to pathTo. Paths must be absolute. Returns true if file was renamed successfully.

info

FSInfo fs_info;
SPIFFS.info(fs_info);

Fills FSInfo structure with information about the file system. Returns true is successful, false otherwise.

Filesystem information structure

 

struct FSInfo {
    size_t totalBytes;
    size_t usedBytes;
    size_t blockSize;
    size_t pageSize;
    size_t maxOpenFiles;
    size_t maxPathLength;
};

This is the structure which may be filled using FS::info method. Field names are self-explanatory.

Directory object (Dir)

 

The purpose of Dir object is to iterate over files inside a directory. It provides three methods: next()fileName(), and openFile(mode).

The following example shows how it should be used:

Dir dir = SPIFFS.openDir("/data");
while (dir.next()) {
    Serial.print(dir.fileName());
    File f = dir.openFile("r");
    Serial.println(f.size());
}

dir.next() returns true while there are files in the directory to iterate over. It must be called before calling fileName and openFile functions.

openFile method takes mode argument which has the same meaning as for SPIFFS.open function.

File object

 

SPIFFS.open and dir.openFile functions return a File object. This object supports all the functions of Stream, so you can use readBytesfindUntil,parseIntprintln, and all other Stream methods.

There are also some functions which are specific to File object.

seek

file.seek(offset, mode)

This function behaves like fseek C function. Depending on the value of mode, it moves current position in a file as follows:

  • if mode is SeekSet, position is set to offset bytes from the beginning.
  • if mode is SeekCur, current position is moved by offset bytes.
  • if mode is SeekEnd, position is set to offset bytes from the end of the file.

Returns true if position was set successfully.

position

file.position()

Returns the current position inside the file, in bytes.

size

file.size()

Returns file size, in bytes.

name

String name = file.name();

Returns file name, as const char*. Convert it to String for storage.

close

file.close()

Close the file. No other operations should be performed on File object after closefunction was called.

 

Code Example

#include "FS.h"
 
void setup() 
{
  Serial.begin(9600);
 
  // always use this to "mount" the filesystem
  bool result = SPIFFS.begin();
  Serial.println("SPIFFS opened: " + result);
 
  // this opens the file "myfile.txt" in read-mode
  File testFile = SPIFFS.open("/myfile.txt", "r");
 
  if (!testFile) 
  {
    Serial.println("File doesn't exist yet. Creating it");
 
    // open the file in write mode
    File testFile = SPIFFS.open("/myfile.txt", "w");
    if (!testFile) 
    {
      Serial.println("file creation failed");
    }
    //write two lines
    testFile.println("this is line 1");
    testFile.println("this is line 2");
  } 
  else 
  {
    // we could open the file
    while(testFile.available()) 
    {
      //read line by line from the file
      String line = testFile.readStringUntil('\n');
      Serial.println(line);
    }
 
  }
  testFile.close();
}
 
void loop() 
{
}

 

Output

Open the serial monitor

SPIFFS opened:
File doesn’t exist yet. Creating it

Now reset the board

SPIFFS opened:
this is line 1
this is line 2

 

WS2812B RGB Shield and ESP8266 example

We are going to look at a WS2812b led or neopixel in this example, again we use a Wemos mini and an RGB LED shield

Lets take a look a the shields and boards that are required

 

Image Summary
The Wemos mini – ESP8266 based board, it comes with various headers. This is the beauty of it you can create stackable projects with the board and pin compatible shields
An RGB LED shield – sometimes known as Neopixel
This is simply a base, you plug the Wemos Mini into one side and you can plug a shield or shields into the other side

 

 

Parts List

1 x Wemos Mini
1 x Wemos Dual Base (optional)
1 x RGB shield

I connect the Wemos Mini to the dual base and then put the WS2812b shield along side this. You could stack these.

 

Code

This library is required – you can install these via the library manager

https://github.com/adafruit/Adafruit_NeoPixel

 

#include <Adafruit_NeoPixel.h>
#define NEOPIN D2
Adafruit_NeoPixel pixels = Adafruit_NeoPixel(1, NEOPIN, NEO_GRB + NEO_KHZ800);
char SerialInput;
void setup()
{
// initialize journal printer sensors to default states
Serial.begin(9600);
pixels.begin(); // This initializes the NeoPixel library.
pixels.setPixelColor(0, pixels.Color(0, 0, 0)); // Moderately bright green color.
pixels.show(); // This sends the updated pixel color to the hardware.
}
void loop()
{
// For a set of NeoPixels the first NeoPixel is 0, second is 1, all the way up to the count of pixels minus one.
SerialInput = Serial.read();
//verify incoming option
switch(SerialInput)
{
case '1':
// RED ON
pixels.setPixelColor(0, pixels.Color(255, 0, 0)); // Moderately bright green color.
pixels.show(); // This sends the updated pixel color to the hardware.
break;
case '2':
// ALL off
pixels.setPixelColor(0, pixels.Color(0, 0, 0)); // Moderately bright green color.
pixels.show(); // This sends the updated pixel color to the hardware.
break;
case '3':
// GREEN ON
pixels.setPixelColor(0, pixels.Color(0, 255, 0)); // Moderately bright green color.
pixels.show(); // This sends the updated pixel color to the hardware.
break;
case '4':
// ALL off
pixels.setPixelColor(0, pixels.Color(0, 0, 0)); // Moderately bright green color.
pixels.show(); // This sends the updated pixel color to the hardware.
break;
case '5':
// BLUE ON
pixels.setPixelColor(0, pixels.Color(0, 0, 255)); // Moderately bright green color.
pixels.show(); // This sends the updated pixel color to the hardware.
break;
case '6':
// ALL off
pixels.setPixelColor(0, pixels.Color(0, 0, 0)); // Moderately bright green color.
pixels.show(); // This sends the updated pixel color to the hardware.
break;
}
}

 

Output

Open the serial monitor and type in the number 1 to 6 to see a different colour on the LED

 

 

Links

 

Smart Electronics D1 mini – Mini NodeMcu 4M bytes development board based ESP8266 by WeMos

Dual Base Expansion board for WeMos D1 mini NodeMCU ESP8266

For WeMos D1 Mini RGB LED Shield Esp8266 For Wemos D1 Mini Shield Expansion Board For Arduino

ESP8266 Project : DHT11 readings stored on an SD card

In this particular example we are going to store temperature readings from a DHT11 on an sd card we will be using a Wemos mini and a variety of shields which make it easy to create projects like this with no wiring.

Lets take a look a the shields and boards that are required

 

Image Summary
The Wemos mini – ESP8266 based board, it comes with various headers. This is the beauty of it you can create stackable projects with the board and pin compatible shields
This shield features the DHT sensor, there are actually a couple of variations of this sensor which use slightly different sensors. The original was a dht11 and the newer one is a DHT12
This allows you to use micro sd cards in your projects, The shield uses the SPI bus pins
This is simply a base, you plug the Wemos Mini into one side and you can plug a shield or shields into the other side

 

 

 

Parts List

1 x Wemos Mini
1 x Wemos Dual Base
1 x Micro SD shield
1 x DHT shield (DHt11)

I connect the Wemos Mini to the dual base and then put the SD card shield along side this, I then place the DHT shield on top of the Wemos Mini.

 

Code

Various libraries required – you can install these via the library manager, here are links to them

https://github.com/adafruit/DHT-sensor-library
https://github.com/adafruit/Adafruit_Sensor

#include <SPI.h>
#include <SD.h>
#include "DHT.h"
#define DHTPIN D4 // what pin we're connected to
#define DHTTYPE DHT11 // DHT 11
const int chipSelect = D8;
File myFile;
DHT dht(DHTPIN, DHTTYPE);
void setup()
{
// Open serial communications and wait for port to open:
Serial.begin(9600);
//init SD card
Serial.print("Initializing SD card...");
if (!SD.begin(chipSelect))
{
Serial.println("initialization failed!");
return;
}
Serial.println("initialization done.");
}
void loop()
{
myFile = SD.open("tempdata.csv", FILE_WRITE);//change the file name if you want
delay(2000);
float h = dht.readHumidity();
float t = dht.readTemperature();
float f = dht.readTemperature(true);
// Check if any reads failed and exit early (to try again).
if (isnan(h) || isnan(t) || isnan(f))
{
Serial.println("Failed to read from DHT sensor!");
return;
}
//debug
Serial.print("Humidity: ");
Serial.print(h);
Serial.print(" %\t");
Serial.print("Temperature: ");
Serial.print(t);
Serial.print(" *C ");
Serial.print(f);
Serial.print(" *F\t");
// if the file opened okay, write to it:
if (myFile)
{
Serial.print("Writing to tempdata.csv...");
myFile.print(h);
myFile.print(",");
myFile.print(t);
myFile.print(",");
myFile.println(f);
// close the file:
myFile.close();
Serial.println("done.");
}
else
{
// if the file didn't open, print an error:
Serial.println("error opening tempdata.csv");
}
}

 

Again if you don’t want to type all of this in then you can download at wemos_sdcard_dht11

 

Output

Here is the output from the serial monitor and there will also be data on the sd card

 

Initializing SD card…initialization done.
Humidity: 19.00 % Temperature: 20.00 *C 68.00 *F Writing to tempdata.csv…done.
Humidity: 19.00 % Temperature: 20.00 *C 68.00 *F Writing to tempdata.csv…done.
Humidity: 19.00 % Temperature: 20.00 *C 68.00 *F Writing to tempdata.csv…done.
Humidity: 19.00 % Temperature: 20.00 *C 68.00 *F Writing to tempdata.csv…done.
Humidity: 20.00 % Temperature: 20.00 *C 68.00 *F Writing to tempdata.csv…done.
Humidity: 20.00 % Temperature: 20.00 *C 68.00 *F Writing to tempdata.csv…done.
Humidity: 19.00 % Temperature: 21.00 *C 69.80 *F Writing to tempdata.csv…done.
Humidity: 19.00 % Temperature: 23.00 *C 73.40 *F Writing to tempdata.csv…done.
Humidity: 19.00 % Temperature: 23.00 *C 73.40 *F Writing to tempdata.csv…done.
Humidity: 19.00 % Temperature: 23.00 *C 73.40 *F Writing to tempdata.csv…done.

 

Links

 

Smart Electronics D1 mini – Mini NodeMcu 4M bytes development board based ESP8266 by WeMos

Dual Base Expansion board for WeMos D1 mini NodeMCU ESP8266

DHT Shield for WeMos D1 mini DHT11 Single-bus digital temperature and humidity sensor module sensor

Micro SD Card Shield IoT Wireless Control for D1 Mini ESP8266 WiFi WeMos Module

ESP8266 Project : DHT11 readings on an OLED

In this particular example we are going to display temperature readings from a DHT11 on an OLED display, we will be using a Wemos mini and a variety of shields which make it easy to create projects like this with no wiring.

Lets take a look a the shields and boards that are required

 

Image Summary
The Wemos mini – ESP8266 based board, it comes with various headers. This is the beauty of it you can create stackable projects with the board and pin compatible shields
This shield features the DHT sensor, there are actually a couple of variations of this sensor which use slightly different sensors. The original was a dht11 and the newer one is a DHT12
A  64×48 OLED screen
This is simply a base, you plug the Wemos Mini into one side and you can plug a shield or shields into the other side

 

 

 

Parts List

1 x Wemos Mini
1 x Wemos Dual Base
1 x OLED Shield
1 x DHT shield (DHt11)

I connect the Wemos Mini to the dual base and then put the OLED shield along side this, I then place the DHT shield on top of the Wemos Mini.

 

Code

Various libraries required – you can install these via the library manager, here are links to them

https://github.com/sparkfun/SparkFun_Micro_OLED_Arduino_Library 

https://github.com/adafruit/DHT-sensor-library
https://github.com/adafruit/Adafruit_Sensor

#include "DHT.h" //https://github.com/adafruit/DHT-sensor-library and
//https://github.com/adafruit/Adafruit_Sensor
#include <Wire.h> // Include Wire if you're using I2C
#include <SFE_MicroOLED.h> // Include the SFE_MicroOLED library
#define DHTPIN D4 // what pin we're connected to
#define DHTTYPE DHT11 // DHT 11
#define PIN_RESET 255 //
#define DC_JUMPER 0 // I2C Addres: 0 - 0x3C, 1 - 0x3D
MicroOLED oled(PIN_RESET, DC_JUMPER); // Example I2C declaration
DHT dht(DHTPIN, DHTTYPE);
void setup()
{
Serial.begin(9600);
dht.begin();
oled.begin();
oled.clear(ALL); // Clear the display's memory (gets rid of artifacts)
oled.display();
}
void loop()
{
// Wait a few seconds between measurements.
delay(2000);
float h = dht.readHumidity();
float t = dht.readTemperature();
// Check if any reads failed and exit early (to try again).
if (isnan(h) || isnan(t))
{
Serial.println("Failed to read from DHT sensor!");
return;
}
oled.clear(PAGE);
oled.setFontType(0); // set font type 0, please see declaration in SFE_MicroOLED.cpp
oled.setCursor(1, 3);
oled.print("Humidity: ");
oled.setCursor(1, 12);
oled.print(h);
oled.print(" %\t");
oled.setCursor(1, 21);
oled.print("Temp :");
oled.setCursor(1, 30);
oled.print(t);
oled.print(" *C ");
oled.display();
}

 

Again if you don’t want to type all of this in then you can download wemos_oled_dht11

Output

Here you can see the output and my setup in another blurry image

 

Links

 

Smart Electronics D1 mini – Mini NodeMcu 4M bytes development board based ESP8266 by WeMos

0.66″ inch For Wemos Oled 64X48 IIC I2C LCD OLED LED Display Shield

Dual Base Expansion board for WeMos D1 mini NodeMCU ESP8266

DHT Shield for WeMos D1 mini DHT11 Single-bus digital temperature and humidity sensor module sensor

ESP8266 Project : BMP180 readings on an OLED

In this particular example we are going to display temperature readings from a BMP180 on an OLED display, we will be using a Wemos mini and a variety of shields which make it easy to create projects like this with no wiring.

Lets take a look a the shields and boards that are required

 

Image Summary
The Wemos mini – ESP8266 based board, it comes with various headers. This is the beauty of it you can create stackable projects with the board and pin compatible shields
Another unofficial shield that is readily available – this time its a BMP180 sensor thats fitted
A  64×48 OLED screen
This is simply a base, you plug the Wemos Mini into one side and you can plug a shield or shields into the other side

 

 

 

Parts List

1 x Wemos Mini
1 x Wemos Dual Base
1 x OLED Shield
1 x BMP180 shield

I connect the Wemos Mini to the dual base and then put the OLED shield along side this, I then place the BMP180 shield on top of the Wemos Mini.

 

Code

Various libraries required – you can install these via the library manager, here are links to them

https://github.com/sparkfun/SparkFun_Micro_OLED_Arduino_Library 

 

#include <Wire.h>
#include <Adafruit_BMP085.h>
#include <SFE_MicroOLED.h> // Include the SFE_MicroOLED library
#define PIN_RESET 255 //
#define DC_JUMPER 0 // I2C Addres: 0 - 0x3C, 1 - 0x3D
MicroOLED oled(PIN_RESET, DC_JUMPER); // Example I2C declaration
Adafruit_BMP085 bmp;
void setup()
{
Serial.begin(9600);
if (!bmp.begin()) {
Serial.println("Could not find a valid BMP180 sensor, check wiring!");
while (1) {}
}
oled.begin();
oled.clear(ALL); // Clear the display's memory (gets rid of artifacts)
oled.display();
}
void loop()
{
// Wait a few seconds between measurements.
delay(2000);
oled.clear(PAGE);
oled.setFontType(0); // set font type 0, please see declaration in SFE_MicroOLED.cpp
oled.setCursor(1, 3);
oled.print("Pressure = ");
oled.setCursor(1, 12);
oled.print(bmp.readPressure());
oled.print(" Pa");
oled.setCursor(1, 21);
oled.print("Temp =");
oled.setCursor(1, 30);
oled.print(bmp.readTemperature());
oled.print(" *C ");
oled.display();
delay(2000);
//2nd page of readings
oled.clear(PAGE);
oled.setFontType(0); // set font type 0, please see declaration in SFE_MicroOLED.cpp
oled.setCursor(1, 3);
oled.print("Altitude = ");
oled.setCursor(1, 12);
oled.print(bmp.readAltitude());
oled.print(" m");
oled.setCursor(1, 21);
oled.print("Sea Level=");
oled.setCursor(1, 30);
oled.print(bmp.readSealevelPressure());
oled.print(" Pa");
oled.display();
}

 

Again if you don’t want to type all of this in then you can download wemos_OLED_bmp180

Output

Here you can see the output and my setup

 

bmp180 output

bmp180 output

 

Links

 

Smart Electronics D1 mini – Mini NodeMcu 4M bytes development board based ESP8266 by WeMos

0.66″ inch For Wemos Oled 64X48 IIC I2C LCD OLED LED Display Shield

Dual Base Expansion board for WeMos D1 mini NodeMCU ESP8266

Wemos BMP180 Digital Barometric Pressure Sensor Module Replace BMP085 BSG For Wemos D1 Mini