#include <Arduino.h>
/*
IES "Giner de los Ríos" León
  dpto. de electrónica

                      *************************
                            LIBRERÍAS
                      *************************

  - Driver CHT8305C
  - Sensor de tempertura y humedad
   
   hardware: CHT8305C
  
  V. 14/05/2024
 */

#include "CHT8305C.h"

//      - VARIABLES Y CONSTANTES GLOBALES -

//      - INSTANCIAS -

CHT8305C sensor(0x40);                // instanciar objeto sensor de la clase CHT8305C 

//      - DECLARACIÓN DE FUNCIONES -

bool temporizador(unsigned int);      // tiempo entre lecturas

//      - INICIALIZACIÓN -

void setup() {

 Serial.begin(115200);
  Wire.begin();                       // Inicializar I2C modo maestro
  Wire.setClock(400000);              // frecuencia scl I2C 400KHz
  delay(100);
      sensor.calentador(false);
}

//      - PROGRAMA PRINCIPAL -

void loop() {
  if (temporizador(2000)) {            // 2 seg
    Serial.println("temperatura: " + String(sensor.leer_temperatura(), 3) + "°C"); // Imprimir valor del sensor
    Serial.println("humedad:     " + String(sensor.leer_humedad(), 3) + "%");
   }

//    ... resto del programa   
}

//             - FUNCIONES -

          /**************************************
          *   Consulta del tiempo transcurrido
          ***************************************/

bool temporizador(unsigned int delta_ms){

 static bool dt_ms = false;                       // bandera de tiempo
 static unsigned long tiempo_anterior = 0;
 unsigned long tiempo_actual = millis();          // leer tiempo actual
 
  if(tiempo_actual - tiempo_anterior > delta_ms){
     tiempo_anterior = tiempo_actual;             // actualizar tiempos
    dt_ms = true;                                 // tiempo delta transcurrió
  }
   else{
    dt_ms = false;                                // aún no ha transcurrido
   }

  return dt_ms;
}