Enable Javascript


Last Arduino/ESP8266 project (click to open)

User Rating: 5 / 5

Star ActiveStar ActiveStar ActiveStar ActiveStar Active
 

Article Index

ESP8266:

/*  DEMO Arduino + NodeMCU Shield
 *   With softwareSerial and micro SD
 *   Edited SD and SoftwareSerial examples
 *****************************************/

#include <SPI.h>             // https://github.com/esp8266/Arduino
#include <SD.h>              // https://github.com/esp8266/Arduino
#include <SoftwareSerial.h>  // https://github.com/esp8266/Arduino
#include <Streaming.h>       // http://arduiniana.org/libraries/streaming

File root;
SoftwareSerial serial(D1, D2, false, 128);  // RX-D1->UNO-TX, TX-D2->UNO-RX

void listFiles();
void printDirectory(File, int);
void show(String);

void setup() {
  Serial.begin(115200);  // to monitor (DEBUG)
  serial.begin(38400);   // to Arduino
  while (!Serial) {};    // wait for serial port to connect. Needed for native USB port only
  for (uint8_t t = 5; t > 0; t--) { 
    Serial.println();
    Serial.flush();
    delay(1000);
  }

  show("\n\nESP8266 Software serial test started\n");
  listFiles();
  show("\nType text to send...\n");
}

void loop() {
  while (serial.available()) Serial << serial.readString();  // from Arduino
  while (Serial.available()) serial << Serial.readString();  // from ESP8266 Monitor to Arduino
}

void listFiles() {
  show("_______________________\nInitializing SD card...\n");
  if (!SD.begin(D4)) {
    show("initialization failed!\n");
    return;
  }
  show("initialization done.\n");
  root = SD.open("/");
  printDirectory(root, 0);
  show("SD card done!\n_______________________\n\n");
}

void printDirectory(File dir, int numTabs) {  // get a list of SD files 
   while(true) {
     File entry =  dir.openNextFile();
     if (! entry) {
       // no more files
       break;
     }
     for (uint8_t i=0; i<numTabs; i++) {
       show("\t");
     }
     show(entry.name());
     if (entry.isDirectory()) {
       show("/\n");
       printDirectory(entry, numTabs+1);
     } else {
       // files have sizes, directories do not
       show("\t\t");
       show(String(entry.size(), DEC) + "\n");
     }
     entry.close();
   }
}

void show(String s) {  // show it on Arduino and ESP8266 monitors
  Serial << s;
  serial << s;
}