#include <SPI.h>
#include <SD.h>
File myFile;
const int chipSelect = 9;
unsigned long ledonoff     = 150;        
unsigned long ledjj = 0;           
unsigned long nubled = 0;
unsigned long interval       = 10000;         
unsigned long previousMillis = 0;            
unsigned long currentMillis = 0;
#include "DHT.h"
#define DHTPIN 2  
#define DHTTYPE DHT22 
DHT dht(DHTPIN, DHTTYPE);
#define led 4
boolean st=0;

void setup(){
  Serial.begin(9600);
  pinMode(led,OUTPUT);
  pinMode(8,OUTPUT);
   while (!Serial) {;}
  dht.begin(); 
  Serial.print("Initializing SD card...");
  pinMode(SS, OUTPUT);
  if (!SD.begin(chipSelect)) {
    Serial.println("initialization failed!");
    return;
  }
  Serial.println("initialization done.");
    delay(10); 
}

void loop(){
  currentMillis = millis();
  nubled = millis();
   float h = dht.readHumidity();
   float t = dht.readTemperature();
   if (isnan(h) || isnan(t) ) {
     Serial.println(F("Failed to read from DHT sensor!"));
     return;
   }
if((currentMillis-previousMillis)>= interval){
myFile = SD.open("SaveValu.txt", FILE_WRITE); 
  if (myFile) {
    if((nubled-ledjj)>= ledonoff){
     digitalWrite(led,!digitalRead(led));
     digitalWrite(led,!digitalRead(led));
       ledjj = millis();
    }//millis
    myFile.println("TEMP: "+String(t)+" °C , HUM: "+String(h)+("%")); // สั่งให้เขียนข้อมูล
    myFile.close();
  } 
  else {
    tone(8, 262, 250);
    Serial.println("error opening test.txt");
  }
   myFile = SD.open("SaveValu.txt"); 
  if (myFile) {
    if((nubled-ledjj)>= ledonoff){
     digitalWrite(led,!digitalRead(led));
     digitalWrite(led,!digitalRead(led));
       ledjj = millis();
    }  
    while (myFile.available()) {
    Serial.write(myFile.read());
    }
    myFile.close(); 
  }
   else { 
    tone(8, 222, 222);
    Serial.println("error opening test.txt");
  }
    previousMillis = millis();   
     }
};