Contador para Embreagem V1.3

 /*Wilson 24/06/2020

  V1.3 - Versão Draft para incluir mensagem de erro de gravação no display e retorno
  V2.7.6 - umidade e temperatura no cartão e via Bluetooth app Serialize Luminosidade
  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
  Colocando somente informação de umidade, temperatura e luminosidade no display
  Retirando os decimais dos valores de DT11
  Retirando a bilbioteca SPI
  Inserindo contador para embreagem (com Bounce)
  Enxugando para agilizar a aquisição
  Inclusão caracter de graus "°"
*/

#include <Bounce.h> // Biblioteca para evitar o repique do interruptor
//#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,
};

//Interruptor de contagem na embreagem
int interruptPin = 18;
int ledPin = 13;
int x = 0;
int ledValue = LOW; //teste de acionamento
Bounce bouncer = Bounce(interruptPin, 5); //5 ms para evitar o repique

//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() {

  //inicialização serial
    //serial1.begin(9600);
    Serial.begin(9600);

  //Botão de acionamento embreagem
    pinMode(ledPin, OUTPUT);
    pinMode(interruptPin, INPUT_PULLUP);
   
  // 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
       
  //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);
       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[] = "LOGGER00.TXT";
       for (uint8_t i = 0; i < 1000; i++) {
         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);
          lcd.clear();
          lcd.setCursor(0, 0);
          lcd.print("*OPEN FAIL FILE ON*");
          lcd.setCursor(3, 1);
          lcd.print("* SD CARD *");
          }
          Serial.print("Logging to: ");
          Serial.println(filename);
/*
  //Relógio RTC
    if (! rtc.begin()) {
      Serial.println("Couldn't find RTC");
      while (1);
      }
    if (! rtc.isrunning()) {
      Serial.println("RTC is NOT running!");
         
    // 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, 5, 20, 9, 10, 0));

      }
*/

}

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

  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);


  //Acionamento da contagem na embreagem
    if (bouncer.update() && bouncer.read() == LOW)
       {
           ledValue = ! ledValue;
           digitalWrite(ledPin, ledValue);
            x++;
           Serial.println(x);
          //Para gravar no SD - só grava quando conta
            logfile.print("Embreagem: ");
            logfile.print(",");
            logfile.print(x);
            logfile.print(",");
            logfile.print("Umidade: ");
            logfile.print(",");
            //logfile.print(DHT.humidity);
            logfile.print(umi);
            logfile.print(",");
            logfile.print("Temperatura: ");
            logfile.print(",");
            //logfile.print(DHT.temperature);
            logfile.print(tempe);
            logfile.print(",");
            logfile.print("Lum: ");
            logfile.print(",");
            logfile.print(sensorValue);
            logfile.println();
       }
/*  
  char caracter;
  DateTime now = rtc.now();
*/
   
  //lcd.print(millis() / 1000);

  //LCD página 1  
      lcd.clear();
      lcd.setCursor(2, 0);
      //lcd.print(now.hour(), DEC);
      lcd.print("EMBREAGEM:");
      //lcd.print(now.minute(), DEC);
      //lcd.print(":");
      //lcd.print(now.second(), DEC);
      //lcd.print(" <> ");
      lcd.print(x);
      //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((DHT.humidity));
      lcd.print(umi);
      lcd.print("% ");
      //lcd.print((DHT.temperature));
      lcd.print(tempe);
      lcd.print("C");
      lcd.write(7); // Writes a character to the LCD
      lcd.print(" ");
      lcd.print("L:");      
      lcd.print(sensorValue);
     // lcd.print("");
     delay(200);
  /*  
  //LCD página 2  
      lcd.setCursor(0, 0);
      lcd.clear();
      lcd.print("T1 ");
      lcd.print("111   ");
      lcd.print("T2 ");
      lcd.print("222 ");
      lcd.setCursor(0, 1);
      lcd.print("T3 ");
      lcd.print("333   ");
      lcd.print("T4 ");
      lcd.print("444 ");
      delay(500);
 
  */
  //Luminosidade
    sensorValue = (analogRead(pinSensor))/1;
 /*
  //Para enviar via bluetooth
      // Simulando senoidal para teste gráfico, para enviar ao app do celular
      //for (float x = -2 * PI; x <= 2 * PI; x = x + PI / 50) {
      serial1.print(graphTag);
      //serial1.print(24 * sin(x));
      //serial1.print(now.second(), DEC);
      serial1.print(sensorValue);
      //serial1.print(A14);
      serial1.print(valueSeparatorCharacter);
      serial1.print(now.minute(), DEC);
      serial1.print(valueSeparatorCharacter);
      serial1.print(DHT.humidity);
      //serial1.print(24 * sin(x + (2 * PI / 3)));
      serial1.print(valueSeparatorCharacter);
      serial1.print(DHT.temperature);
      //serial1.print(24 * sin(x + (4 * PI / 3)));
      serial1.print(terminationSeparatorCharacter);
      //}
 
  DHT.read11(A14); // chama método de leitura da classe dht,pino A14
                         
    //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();
       //logfile.print(m/1000);           // milliseconds since start
       //logfile.print(", ");    
 /*
   //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(" (");
      //Serial.print(daysOfTheWeek[now.dayOfTheWeek()]);
      //Serial.print(") ");
      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(DHT.humidity);
      Serial.print(" , ");
      Serial.print(DHT.temperature);
      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(" (");
      //logfile.print(daysOfTheWeek[now.dayOfTheWeek()]);
      //logfile.print(") ");
     // logfile.print(" , ");
     // logfile.print(now.hour(), DEC);
     // logfile.print(':');
     // logfile.print(now.minute(), DEC);
     // logfile.print(':');
     // logfile.print(now.second(), DEC);
      logfile.print("Embreagem: ");
      logfile.print(" , ");
      logfile.print(x);
      //logfile.print(DHT.humidity);
      //logfile.print(" , ");
      logfile.print("Luminosidade: ");
      //logfile.print(DHT.temperature);
      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