Modulo de Tiempo DS3231

Buenas!!!

Estoy utilizando un Arduino ATmega 2560 con un modulo de tiempo el DS3231 (https://datasheets.maximintegrated.com/en/ds/DS3231.pdf ), con este modulo logro guardar la hora y puedo leerla en el puerto serial; Pero también necesito generar una alarma con la cual pueda encender un puerto por un tiempo determinado, mediante este modulo.

Les adjunto el código que estoy utilizando...

#include "Wire.h"
#define DS3231_I2C_ADDRESS 0x68

const int minute = minutos;

// Convert normal decimal numbers to binary coded decimal
byte decToBcd(byte val)
{
  return( (val/10*16) + (val%10) );
}
// Convert binary coded decimal to normal decimal numbers
byte bcdToDec(byte val)
{
  return( (val/16*10) + (val%16) );
  
}
   
void setup()
{
 Wire.begin();
  Serial.begin(9600);
    // set the initial time here:
  // DS3231 seconds, minutes, hours, day, date, month, year
 // setDS3231time(30,35,14,2,13,03,17);
 
 }


void setDS3231time(byte second, byte minute, byte hour, byte dayOfWeek, byte
dayOfMonth, byte month, byte year)
{
  // sets time and date data to DS3231
  Wire.beginTransmission(DS3231_I2C_ADDRESS);
  Wire.write(0); // set next input to start at the seconds register
  Wire.write(decToBcd(second)); // set seconds
  Wire.write(decToBcd(minute)); // set minutes
  Wire.write(decToBcd(hour)); // set hours
  Wire.write(decToBcd(dayOfWeek)); // set day of week (1=Sunday, 7=Saturday)
  Wire.write(decToBcd(dayOfMonth)); // set date (1 to 31)
  Wire.write(decToBcd(month)); // set month
  Wire.write(decToBcd(year)); // set year (0 to 99)
  Wire.endTransmission();
}
void readDS3231time(
  byte *second,
  byte *minute,
  byte *hour,
  byte *dayOfWeek,
  byte *dayOfMonth,
  byte *month,
  byte *year)
{
  Wire.beginTransmission(DS3231_I2C_ADDRESS);
  Wire.write(0); // set DS3231 register pointer to 00h
  Wire.endTransmission();
  Wire.requestFrom(DS3231_I2C_ADDRESS, 7);
  // request seven bytes of data from DS3231 starting from register 00h
  *second = bcdToDec(Wire.read() & 0x7f);
  *minute = bcdToDec(Wire.read());
  *hour = bcdToDec(Wire.read() & 0x3f);
  *dayOfWeek = bcdToDec(Wire.read());
  *dayOfMonth = bcdToDec(Wire.read());
  *month = bcdToDec(Wire.read());
  *year = bcdToDec(Wire.read());
}
void displayTime()
{
  byte second, minute, hour, dayOfWeek, dayOfMonth, month, year;
  // retrieve data from DS3231
  readDS3231time(&second, &minute, &hour, &dayOfWeek, &dayOfMonth, &month,
  &year);
  // send it to the serial monitor
  Serial.print(hour, DEC);
  // convert the byte variable to a decimal number when displayed
  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(" ");
  Serial.print(dayOfMonth, DEC);
  Serial.print("/");
  Serial.print(month, DEC);
  Serial.print("/");
  Serial.print(year, DEC);
  Serial.print(" Dia de la Semana: ");
  switch(dayOfWeek){
  case 1:
    Serial.println("Domingo");
    break;
  case 2:
    Serial.println("Lunes");
    break;
  case 3:
    Serial.println("Martes");
    break;
  case 4:
    Serial.println("Mierdoles");
    break;
  case 5:
    Serial.println("Jueves");
    break;
  case 6:
    Serial.println("Viernes");
    break;
  case 7:
    Serial.println("Sabado");
    break;
  }
}


void loop()
{
  
  displayTime(); // display the real-time clock data on the Serial Monitor,
  delay(1000); // every second
}

:RE :RE :RE :RE :RE :wink:

Porque no usas las librerías existentes?

Time y TimeAlarms

Ejemplo

/*
 * TimeAlarmExample.pde
 *
 * This example calls alarm functions at 8:30 am and at 5:45 pm (17:45)
 * and simulates turning lights on at night and off in the morning
 * A weekly timer is set for Saturdays at 8:30:30
 *
 * A timer is called every 15 seconds
 * Another timer is called once only after 10 seconds
 *
 * At startup the time is set to Jan 1 2011  8:29 am
 */
 
#include <Time.h>
#include <TimeAlarms.h>

void setup()
{
  Serial.begin(9600);
  setTime(8,29,0,1,1,11); // set time to Saturday 8:29:00am Jan 1 2011
  // create the alarms 
  Alarm.alarmRepeat(8,30,0, MorningAlarm);  // 8:30am every day
  Alarm.alarmRepeat(17,45,0,EveningAlarm);  // 5:45pm every day 
  Alarm.alarmRepeat(dowSaturday,8,30,30,WeeklyAlarm);  // 8:30:30 every Saturday 

 
  Alarm.timerRepeat(15, Repeats);            // timer for every 15 seconds    
  Alarm.timerOnce(10, OnceOnly);             // called once after 10 seconds 
}

void  loop(){  
  digitalClockDisplay();
  Alarm.delay(1000); // wait one second between clock display
}

// functions to be called when an alarm triggers:
void MorningAlarm(){
  Serial.println("Alarm: - turn lights off");    
}

void EveningAlarm(){
  Serial.println("Alarm: - turn lights on");           
}

void WeeklyAlarm(){
  Serial.println("Alarm: - its Monday Morning");      
}

void ExplicitAlarm(){
  Serial.println("Alarm: - this triggers only at the given date and time");       
}

void Repeats(){
  Serial.println("15 second timer");         
}

void OnceOnly(){
  Serial.println("This timer only triggers once");  
}

void digitalClockDisplay()
{
  // digital clock display of the time
  Serial.print(hour());
  printDigits(minute());
  printDigits(second());
  Serial.println(); 
}

void printDigits(int digits)
{
  Serial.print(":");
  if(digits < 10)
    Serial.print('0');
  Serial.print(digits);
}

Solo debes agregar lo necesario para que la hora sea leida desde el RTC y sincronizarla cada cierto tiempo para evitar problemas.

Prueba con estas librerías a ver si te sirven.

Buenas !!!!

Excelente código yo tenia un problema similar, pero una consulta con el código que pones cuando se abre el puerto serial se reinicia el reloj, he estado cambiando la progra pero no logro quitar el set del reloj, ya que mi idea es implementarlo en una alarma de colegio y no se debe perder la hora

surbyte muchas gracias por tu comentario probé el código y funciona muy bien a como yo lo ocupo, el problema que encontré es que cada vez que abro el puerto serial la hora se reinicia lo cual me ocasiona problemas porque se desajusta la hora.

En el código que publique inicial mente puedo grabar la hora la primera vez y después lo grabo por segunda ocasion pero con esta linea // setDS3231time(30,35,14,2,13,03,17); como comentario entonces la hora queda guardada y no importa si desconecto el modulo, la hora siempre queda guardada.

Lo que necesito es aplicar el tipo de alarma que muestras en el código que facilitaste en el código que yo mostré al inicio, he intentado de diversas formas y utilizando las librerías que mostraste pero la alarma no se activa.

al final lo que quiero hacer con el proyecto es mostrar un dato obtenido por un sensor a cierta hora determinada o activar diferentes dispositivos, pero lo el problema es al tomar la hora de muestra para que estas funciones se activen que es lo que no he podido lograr... si pudieras ayudar te lo agradecería mucho.
:grinning:

Vaya gente, hay que trabajar un poco.
El código es un ejemplo.
La hora que pone la fija pero pueden usar un RTC.
Luego les pongo como se hace.

En el setup agregan esto

void setup(){
  Serial.begin(9600);
  setTime(8,29,0,1,1,11); // set time to Saturday 8:29:00am Jan 1 2011

  setSyncProvider(RTC.get);   // the function to get the time from the RTC
  setSyncInterval(600);
  if (timeStatus() != timeSet) 
      Serial.println("No pude sincronizarme con el RTC");
   else
      Serial.println("RTC ha fijado el tiempo del sistema"); 
  RTC.read(tm);                     //No it didn't, set the clock from this code

  // create the alarms 
  Alarm.alarmRepeat(8,30,0, MorningAlarm);  // 8:30am every day
  Alarm.alarmRepeat(17,45,0,EveningAlarm);  // 5:45pm every day 
  Alarm.alarmRepeat(dowSaturday,8,30,30,WeeklyAlarm);  // 8:30:30 every Saturday 

 
  Alarm.timerRepeat(15, Repeats);            // timer for every 15 seconds    
  Alarm.timerOnce(10, OnceOnly);             // called once after 10 seconds 
}

En mi caso, una alarma para una empresa que le debe avisar a sus empleados cuando comenzar a trabajar, cuando puede descansar, cuando volver al trabajo, etc etc, similar a una alarma de colegio lo que hice fue crear

Alarm.alarmRepeat(horaON, funcionON);
Alarm.alarmRepeat(horaOFF, funcionOFF);

funcionON activa la sirena y funcionOFF la apaga. Le di 10 segundos entre una y otra entonces si debe sonar 7AM uso

Alarm.alarmRepeat(7,0,0, funcionON);
Alarm.alarmRepeat(7,0,10, funcionOFF);

1 activa y otra desactiva. la duración la fijan Uds.

Para probar si todo funciona hagan esto.
pongan en lugar de Alarm.delay(1000) un Alarm.delay(1) y el sistema volará y pueden probar todo el dia de toda la semana.
Y lo ven por monitor Serie.