//███████████████████████████████████████████████████████████████
//████████ LIBRERIAS NECESARIAS ██████████████████████████████████████████
//███████████████████████████████████████████████████████████████
#include <OneWire.h>
#include <Wire.h>
#define DS1307_I2C_ADDRESS 0x68
//███████████████████████████████████████████████████████████████
//████████ VARIABLES GENERICAS PARA TODO █████████████████████████████████████
//███████████████████████████████████████████████████████████████
byte second, minute, hour, dayOfWeek, dayOfMonth, month, year; //variables necesarias para la fecha y hora usadas en varias funciones
//███████████████████████████████████████████████████████████████
//████████ TEMPERATURA ███████████████████████████████████████████████
//███████████████████████████████████████████████████████████████
OneWire ds(11); // PIN CONEXION SENSORES TEMPERATURA
//███████████████████████████████████████████████████████████████
//████████ CALCULOS PARA LA FECHA Y LA HORA ███████████████████████████████████
//███████████████████████████████████████████████████████████████
byte decToBcd(byte val)
{
return ( (val/10*16) + (val%10) );
}
byte bcdToDec(byte val)// Convierte BCD (binario decimal codificado) a números normales decimales
{
return ( (val/16*10) + (val%16) );
}
void setDateDs1307(byte second, // 0-59
byte minute, // 0-59
byte hour, // 1-23
byte dayOfWeek, // 1-7
byte dayOfMonth, // 1-28/29/30/31
byte month, // 1-12
byte year) // 0-99
{
Wire.beginTransmission(DS1307_I2C_ADDRESS);
Wire.write(0);
Wire.write(decToBcd(second)); // 0 a bit 7 inicia el reloj
Wire.write(decToBcd(minute));
Wire.write(decToBcd(hour)); // Si usted quiere 12 hora am/pm usted tiene que poner el
// bit 6 (tambien tiene que cambiar readDateDs1307)
Wire.write(decToBcd(dayOfWeek));
Wire.write(decToBcd(dayOfMonth));
Wire.write(decToBcd(month));
Wire.write(decToBcd(year));
Wire.endTransmission();
}
// Establece la fecha y el tiempo del ds1307
void getDateDs1307(byte *second,
byte *minute,
byte *hour,
byte *dayOfWeek,
byte *dayOfMonth,
byte *month,
byte *year)
{
// Resetea el registro puntero
Wire.beginTransmission(DS1307_I2C_ADDRESS);
Wire.write(0);
Wire.endTransmission();
Wire.requestFrom(DS1307_I2C_ADDRESS, 7);
// Alguno de estos necesitan enmascarar porque ciertos bits son bits de control
*second = bcdToDec(Wire.read() & 0x7f);
*minute = bcdToDec(Wire.read());
*hour = bcdToDec(Wire.read() & 0x3f); // Need to change this if 12 hour am/pm
*dayOfWeek = bcdToDec(Wire.read());
*dayOfMonth = bcdToDec(Wire.read());
*month = bcdToDec(Wire.read());
*year = bcdToDec(Wire.read());
}
//███████████████████████████████████████████████████████████████
//████████ ILUMINACION ████ por OSCAR, krop en wwww.todomarino.com ████████████████████
//███████████████████████████████████████████████████████████████
//ESTABLECEMOS LOS PINS DE CADA CANAL LED
byte led20 = 2; // Pin digital PWM
byte led460 = 3; // Pin digital PWM
byte led450 = 4; // Pin digital PWM
byte led15 = 5; // Pin digital PWM
byte led65 = 6; // Pin digital PWM
byte ledcyan = 7; // Pin digital PWM
byte ledvioleta = 8; // Pin digital PWM
byte ledocw = 9; // Pin digital PWM
//███████████████████████████████████████████████████████████████
//████████ DEFINICION DE LAS HORAS Y LAS POTENCIAS ███████████████████████████████
//███████████████████████████████████████████████████████████████
/*
He pensado que haya una hora de mediodia, y una amplitud en horas
de manera que, por ejemplo si son 6 horas la amplitud y las 17 horas
el medio dia entonces empieze a amanecer desde las 11 (17-6), poco a poco
hasta el maximo de luz. He creado otra contante que se puede cambiar
hsubida (horas de subida), que son las horas que le tiene que costar
alcanzar el maximo de luz. En la funcion hace calculos para saber
que porcentaje de tiempo de subida y bajada ha transcurrido, por eso
todos los valores son float.
En cada interaccion calcula un pwmteorico, pwm que deberia ser, que pasado
el tiempo de subida es mayor que pwmmax, contante que ponemos como
maximo valor de pwm, en este caso pwm es simplemente pwmmax, o sea,
si calcula pwmteorico de 400, lo deja en pwmmax como mucho 255
Pasado el medio dia a pwmteorico le sumo pwmluna, que sera lo que
definamos somo pwm para luz de luna. Despues, en tiempo luna pwm es
ese valor.
Ademas con esta funcion si la luna empieza antes de las 00 horas
y termina despues no hay ningun problema. ya que todos los calculos
los hago pasando las horas establecidadas a minutos.
Por otra parte si reiniciamos el arduino siempre pondra la luz que
corresponda al minuto concreto del dia en que estamos.
*/
float hmediodia= 17; // hora que establecemos como medio dia
float hluna=7; // numero de horas de luna
float hamplitud= 6; //horas de amplitud del dia, hmediodia-hamplitud es el momento de amanecer
float pwmmax = 200; //pwm maximo para los canales de luz
float mmediodia = hmediodia*60; //calcula el minuto del medio dia ejemplo 17*60
float mluna = hluna * 60; //minutos que dura la fase de luna
float mamplitud = hamplitud*60; //minutos que duara "amplitud"
float msubida = mamplitud / 2; //minutos que cuesta pasar de pwm=0 hasta pwm=pwmmax
float mfin = mmediodia + mamplitud; //minuto a partir del cual solo queda luz luna
float minicio = mmediodia - mamplitud; //minuto del dia en el que amanece
float pwmteorico = 0; //pwm teorico que calcula en cada minuto, puede ser mayor que 255
float pwm=0; //variable que en la que guardara pwm en cada minuto
float mactual=0; //variable en la que guardara en minuto actual del dia
float pwmluna=200; //pwm que establezcamos para periodo luna
//███████████████████████████████████████████████████████████████
//█████████ SETUP ████████████ SETUP ██████████ SETUP ████████████████████
//███████████████████████████████████████████████████████████████
void setup()
{
Wire.begin();
Serial.begin(9600);
//███████████████████████████████████████████████████████████████
//████████ SOLO PARA PONER RELOJ EN HORA LUEGO QUITAR O DESACTIVAR DENTRO DEL SETUP ████████████
//███████████████████████████████████████████████████████████████
// Cambie estos valores a los que usted quiere poner su reloj.
/*
second = 00;
minute = 51;
hour = 10;
dayOfWeek = 3;
dayOfMonth = 11;
month = 9;
year = 13;
setDateDs1307(second, minute, hour, dayOfWeek, dayOfMonth, month, year);
*/
}
//███████████████████████████████████████████████████████████████
//█████████ VOID LOOP ████████████ VOID LOOP ██████████ VOID LOOP █████████████
//███████████████████████████████████████████████████████████████
void loop()
{
luz();// ejecuta la funcion luz que esta definida mas abajo
muestrahoraEnmonitor(); //muestra en monitor Serial la fecha, lo uso para comprobar que la hora la lee bien definido mas abajo
delay(1000);
//███████████████████████████████████████████████████████████████
//████████ PROGRAMA BUSQUEDA DE SENSORES DE TEMPERATURA Y MEDICION RESOLUCION 0.5ºC ████████████
//███████████████████████████████████████████████████████████████
byte i;
byte present = 0;
byte type_s;
byte data[12];
byte addr[8];
float celsius;
int iNSensors=0;
while(ds.search(addr))
{
iNSensors++;
Serial.print("ROM =");
for( i = 0; i < 8; i++) {
Serial.write(' ');
if(addr<16)
Serial.print(0);
Serial.print(addr, HEX);
}
if (OneWire::crc8(addr, 7) != addr[7]) {
Serial.println("CRC is not valid!");
return;
}
// the first ROM byte indicates which chip
switch (addr[0]) {
case 0x10:
Serial.print(": DS18S20 "); // or old DS1820
type_s = 1;
break;
case 0x28:
Serial.print(": DS18B20 ");
type_s = 0;
break;
case 0x22:
Serial.print(": DS1822 ");
type_s = 0;
break;
default:
Serial.println("Device is not a DS18x20 family device.");
return;
}
ds.reset();
ds.select(addr);
ds.write(0x44,1); // start conversion, with parasite power on at the end
delay(700); // maybe 750ms is enough, maybe not
// we might do a ds.depower() here, but the reset will take care of it.
present = ds.reset();
ds.select(addr);
ds.write(0xBE); // Read Scratchpad
for ( i = 0; i < 9; i++)
data = ds.read();
// convert the data to actual temperature
unsigned int raw = (data[1] << 8) | data[0];
if (type_s) {
raw = raw << 3; // 9 bit resolution default
if (data[7] == 0x10) {
// count remain gives full 12 bit resolution
raw = (raw & 0xFFF0) + 12 - data[6];
}
} else {
byte cfg = (data[4] & 0x60);
if (cfg == 0x00) raw = raw << 3; // 9 bit resolution, 93.75 ms
else if (cfg == 0x20) raw = raw << 2; // 10 bit res, 187.5 ms
else if (cfg == 0x40) raw = raw << 1; // 11 bit res, 375 ms
// default is 12 bit resolution, 750 ms conversion time
}
celsius = (float)raw / 16.0;
Serial.print(celsius);
Serial.println(" C");
}
Serial.print(iNSensors);
Serial.println(" sensors.\n");
ds.reset_search();
delay(250);
}
//███████████████████████████████████████████████████████████████
//████████ PROGRAMA LUZ ███████████████████████████████████████████████
//███████████████████████████████████████████████████████████████
void luz ()
{
getDateDs1307(&second, &minute, &hour, &dayOfWeek, &dayOfMonth, &month, &year);
pwmteorico=0; //establece pwmteorico a 0
mactual = hour *60 + minute; //calcula el minuto actual
//si es despues de amanecer y antes de medio dia
if(mactual > minicio && mactual <= mmediodia){
pwmteorico=(mactual-minicio)/msubida*pwmmax; //calcula la proporcion de minutos subbida consumida
//y lo multiplica por pwmmax para calcula pwmteorico que puede ser mayor de 255
}
//si es despues de medio dia y antes de anochecer
if(mactual>mmediodia && mactual <= mfin){//calcula la proporcion de minutos ha bajado hasta anochcer consumida
pwmteorico=((mfin-mactual)/msubida*pwmmax)+pwmluna; //y lo multiplica por pwmmax para calcula pwmteorico que puede ser mayor de 255
}
// si estamos en los minutos de luz de luna deja pwm con el valor que hemos establecido para pwmluna
if(mactual > mfin && mactual <= (mfin + mluna) ){
pwmteorico=pwmluna;
}
if(mactual+1440 < mfin+mluna){
pwmteorico=pwmluna;
}
//si en algun momento hemos dejado pwmteorico por encima de pwmmax deja pwm con el la constante que hemos dejado como pwmmax y si no con el que ha calculado
if(pwmteorico>=pwmmax){
pwm = pwmmax;
}
else{
pwm=pwmteorico;
}
float tluna=(hour*60)+minute;
if(mactual > mfin && mactual <= (mfin + mluna) && tluna >=0 ){
// COMPRUEBA QUE SEA ENTRE EL FIN DEL ATARDECER Y ANTES DE LAS 00:00 Y ESCRIBE LA POTENCIA DE LA
// LUNA SOLO EN EL CANAL 450, EL RESTO LO ESCRIBO A 0, ES DECIR APAGADO
pwm=pwmluna;
analogWrite (led20,0);
analogWrite (led460,0);
analogWrite (led450,pwm);
analogWrite (led15,0);
analogWrite (led65,0);
analogWrite (ledcyan,0);
analogWrite (ledvioleta,0);
analogWrite (ledocw,0);
}
else if (tluna >=0 && tluna < minicio) {
// COMPRUEBA QUE SEA PASADA LAS 00:00 Y ANTES DEL AMANECER Y ESCRIBE LA POTENCIA DE LA
// LUNA SOLO EN EL CANAL 450, EL RESTO LO ESCRIBO A 0, ES DECIR APAGADO
pwm=pwmluna;
analogWrite (led20,0);
analogWrite (led460,0);
analogWrite (led450,pwm);
analogWrite (led15,0);
analogWrite (led65,0);
analogWrite (ledcyan,0);
analogWrite (ledvioleta,0);
analogWrite (ledocw,0);
}
else{ //SI NO SE CUMPLE LAS 2 SENTENCIAS ANTERIORES, EJECUTA ESTA Y ESCRIBE LA POTENCIA PWM EN TODOS LOS CANALES
analogWrite (led20,pwm);
analogWrite (led460,pwm);
analogWrite (led450,pwm);
analogWrite (led15,pwm);
analogWrite (led65,pwm);
analogWrite (ledcyan,pwm);
analogWrite (ledvioleta,pwm);
analogWrite (ledocw,pwm);
}
}
//███████████████████████████████████████████████████████████████
//████████ PROGRAMA PARA MOSTRAR FECHA Y HORA Y POTENCIA ACTUAL ███████████████████████
//███████████████████████████████████████████████████████████████
void muestrahoraEnmonitor()
{
getDateDs1307(&second, &minute, &hour, &dayOfWeek, &dayOfMonth, &month, &year);
if (dayOfMonth < 10) Serial.print("0");
Serial.print(dayOfMonth, DEC);
Serial.print("/");
if (month < 10) Serial.print("0");
Serial.print(month, DEC);
Serial.print("/");
Serial.print("20");
if (year < 10) Serial.print("0");
Serial.print(year, DEC);
Serial.print(" ");
if (hour < 10) Serial.print("0");
Serial.print(hour, DEC);
Serial.print(":");
if (minute < 10) Serial.print("0");
Serial.print(minute, DEC);
Serial.print(":");
if (second < 10) Serial.print("0");
Serial.print(second, DEC);
Serial.print(" Dia de la semana:");
switch (dayOfWeek) // Esto pone nombre del dia
{
case 1:
Serial.print(" Lunes"); break;
case 2:
Serial.print(" Martes"); break;
case 3:
Serial.print(" Miercoles"); break;
case 4:
Serial.print(" Jueves"); break;
case 5:
Serial.print(" Viernes"); break;
case 6:
Serial.print(" Sabado"); break;
case 7:
Serial.print(" Domingo"); break;
}
Serial.print(" Potencia leds:");
Serial.print(pwm);
Serial.print(" ");
Serial.print(pwm*0.3921);
Serial.println("%");
}