help combining two sketches

hello everyone ,
I just need help with combining the two sketches .
I am using Urduino mega, ehternet shield w5100, and time keeper ds3231 .
the first code below work well, I can browse the sd card contain using firefox ,

and the second code is to read the temperature and time then write to the csv file …
call datalog.csv .
out put to serial some thing like this …

date time temp

10/3/2016 , 12:45 , 25

it is working …

and the third lot of code I need help on this , especially in the void loop
where this code should go …?

DateTime now = RTC.now(); // get time from RTC
int time = now.second();
// if (abs(time - lastTime) > 5)
{
// int chk = DHT.read22(DHT22_PIN); // get data from DHT22
sensors.requestTemperatures(); // get data from DS18B20
temp = sensors.getTempCByIndex(0);

File dataFile = SD.open(“datalog.CSV”, FILE_WRITE);

// if the file is available, write to it:
if (dataFile) {
dataFile.print(now.day(), DEC);
dataFile.print(’/’);

Serial.println(“error opening datalog.CSV”);
}

when I upload the third code to the urduino , I am unable to access or view the sd card
contain… as the code list below keep on looping…
and this is the serial out put when the third code run…

(Free RAM: 6465
Initializing SD card…Volume is FAT32

Files found in root:
DATALOG.CSV 2016-03-16 21:25:48 259035

Done
2016, Room Temperature = 28.00

please help .thank you :slight_smile:

first code

#include <SD.h>
#include <SdFatUtil.h>
#include <Ethernet.h>
#include <SPI.h>

/************ ETHERNET STUFF ************/
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
byte ip[] = { 192, 168, 50, 80 };
EthernetServer server(80);

/************ SDCARD STUFF ************/
Sd2Card card;
SdVolume volume;
SdFile root;
SdFile file;

// store error strings in flash to save RAM
#define error(s) error_P(PSTR(s))

void error_P(const char* str) {
  PgmPrint("error: ");
  SerialPrintln_P(str);
  if (card.errorCode()) {
    PgmPrint("SD error: ");
    Serial.print(card.errorCode(), HEX);
    Serial.print(',');
    Serial.println(card.errorData(), HEX);
  }
  while(1);
}

void setup() {
  Serial.begin(9600);
 
  PgmPrint("Free RAM: ");
  Serial.println(FreeRam());  
  
  // initialize the SD card at SPI_HALF_SPEED to avoid bus errors with
  // breadboards.  use SPI_FULL_SPEED for better performance.
  pinMode(10, OUTPUT);                      
  digitalWrite(10, HIGH);                    

  if (!card.init(SPI_HALF_SPEED, 4)) error("card.init failed!");
  
  // initialize a FAT volume
  if (!volume.init(&card)) error("vol.init failed!");

  PgmPrint("Volume is FAT");
  Serial.println(volume.fatType(),DEC);
  Serial.println();
  
  if (!root.openRoot(&volume)) error("openRoot failed");

  // list file in root with date and size
  PgmPrintln("Files found in root:");
  root.ls(LS_DATE | LS_SIZE);
  Serial.println();
  
  // Recursive list of all directories
  PgmPrintln("Files found in all dirs:");
  root.ls(LS_R);
  
  Serial.println();
  PgmPrintln("Done");
  
  // Debugging complete, we start the server!
  Ethernet.begin(mac, ip);
  server.begin();
}

void ListFiles(EthernetClient client, uint8_t flags) {
  // This code is just copied from SdFile.cpp in the SDFat library
  // and tweaked to print to the client output in html!
  dir_t p;
  
  root.rewind();
  client.println("<ul>");
  while (root.readDir(p) > 0) {
    // done if past last used entry
    if (p.name[0] == DIR_NAME_FREE) break;

    // skip deleted entry and entries for . and  ..
    if (p.name[0] == DIR_NAME_DELETED || p.name[0] == '.') continue;

    // only list subdirectories and files
    if (!DIR_IS_FILE_OR_SUBDIR(&p)) continue;

    // print any indent spaces
    client.print("<li><a href=\"");
    for (uint8_t i = 0; i < 11; i++) {
      if (p.name[i] == ' ') continue;
      if (i == 8) {
        client.print('.');
      }
      client.print((char)p.name[i]);
    }
    client.print("\">");
    
    // print file name with possible blank fill
    for (uint8_t i = 0; i < 11; i++) {
      if (p.name[i] == ' ') continue;
      if (i == 8) {
        client.print('.');
      }
      client.print((char)p.name[i]);
    }
    
    client.print("</a>");
    
    if (DIR_IS_SUBDIR(&p)) {
      client.print('/');
    }

    // print modify date/time if requested
    if (flags & LS_DATE) {
       root.printFatDate(p.lastWriteDate);
       client.print(' ');
       root.printFatTime(p.lastWriteTime);
    }
    // print size if requested
    if (!DIR_IS_SUBDIR(&p) && (flags & LS_SIZE)) {
      client.print(' ');
      client.print(p.fileSize);
    }
    client.println("</li>");
  }
  client.println("</ul>");
}

// How big our line buffer should be. 100 is plenty!
#define BUFSIZ 100

void loop()
{
  char clientline[BUFSIZ];
  int index = 0;
  
  EthernetClient client = server.available();
  if (client) {
    // an http request ends with a blank line
    boolean current_line_is_blank = true;
    
    // reset the input buffer
    index = 0;
    
    while (client.connected()) {
      if (client.available()) {
        char c = client.read();
        
        // If it isn't a new line, add the character to the buffer
        if (c != '\n' && c != '\r') {
          clientline[index] = c;
          index++;
          // are we too big for the buffer? start tossing out data
          if (index >= BUFSIZ) 
            index = BUFSIZ -1;
          
          // continue to read more data!
          continue;
        }
        
        // got a \n or \r new line, which means the string is done
        clientline[index] = 0;
        
        // Print it out for debugging
        Serial.println(clientline);
        
        // Look for substring such as a request to get the root file
        if (strstr(clientline, "GET / ") != 0) {
          // send a standard http response header
          client.println("HTTP/1.1 200 OK");
          client.println("Content-Type: text/html");
          client.println();
          
          // print all the files, use a helper to keep it clean
          client.println("<h2>Files:</h2>");
          ListFiles(client, LS_SIZE);
        } else if (strstr(clientline, "GET /") != 0) {
          // this time no space after the /, so a sub-file!
          char *filename;
          
          filename = clientline + 5; // look after the "GET /" (5 chars)
          // a little trick, look for the " HTTP/1.1" string and 
          // turn the first character of the substring into a 0 to clear it out.
          (strstr(clientline, " HTTP"))[0] = 0;
          
          // print the file we want
          Serial.println(filename);

          if (! file.open(&root, filename, O_READ)) {
            client.println("HTTP/1.1 404 Not Found");
            client.println("Content-Type: text/html");
            client.println();
            client.println("<h2>File Not Found!</h2>");
            break;
          }
          
          Serial.println("Opened!");
                    
          client.println("HTTP/1.1 200 OK");
          client.println("Content-Type: text/plain");
          client.println();
          
          int16_t c;
          while ((c = file.read()) > 0) {
              // uncomment the serial to debug (slow!)
              //Serial.print((char)c);
              client.print((char)c);
          }
          file.close();
        } else {
          // everything else is a 404
          client.println("HTTP/1.1 404 Not Found");
          client.println("Content-Type: text/html");
          client.println();
          client.println("<h2>File Not Found!</h2>");
        }
        break;
      }
    }
    // give the web browser time to receive the data
    delay(1);
    client.stop();
  }
}

second code
please see attachment
third code
please see attachment

thirdcode.ino (8.66 KB)

secondcode.ino (4.29 KB)

Hi

Welcome to the forum. Can you please post a copy of your sketch, using code tags? Please use code tags.. See section 7 http://forum.arduino.cc/index.php/topic,148850.0.html

Thanks...It helps to read your sketch with scrolling text...Tom.. :)

the second code

#include <SPI.h>
#include <Ethernet.h>
#include <Wire.h>
#include "RTClib.h"
#include <DHT.h>
#include <SD.h>
#include <OneWire.h>
#include <DallasTemperature.h>

//OneWire  ds(10);  // on pin 10

const int ONE_WIRE_BUS = 10;                // signal pin of DS18B20 connected to pin 3
OneWire ourWire(ONE_WIRE_BUS);
DallasTemperature sensors(&ourWire);

//dht DHT;

RTC_DS1307 RTC;

#define DHTTYPE DHT22 // Sensor type
#define DHT22_PIN 2   // DHT22 signal on pin 2

byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
byte ip[] = {192,168,50, 80 };

int lastTime = -1;

float temp;            // float for temperature value from DS18B20

EthernetServer server(80);

const int chipSelect = 4;      // CS for SD card

void setup()
{
  Serial.begin(9600);
  Ethernet.begin(mac, ip);
  server.begin();
  Wire.begin();
  
  sensors.begin();            // for DS18B20 sensor
  RTC.begin();
  RTC.adjust(DateTime(__DATE__, __TIME__));
  Serial.print("Initializing SD card...");
  //pinMode(10, OUTPUT);

  // see if the card is present and can be initialized:
  if (!SD.begin(chipSelect)) {
    Serial.println("Card failed, or not present");
    // don't do anything more:
    return;
  }
  Serial.println("card initialized.");
}

void loop()
{
  DateTime now = RTC.now();                              // get time from RTC

  int time = now.second();
  if (abs(time - lastTime) > 5)
  {
//    int chk = DHT.read22(DHT22_PIN);                       // get data from DHT22
    sensors.requestTemperatures();                         // get data from DS18B20
    temp = sensors.getTempCByIndex(0);                  


    File dataFile = SD.open("datalog.CSV", FILE_WRITE);

    // if the file is available, write to it:
    if (dataFile) {
      dataFile.print(now.day(), DEC);
      dataFile.print('/');
      dataFile.print(now.month(), DEC);
      dataFile.print('/');
      dataFile.print(now.year(), DEC);
      dataFile.print(" , ");
      dataFile.print(now.hour(), DEC);
      dataFile.print(':');
      dataFile.print(now.minute(), DEC);
      dataFile.print(" , ");
//      dataFile.print((float)DHT.temperature);
      dataFile.print(" , ");
      dataFile.println((float)temp);
      dataFile.close();
      // print to the serial port too:
     // Serial.print("DHT = ");
//      Serial.println(DHT.temperature);
      Serial.print("DS18B20 = ");
      Serial.println(temp);
    }  
    // if the file isn't open, pop up an error:
    else {
      Serial.println("error opening datalog.CSV");
    }
    lastTime = time;
  }

  EthernetClient client = server.available();
  if (client) {
    // an http request ends with a blank line
    boolean currentLineIsBlank = true;
    while (client.connected()) {
      if (client.available()) {
        char c = client.read();
        if (c == '\n' && currentLineIsBlank) {
          // send a standard http response header
          client.println("HTTP/1.1 200 OK");
          client.println("Content-Type: text/html");
          client.println();
          
          client.print(now.day(), DEC);
          client.print('/');
          client.print(now.month(), DEC);
          client.print('/');
          client.print(now.year(), DEC);
          client.print(' ');
          client.print(now.hour(), DEC);
          client.print(':');
          client.print(now.minute(), DEC);
          client.println("
");
          client.print("Arduino powered webserver");
          client.println("
");
          client.print("Serving temperature and humidity values from a DHT22 and DS18B20 sensor");
          client.println("
");
          client.print("Inside temperature (oC): ");
  //        client.print(DHT.temperature);
          client.println("
");
          client.print("Humidity (%): ");
//          client.print(DHT.humidity);
          client.println("
"); 
          client.print("Outside temperature (oC): ");
          client.print(temp); 
          client.println("
"); 

          break;
        }
        if (c == '\n') {
          // you're starting a new line
          currentLineIsBlank = true;
        } 
        else if (c != '\r') {
          // you've gotten a character on the current line
          currentLineIsBlank = false;
        }
      }
    }
    // give the web browser time to receive the data
    delay(1);
    // close the connection:
    client.stop();
  } 
}

[/code]

sorry , it was complaining about 9000 charactoers limit

and the third code…

#include <SPI.h>
#include <Ethernet.h>
#include <Wire.h>
#include "RTClib.h"
#include <DHT.h>
#include <SD.h>
#include <OneWire.h>
#include <DallasTemperature.h>
#include <SdFatUtil.h>

byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
byte ip[] = {192,168,50,80};
EthernetServer server(80);


const int ONE_WIRE_BUS = 10;                // signal pin of DS18B20 connected to pin 3
OneWire ourWire(ONE_WIRE_BUS);
DallasTemperature sensors(&ourWire);


RTC_DS1307 RTC;

#define DHTTYPE DHT22 // Sensor type
#define DHT22_PIN 2   // DHT22 signal on pin 2

int lastTime = -1;
const int chipSelect = 4;      // CS for SD card
float temp;            


Sd2Card card;
SdVolume volume;
SdFile root;
SdFile file;

// store error strings in flash to save RAM
#define error(s) error_P(PSTR(s))

void error_P(const char* str) {
  PgmPrint("error: ");
  SerialPrintln_P(str);
  if (card.errorCode()) {
    PgmPrint("SD error: ");
    Serial.print(card.errorCode(), HEX);
    Serial.print(',');
    Serial.println(card.errorData(), HEX);
  }
  while(1);
}

void setup() {
  Serial.begin(9600);
   Wire.begin();
  sensors.begin();            // for DS18B20 sensor
  RTC.begin();
  RTC.adjust(DateTime(__DATE__, __TIME__));
    
  PgmPrint("Free RAM: ");
  Serial.println(FreeRam());  
  
  // initialize the SD card at SPI_HALF_SPEED to avoid bus errors with
  // breadboards.  use SPI_FULL_SPEED for better performance.
  pinMode(10, OUTPUT);                       // set the SS pin as an output (necessary!)
  digitalWrite(10, HIGH);                    // but turn off the W5100 chip!

   Serial.print("Initializing SD card...");
  // see if the card is present and can be initialized:
  if (!SD.begin(chipSelect)) {
    Serial.println("Card failed, or not present");
    // don't do anything more:
    return;
  }

  if (!card.init(SPI_HALF_SPEED, 4)) error("card.init failed!");
  
  // initialize a FAT volume
  if (!volume.init(&card)) error("vol.init failed!");

  PgmPrint("Volume is FAT");
  Serial.println(volume.fatType(),DEC);
  Serial.println();
  
  if (!root.openRoot(&volume)) error("openRoot failed");

  // list file in root with date and size
  PgmPrintln("Files found in root:");
  root.ls(LS_DATE | LS_SIZE);
  Serial.println();
  
//   Recursive list of all directories
 // PgmPrintln("Files found in all dirs:");
 // root.ls(LS_R);
  
  Serial.println();
  PgmPrintln("Done");
  
  // Debugging complete, we start the server!
  Ethernet.begin(mac, ip);
  server.begin();
}
// WORK UP TO HERE 7:30 17/3/2016  JUST ADDED THE VOID LISTFILES 

void ListFiles(EthernetClient client, uint8_t flags) {
  // This code is just copied from SdFile.cpp in the SDFat library
  // and tweaked to print to the client output in html!
  dir_t p;
  root.rewind();
  client.println("<ul>");
  while (root.readDir(p) > 0) {
    // done if past last used entry
    if (p.name[0] == DIR_NAME_FREE) break;

    // skip deleted entry and entries for . and  ..
    if (p.name[0] == DIR_NAME_DELETED || p.name[0] == '.') continue;

    // only list subdirectories and files
    if (!DIR_IS_FILE_OR_SUBDIR(&p)) continue;

    // print any indent spaces
    client.print("<li><a href=\"");
    for (uint8_t i = 0; i < 11; i++) {
      if (p.name[i] == ' ') continue;
      if (i == 8) {
        client.print('.');
      }
      client.print((char)p.name[i]);
    }
    client.print("\">");
    
    // print file name with possible blank fill
    for (uint8_t i = 0; i < 11; i++) {
      if (p.name[i] == ' ') continue;
      if (i == 8) {
        client.print('.');
      }
      client.print((char)p.name[i]);
    }
    
    client.print("</a>");
    
    if (DIR_IS_SUBDIR(&p)) {
      client.print('/');
    }

    // print modify date/time if requested
    if (flags & LS_DATE) {
       root.printFatDate(p.lastWriteDate);
       client.print(' ');
       root.printFatTime(p.lastWriteTime);
    }
    // print size if requested
    if (!DIR_IS_SUBDIR(&p) && (flags & LS_SIZE)) {
      client.print(' ');
      client.print(p.fileSize);
    }
    client.println("</li>");
  }
  client.println("</ul>");
}

// 7:44 COMFILED AND UPLOAD OK  , FROM HERE JUST ADD LOOP 


// How big our line buffer should be. 100 is plenty!
#define BUFSIZ 100

void loop()
{
char clientline[BUFSIZ];
int index = 0;


EthernetClient client = server.available();
  if (client) {
    // an http request ends with a blank line
    boolean current_line_is_blank = true;
    
    // reset the input buffer
    index = 0;
    
    while (client.connected()) {
      if (client.available()) {
        char c = client.read();
        
        // If it isn't a new line, add the character to the buffer
        if (c != '\n' && c != '\r') {
          clientline[index] = c;
          index++;
          // are we too big for the buffer? start tossing out data
          if (index >= BUFSIZ) 
            index = BUFSIZ -1;
          
          // continue to read more data!
          continue;
        }
        
        // got a \n or \r new line, which means the string is done
        clientline[index] = 0;
        
        // Print it out for debugging
        Serial.println(clientline);
        
        // Look for substring such as a request to get the root file
        if (strstr(clientline, "GET / ") != 0) {
          // send a standard http response header
          client.println("HTTP/1.1 200 OK");
          client.println("Content-Type: text/html");
          client.println();
          
          // print all the files, use a helper to keep it clean
          client.println("<h2>Files:</h2>");
          ListFiles(client, LS_SIZE);
        } else if (strstr(clientline, "GET /") != 0) {
          // this time no space after the /, so a sub-file!
          char *filename;
          
          filename = clientline + 5; // look after the "GET /" (5 chars)
          // a little trick, look for the " HTTP/1.1" string and 
          // turn the first character of the substring into a 0 to clear it out.
          (strstr(clientline, " HTTP"))[0] = 0;
          
          // print the file we want
          Serial.println(filename);

          if (! file.open(&root, filename, O_READ)) {
            client.println("HTTP/1.1 404 Not Found");
            client.println("Content-Type: text/html");
            client.println();
            client.println("<h2>File Not Found!</h2>");
            break;
          }
          
          Serial.println("Opened!");
                    
          client.println("HTTP/1.1 200 OK");
          client.println("Content-Type: text/plain");
          client.println();
          
          int16_t c;
          while ((c = file.read()) > 0) {
              // uncomment the serial to debug (slow!)
              //Serial.print((char)c);
              client.print((char)c);
          }
          file.close();
        } else {
          // everything else is a 404
          client.println("HTTP/1.1 404 Not Found");
          client.println("Content-Type: text/html");
          client.println();
          client.println("<h2>File Not Found!</h2>");
        }
        break;
      }
    }
    // give the web browser time to receive the data
    delay(1);
    client.stop();
  }

  
  DateTime now = RTC.now();                              // get time from RTC
  int time = now.second();
  // if (abs(time - lastTime) > 5)
  {
// int chk = DHT.read22(DHT22_PIN);                       // get data from DHT22
   sensors.requestTemperatures();                         // get data from DS18B20
    temp = sensors.getTempCByIndex(0);                  

    File dataFile = SD.open("datalog.CSV", FILE_WRITE);

    // if the file is available, write to it:
    if (dataFile) {
      dataFile.print(now.day(), DEC);
      dataFile.print('/');
      dataFile.print(now.month(), DEC);
      dataFile.print('/');
      dataFile.print(now.year(), DEC);
      dataFile.print(" , ");
      dataFile.print(now.hour(), DEC);
      dataFile.print(':');
      dataFile.print(now.minute(), DEC);
       dataFile.print(" , ");
      dataFile.println((float)temp);
      dataFile.close();
        
      Serial.print(now.year(), DEC);
     Serial.print(", Room Temperature = ");
      Serial.println(temp);
    }  
    // if the file isn't open, pop up an error:
    else {
      Serial.println("error opening datalog.CSV");
    }
    lastTime = time;
  }   

}

hello again ,

in the "third code" , when removed this part of the code in the void loop... and upload... this is the result from serial display...

Free RAM: 6545 Initializing SD card...Volume is FAT32

Files found in root: DATALOG.CSV 2016-03-16 21:25:48 441775

Done GET / HTTP/1.1 GET /DATALOG.CSV HTTP/1.1 DATALOG.CSV Opened!

when open firefox (192.168.0.20) I got DATALOG.CSV DIPLAY which is work perfect, but without the date, time, and temperature continue logging .

Just hope someone follow this and please help , where the right place to insert this code ..

many thanks

  DateTime now = RTC.now();                              // get time from RTC
  int time = now.second();
  // if (abs(time - lastTime) > 5)
  {
// int chk = DHT.read22(DHT22_PIN);                       // get data from DHT22
   sensors.requestTemperatures();                         // get data from DS18B20
    temp = sensors.getTempCByIndex(0);                  

    File dataFile = SD.open("datalog.CSV", FILE_WRITE);

    // if the file is available, write to it:
    if (dataFile) {
      dataFile.print(now.day(), DEC);
      dataFile.print('/');
      dataFile.print(now.month(), DEC);
      dataFile.print('/');
      dataFile.print(now.year(), DEC);
      dataFile.print(" , ");
      dataFile.print(now.hour(), DEC);
      dataFile.print(':');
      dataFile.print(now.minute(), DEC);
       dataFile.print(" , ");
      dataFile.println((float)temp);
      dataFile.close();
        
      Serial.print(now.year(), DEC);
     Serial.print(", Room Temperature = ");
      Serial.println(temp);
    }  
    // if the file isn't open, pop up an error:
    else {
      Serial.println("error opening datalog.CSV");
    }
    lastTime = time;
  }

After days of searching and practice , I finally did it, all informations here in the forum :)