Umidade e Temperatura V3.3 - 2020

 /*Wilson 29/06/2020

  V3.3 - umidade e temperatura no cartão e via Bluetooth app Serialize Luminosidade
  Funciona no Arduino IDE 1.8.12
  Alimentando DHT11 pelo canal analógico
  Enviando informação via bluetooth  https://www.youtube.com/watch?v=Zl3IvfNaafA
  https://www.instructables.com/id/Plotting-Real-time-Graph-on-Android-From-Arduino-T/
  Mesclando com Umidade e Temperatura com RTC v0.3
  Inserindo o RTC: https://learn.adafruit.com/adafruit-shield-compatibility/data-logging-shield-assembled
  https://www.youtube.com/watch?time_continue=62&v=xT3fjSvhrU4&feature=emb_logo
  Necessário retirar A4 e A5 e conectar com cabos A5 - SCL 21 e A4 - SDA 20
  Colocando quatro canais para o app
  Adcionando luminosidade: https://www.youtube.com/brincandocomideias ; https://cursodearduino.net/
  Adicionando LCD :  http://www.arduino.cc/en/Tutorial/LiquidCrystalHelloWorld
  Adicionando Aviso de erro de leitura no cartão com condicional:  http://www.arduino.cc/en/Tutorial/IfStatement
  Comparando com a versão V2.7.1 e V1.3 do Contador para embreagem
  Enxugando a V3.1
  Colocando o nome do arquivo no LCD e inserindo tempo início de aquisição
*/

#include "RTClib.h" //biblioteca do RTC
#include <SoftwareSerial.h> // biblioteca para bluetooth
//#include <SPI.h> // biblioteca comunicação serial
#include <SD.h> // biblioteca cartão SD
#include <dht.h> // biblioteca sensor umidade e temp
#include <LiquidCrystal.h> // biblioteca LCD

// Array of bytes - caracter especial
byte slash[8]= {
  B01100,  // B stands for binary formatter and the 5 numbers are the pixels
  B10010,
  B01100,
  B00000,
  B00000,
  B00000,
  B00000,
  B00000,
};

//Variável para o Led de erro
 const int lederroPin = 45;      
 
//Initialize the library by associating any needed LCD interface pin with the arduino pin number it is connected to
  const int rs = 7, en = 6, d4 = 5, d5 = 4, d6 = 3, d7 = 2;
  LiquidCrystal lcd(rs, en, d4, d5, d6, d7);

//RTC
  RTC_DS1307 rtc;
  char daysOfTheWeek[7][12] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};

//Bluetooth
  SoftwareSerial serial1(31, 33); // RX, TX
  // Used to identify graphing values on app Serialize
     String graphTag = "Graph:";
  // Used to identify the separation of values inside the stream
     char valueSeparatorCharacter = '&';
  // Used to identify the end of the stream. This will apply for both the serial monitor and graph
     char terminationSeparatorCharacter = '$';

//DHT sensor - temperature and humidity
  dht DHT;
  uint32_t timer = 0;
  const int chipSelect = 10;

//LDR sensor - luminosidade
  int sensorValue = 0;  // variable to store the value coming from the sensor
  #define pinSensor A8 //

//Millis time base ms
// **** É necessário pelo menos 1000 (1s) para que haja sincronismo com o app Serialize  
   #define LOG_INTERVAL  1000 // mills between entries (reduce to take more/faster data)

// how many milliseconds before writing the logged data permanently to disk
// set it to the LOG_INTERVAL to write each time (safest)
// set it to 10*LOG_INTERVAL to write all data every 10 datareads, you could lose up to
// the last 10 reads if power is lost but it uses less power and is much faster!
   #define SYNC_INTERVAL 1000 // mills between calls to flush() - to write data to the card
   uint32_t syncTime = 0; // time of last sync()
   //#define ECHO_TO_SERIAL   1 // echo data to serial port
   //#define WAIT_TO_START    0 // Wait for serial input in setup()

//Abertura arquivo no SD
  File logfile;

void error(char *str)  {
  Serial.print("error: ");
  Serial.println(str);
 
  while(1);
  }

//============================================================
void setup() {

  // Inicializando Led de erro 45, para aviso de cartão com erro
    pinMode(lederroPin, OUTPUT);
 
  // set up the LCD's number of columns and rows:
    lcd.begin(16, 2); //4 linhas por causa dos menus
     //lcd.print("VAI QUEBRAR!!");
    lcd.createChar(7, slash); // Create a custom character for use on the LCD. Up to eight characters of 5x8 pixels are supported
 
  //Luminosidade LDR
    pinMode (A11, OUTPUT); // LDR VCC
    pinMode (A10, OUTPUT); // LDR GND
    digitalWrite (A11, HIGH); // LDR tensão
    digitalWrite (A10, LOW); // LDR Terra
    pinMode(pinSensor,INPUT); //Sinal do LDR
       
  //inicialização serial
    serial1.begin(9600);
    Serial.begin(9600);
 
  //Sensor temperatura e umidade
    pinMode (A15, OUTPUT); // DHT11 Vcc
    pinMode (A13, OUTPUT); // DHT11 GND
    digitalWrite (A15, HIGH); // Damos tensão
    digitalWrite (A13, LOW); // Dar nível 0
       
  //Cartão SD
    Serial.print("Initializing SD card...");
    pinMode(10, OUTPUT); //configuração para shield SD
   
    //see if the card is present and can be initialized:
      if (!SD.begin(10, 11, 12, 13)) {  
       Serial.println("Card failed, or not present");
       Serial.println("Led de erro aceso - falha de cartão SD");
       digitalWrite(lederroPin, HIGH);   // turn the LED on (HIGH is the voltage level)
       lcd.clear();
       lcd.setCursor(3, 0);
       lcd.print("* FAIL ON *");
       lcd.setCursor(3, 1);
       lcd.print("* SD CARD *");
       while (1) ;
       }
       
       Serial.println("card initialized.");
    // create a new file sequencial
       char filename[] = "FILE0000.TXT";
       for (uint8_t i = 0; i < 1000; i++) {
         filename[5] = i/100 + '0';
         filename[6] = i/10 + '0';
         filename[7] = i%10 + '0';
          if (! SD.exists(filename)) {
          // only open a new file if it doesn't exist
          logfile = SD.open(filename, FILE_WRITE);
          digitalWrite(lederroPin, LOW);    // turn the LED off by making the voltage LOW
          break;  // leave the loop!
          }
        }
          if (! logfile) {
            error("couldnt create file");
            Serial.println("Led de erro aceso - falha de arquivo");
            digitalWrite(lederroPin, HIGH);   // turn the LED on (HIGH is the voltage level)
            lcd.clear();
            lcd.setCursor(3, 0);
            lcd.print("* FAIL ON *");
            lcd.setCursor(3, 1);
            lcd.print("* SD CARD *");
          }
          Serial.print("Logging to: ");
          Serial.println(filename);
          lcd.clear();
          lcd.setCursor(3, 0);
          lcd.print("Logging to: ");
          lcd.setCursor(3, 1);
          lcd.print(filename);
          delay(2000);


  //Relógio RTC
    if (! rtc.begin()) {
      Serial.println("Couldn't find RTC");
      lcd.clear();
      lcd.setCursor(3, 0);
      lcd.print("* FAIL ON *");
      lcd.setCursor(7, 1);
      lcd.print("* RTC *");

      while (1);
      }
   
      if (! rtc.isrunning()) {
          Serial.println("RTC is NOT running!");
          lcd.clear();
          lcd.setCursor(3, 0);
          lcd.print("* FAIL ON *");
          lcd.setCursor(7, 1);
          lcd.print("* RTC *");
      }  

       
  // Ajuste data e hora - following line sets the RTC to the date & time this sketch was compiled
    //rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
  // This line sets the RTC with an explicit date & time, for example to set
  // January 21, 2014 at 3am you would call:
   // rtc.adjust(DateTime(2020, 12, 22, 14, 10, 0));
         
       
}

//===================================================================
void loop(){

  char caracter;
  DateTime now = rtc.now();

  DHT.read11(A14); // chama método de leitura da classe dht,pino A14

//Retirando os decimais dos valores de DT11
  int umi = (DHT.humidity);  
  int tempe = (DHT.temperature);
 
 
//lcd.print(millis() / 1000);
   
  //LCD página 1  
      lcd.setCursor(0, 0);
      lcd.clear();
      lcd.print(now.hour(), DEC);
      lcd.print(":");
      lcd.print(now.minute(), DEC);
      lcd.print(":");
      lcd.print(now.second(), DEC);
      lcd.print("><");
      lcd.print(now.day(), DEC);
      lcd.print("/");
      lcd.print(now.month(), DEC);
      lcd.print("/");
      lcd.print(now.year(), DEC);
      lcd.setCursor(1, 1);
      lcd.print(umi);
      lcd.print("% ");
      lcd.print(tempe);
      lcd.print("C");
      lcd.write(7); // Writes a character to the LCD
      lcd.print(" ");      
      lcd.print("Lum:");      
      lcd.print(sensorValue);
      lcd.print("");
      delay(500);
 
  //Luminosidade
    sensorValue = (analogRead(pinSensor))/10;
 
  //Para enviar via bluetooth
      serial1.print(graphTag);
      serial1.print(sensorValue);
      serial1.print(valueSeparatorCharacter);
      serial1.print(now.minute(), DEC);
      serial1.print(valueSeparatorCharacter);
      serial1.print(umi);
      serial1.print(valueSeparatorCharacter);
      serial1.print(tempe);
      serial1.print(terminationSeparatorCharacter);
 
    //delay for the amount of time we want between readings
       delay((LOG_INTERVAL -1) - (millis() % LOG_INTERVAL));
   
    //log milliseconds since starting
       uint32_t m = millis();
         
   //Para enviar via serial do computador
      Serial.print(m/1000);           // milliseconds since start
      Serial.print(" , ");    
      Serial.print(now.day(), DEC);
      Serial.print('/');
      Serial.print(now.month(), DEC);
      Serial.print('/');
      Serial.print(now.year(), DEC);
      //Serial.print(daysOfTheWeek[now.dayOfTheWeek()]);
      Serial.print(" , ");
      Serial.print(now.hour(), DEC);
      Serial.print(':');
      Serial.print(now.minute(), DEC);
      Serial.print(':');
      Serial.print(now.second(), DEC);
      Serial.print(" , ");
      Serial.print(umi);
      Serial.print(" , ");
      Serial.print(tempe);
      Serial.print(" , ");
      Serial.print(sensorValue);
      Serial.println();
 
  //Para gravar no SD
      logfile.print(m/1000);           // milliseconds since start
      logfile.print(" , ");
      logfile.print(now.day(), DEC);
      logfile.print('/');
      logfile.print(now.month(), DEC);
      logfile.print('/');
      logfile.print(now.year(), DEC);
      //logfile.print(daysOfTheWeek[now.dayOfTheWeek()]);
      logfile.print(" , ");
      logfile.print(now.hour(), DEC);
      logfile.print(':');
      logfile.print(now.minute(), DEC);
      logfile.print(':');
      logfile.print(now.second(), DEC);
      logfile.print(" , ");
      logfile.print(umi);
      logfile.print(" , ");
      logfile.print(tempe);
      logfile.print(" , ");
      logfile.print(sensorValue);
      logfile.println();
     
    //Now we write data to disk! Don't sync too often - requires 2048 bytes of I/O to SD card
    //which uses a bunch of power and takes time
      if ((millis() - syncTime) < SYNC_INTERVAL) return;
       syncTime = millis();
   
    //blink LED to show we are syncing data to the card & updating FAT!
      logfile.flush();

}

Comentários

Postagens mais visitadas