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 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 : DS18b20 temperature on an OLED

In this particular example we are going to display temperature readings from a DS18B20 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

 

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
Not an official Wemos board but readily available featuring the ever popular DS18B20 temperature sensor
A little 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 Ds18B20 shield

I connect the Wemos Mini to the dual base and then put the OLED shield along side this, I then place the DS18b20 shield on top of the Wemos Mini. This image hopefully shows this

 

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 

You will also have to install the OneWire library

#include <OneWire.h>
#include <SFE_MicroOLED.h> // Include the SFE_MicroOLED library
#define PIN_RESET 255 //
#define DC_JUMPER 0 // I2C Addres: 0 - 0x3C, 1 - 0x3D
// OneWire DS18S20, DS18B20, DS1822 Temperature Example
OneWire ds(D2); // on pin D2 (a 4.7K resistor is necessary)
MicroOLED oled(PIN_RESET, DC_JUMPER); // Example I2C declaration
void setup(void)
{
Serial.begin(9600);
oled.begin();
oled.clear(ALL); // Clear the display's memory (gets rid of artifacts)
oled.display();
}
void loop(void)
{
byte i;
byte present = 0;
byte type_s;
byte data[12];
byte addr[8];
float celsius, fahrenheit;
if ( !ds.search(addr))
{
ds.reset_search();
delay(250);
return;
}
if (OneWire::crc8(addr, 7) != addr[7])
{
Serial.println("CRC is not valid!");
return;
}
// the first ROM byte indicates which chip
switch (addr[0])
{
case 0x10:
type_s = 1;
break;
case 0x28:
type_s = 0;
break;
case 0x22:
type_s = 0;
break;
default:
Serial.println("Device is not a DS18x20 family device.");
return;
}
ds.reset();
ds.select(addr);
ds.write(0x44, 1); // start conversion, with parasite power on at the end
delay(1000);
present = ds.reset();
ds.select(addr);
ds.write(0xBE); // Read Scratchpad
for ( i = 0; i < 9; i++)
{
data[i] = ds.read();
}
// Convert the data to actual temperature
int16_t raw = (data[1] << 8) | data[0];
if (type_s) {
raw = raw << 3; // 9 bit resolution default
if (data[7] == 0x10)
{
raw = (raw & 0xFFF0) + 12 - data[6];
}
}
else
{
byte cfg = (data[4] & 0x60);
if (cfg == 0x00) raw = raw & ~7; // 9 bit resolution, 93.75 ms
else if (cfg == 0x20) raw = raw & ~3; // 10 bit res, 187.5 ms
else if (cfg == 0x40) raw = raw & ~1; // 11 bit res, 375 ms
}
oled.clear(PAGE);
oled.setFontType(0); // set font type 0, please see declaration in SFE_MicroOLED.cpp
oled.setCursor(1, 3);
celsius = (float)raw / 16.0;
fahrenheit = celsius * 1.8 + 32.0;
oled.print("Cels = ");
oled.setCursor(1, 12);
oled.print(celsius);
oled.print(" *C");
oled.setCursor(1, 21);
oled.print("Fahr =");
oled.setCursor(1, 30);
oled.print(fahrenheit);
oled.print(" *F");
oled.display();
}

Can’t be bothered typing all that in – Wemos_OLED_DS18b20

 

Output

Here you can see the output and my setup

DS18b20 and WEMOS output

DS18b20 and WEMOS output

 

 

Links

You can hopefully pick this all up for $10

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

Shield for WeMos D1 mini V2 DS18B20 Single-bus digital temperature and humidity sensor module sensor

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

Dual Base Expansion board for WeMos D1 mini NodeMCU ESP8266

Build a luxmeter with an ESP8266 and an OPT3001 sensor

In this particular example we are going to simply display visible light measurements from a OPT3001 sensor on an OLED display. We will be using various Wemos MIni shields and an OPT3001 sensor

Here is a little about the OPT3001

The OPT3001 is a sensor that measures the intensity of visible light. The spectral response of the sensor tightly matches the photopic response of the human eye and includes significant infrared rejection.

The OPT3001 is a single-chip lux meter, measuring the intensity of light as visible by the human eye. The precision spectral response and strong IR rejection of the device enables the OPT3001 to accurately meter the intensity of light as seen by the human eye regardless of light source. The strong IR rejection also aids in maintaining high accuracy when industrial design calls for mounting the sensor under dark glass for aesthetics. The OPT3001 is designed for systems that create light-based experiences for humans, and an ideal preferred replacement for photodiodes, photoresistors, or other ambient light sensors with less human eye matching and IR rejection.

Parts List

1 x Wemos Mini
1 x Wemos Dual Base
1 x OLED Shield
1 x OPT3001 board

I connect the Wemos Mini to the dual base and then put the OLED shield along side this, I then connect the OPT3001 sensor to the Wemos Mini using cables.

Wemos  CJMCU-3001
3v3 Vcc
Gnd Gnd
SDA SDA
SCL SCL

 

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/closedcube/ClosedCube_OPT3001_Arduino

If you can’t be bothere dtyping all of this in you can download the sketch from luxmeter 

#include <Wire.h>  // Include Wire if you're using I2C
#include <SFE_MicroOLED.h>  // Include the SFE_MicroOLED library
#include <ClosedCube_OPT3001.h>
#define OPT3001_ADDRESS 0x44
#define PIN_RESET 255 //
#define DC_JUMPER 0 // I2C Addres: 0 - 0x3C, 1 - 0x3D
MicroOLED oled(PIN_RESET, DC_JUMPER);
ClosedCube_OPT3001 opt3001;
void setup()
{
Serial.begin(9600);
oled.begin();
oled.clear(ALL);
oled.display();
opt3001.begin(OPT3001_ADDRESS);
Serial.print("OPT3001 Manufacturer ID");
Serial.println(opt3001.readManufacturerID());
Serial.print("OPT3001 Device ID");
Serial.println(opt3001.readDeviceID());
configureSensor();
printResult("High-Limit", opt3001.readHighLimit());
printResult("Low-Limit", opt3001.readLowLimit());
Serial.println("----");
}
void loop()
{
OPT3001 result = opt3001.readResult();
printResult("OPT3001", result);
delay(500);
}
void configureSensor() {
OPT3001_Config newConfig;
newConfig.RangeNumber = B1100;
newConfig.ConvertionTime = B0;
newConfig.Latch = B1;
newConfig.ModeOfConversionOperation = B11;
OPT3001_ErrorCode errorConfig = opt3001.writeConfig(newConfig);
if (errorConfig != NO_ERROR)
printError("OPT3001 configuration", errorConfig);
else {
OPT3001_Config sensorConfig = opt3001.readConfig();
Serial.println("OPT3001 Current Config:");
Serial.println("------------------------------");
Serial.print("Conversion ready (R):");
Serial.println(sensorConfig.ConversionReady,HEX);
Serial.print("Conversion time (R/W):");
Serial.println(sensorConfig.ConvertionTime, HEX);
Serial.print("Fault count field (R/W):");
Serial.println(sensorConfig.FaultCount, HEX);
Serial.print("Flag high field (R-only):");
Serial.println(sensorConfig.FlagHigh, HEX);
Serial.print("Flag low field (R-only):");
Serial.println(sensorConfig.FlagLow, HEX);
Serial.print("Latch field (R/W):");
Serial.println(sensorConfig.Latch, HEX);
Serial.print("Mask exponent field (R/W):");
Serial.println(sensorConfig.MaskExponent, HEX);
Serial.print("Mode of conversion operation (R/W):");
Serial.println(sensorConfig.ModeOfConversionOperation, HEX);
Serial.print("Polarity field (R/W):");
Serial.println(sensorConfig.Polarity, HEX);
Serial.print("Overflow flag (R-only):");
Serial.println(sensorConfig.OverflowFlag, HEX);
Serial.print("Range number (R/W):");
Serial.println(sensorConfig.RangeNumber, HEX);
Serial.println("------------------------------");
}
}
void printResult(String text, OPT3001 result)
{
if (result.error == NO_ERROR)
{
Serial.print(text);
Serial.print(": ");
Serial.print(result.lux);
Serial.println(" lux");
oled.clear(PAGE);
oled.setFontType(0); // set font type 0, please see declaration in SFE_MicroOLED.cpp
oled.setCursor(1, 3);
oled.print("Lux: ");
oled.setCursor(1, 12);
oled.print(result.lux);
oled.print(" lux\t");
oled.display();
}
else
{
printError(text,result.error);
}
}
void printError(String text, OPT3001_ErrorCode error) {
Serial.print(text);
Serial.print(": [ERROR] Code #");
Serial.println(error);
}

 

Output

Here you can see the output and my setup

 

 

Links

 

Mini NodeMcu 4M bytes Lua WIFI Internet of Things development board based ESP8266 by WeMos

Double Socket Dual Base Shield for WeMos D1 Mini NodeMCU ESP8266 Diy PCB D1 Expansion board

64X48 IIC I2C LCD OLED LED Dispaly Shield for Arduino Compatible WeMos D1 Mini

OPT3001 CJMCU-3001 ambient light sensor eye like measurement light intensity single chip illumination meter