Reloj de tiempo real DS 1302

Hola a todos, estoy tratando de implementar un pequeño modulo de reloj basado en el chip DS1302, ya pude isar incluso una librería llamada virtualbotixRTC pero por más que busco, siempre me pide establecer el tiempo de salida, es decir:
Digamos que establezco mi tiempo inicial 14-05-14 a las 23:00
Ejecuto un ejemplo para que me de el tiempo por la consola serial
Empieza desde las 23:00 y contando cada 5 segundos
Cierro la consola
La abro nuevamente
y nuevamente empieza desde las 23:00 :S

Pienso utilizarlo como un reloj que asi conecte y desconecte el arduino, no pierda la hora y me de la hora indicada sin necesidad de establecerla cada vez que quiero usarlo. Si alguien ha trabajado con esto y pueda ayudarme, lo agradecería!.

Muchas gracias a todos y un saludo desde Bogotá.

Hola

Asegúrate que la batería tenga 3 volts.

Yo uso la libreria "RTClib"

Para cargar los datos de la hora usa el ejemplo ds1307
1.- Conecta lo al Arduino pero sin la batería.
2.- Carga el ejemplo al Arduino.
3.- Abre el monitor Serial para mirar que la hora se cargo correctamente.
4.- Con cuidado coloca la batería.

De esta forma mantendrá la hora correcta, siempre y cuando lo mantengas tengas con una buena batería.

Al parecer esa librería y ejemplo son para el DS 1307 porque aquí lo probé y nada, el tiempo no avanza y todos está bien conectado. Creo que será tirarlo al río y conseguir un DS 1307. Gracias ehrja tus aportes son muy valiosos.
Un saludo.

Una pregunta por curiosidad, cada vez que abres la consola serie arranca de nuevo, podrá ser por que al abrir la consola reinicia el arduino?

Hola.
Con este código realizado al vuelo y pila instalada en mi rtc, la hora se introduce enviando una s por serial.
Después se mantiene independientemente de si se apaga.
Prueba a ver.
Saludos.

#include <DS1302.h>
 
/* Set the appropriate digital I/O pin connections */
uint8_t CE_PIN   = 5;
uint8_t IO_PIN   = 6;
uint8_t SCLK_PIN = 7;
 
/* Create buffers */
char buf[50];
char day[10];
 
/* Create a DS1302 object */
DS1302 rtc(CE_PIN, IO_PIN, SCLK_PIN);
 
 
void print_time()
{
  /* Get the current time and date from the chip */
  Time t = rtc.time();
 
  /* Name the day of the week */
  memset(day, 0, sizeof(day));  /* clear day buffer */
  switch (t.day) {
  case 1:
    strcpy(day, "Sunday");
    break;
  case 2:
    strcpy(day, "Monday");
    break;
  case 3:
    strcpy(day, "Tuesday");
    break;
  case 4:
    strcpy(day, "Wednesday");
    break;
  case 5:
    strcpy(day, "Thursday");
    break;
  case 6:
    strcpy(day, "Friday");
    break;
  case 7:
    strcpy(day, "Saturday");
    break;
  }
 
  /* Format the time and date and insert into the temporary buffer */
  snprintf(buf, sizeof(buf), "%s %04d-%02d-%02d %02d:%02d:%02d",
  day,
  t.yr, t.mon, t.date,
  t.hr, t.min, t.sec);
 
  /* Print the formatted string to serial so we can see the time */
  Serial.println(buf);
}
 
 
void setup()
{
  Serial.begin(9600);
}
 
 
/* Loop and print the time every second */
void loop()
{
  if(Serial.available())
    gestionaComandos();
  print_time();
  delay(1000);
}
 
void gestionaComandos()
{
  Time t;
  if(Serial.read()=='s'){
    Serial.print("Year?: ");
    while(!Serial.available());
    t.yr=Serial.parseInt();
    Serial.println(t.yr);
    Serial.print("Month?: ");
    while(!Serial.available());
    t.mon=Serial.parseInt();
    Serial.println(t.mon);
    Serial.print("Day?: ");
    while(!Serial.available());
    t.date=Serial.parseInt();
    Serial.println(t.date);
    Serial.print("Day of week? (1=Sunday-7=Saturday");
    while(!Serial.available());
    t.day=Serial.parseInt();
    Serial.println(t.day);
    Serial.print("Hour?: ");
    while(!Serial.available());
    t.hr=Serial.parseInt();
    Serial.println(t.hr);
    Serial.print("Minute?: ");
    while(!Serial.available());
    t.min=Serial.parseInt();
    Serial.println(t.min);
    t.sec=0;
  }
  rtc.write_protect(false);
  rtc.halt(false);
  rtc.time(t);
}

Oh discúlpame, si me confundí con el ds1307, el ds1302 debería de funcionar igual.
...me dio la gripe :frowning:

Hola, me llamo Álvaro y soy nuevo en esto. Estoy empezando hacer pequeños proyectos con un Arduino Uno y me he comprado un DS1302, en los programas que e visto me dice que conecte el pin CE_PIN, pero en mi modulo no aparece ningún pin con ese nombre. Me podría ayudar alguien? También querría preguntar en que pin alimento el DS1302, en el VCC1 o en el VCC2?.

Muchas gracias de antemano y un saludo a todos!

VCC1 es la pila, al menos en mi plaquita.
ce pin, es reset ahora...

http://playground.arduino.cc/Main/DS1302

conexión

MODULE ARDUINO
GND GND del arduino
VCC 2 +5V del arduino
SCK D4 "salida digital arduino"
I/O D3 "salida digital arduino"
RST(CS) D2 "salida digital arduino"

scketch

/* Define the DIO pins used for the RTC module */
#define SCK_PIN 4
#define IO_PIN 3
#define RST_PIN 2

/* Include the DS1302 library */
#include <DS1302.h>

/* Initialise the DS1302 library */
DS1302 rtc(RST_PIN, IO_PIN, SCK_PIN);

void setup()
{
/* Clear the 1302's halt flag /
rtc.halt(false);
/
And disable write protection */
rtc.writeProtect(false);

/* Initialise the serial port */
Serial.begin(9600);
}

/* Main program */
void loop()
{

/* Set the time and date to 16:30 on the 3rd of September 2013 */
rtc.setDOW(MONDAY);
rtc.setTime(16,30,0);
rtc.setDate(3, 9, 2013);

/* Read the time and date once every second */
while(1)
{
Serial.print("It is ");
Serial.print(rtc.getDOWStr());
Serial.print(" ");
Serial.print(rtc.getDateStr());
Serial.print(" ");
Serial.print("and the time is: ");
Serial.println(rtc.getTimeStr());

/* Wait before reading again */
delay (1000);
}
}

Diego para la próxima si es que ya solucionaste tu problema PUBLICA tu código, el mismo con el que tienes problemas. Seguramente ahi se vería como al arrancar el ARDUINO se esta inicializando el RTC.

Muchas gracias Derty-2. ya e conseguido q medio funcione xD. Por que ahora me da un valor correcto, y al segundo siguiente me da otro erróneo, y así continuamente. Adjunto la foto con lo que me muestra el monitor. Gracias de nuevo!!

Con el tiempo alguien va comenzar a presentar sus programas con los links de las librerias y asi nos ahorraremos dolores de cabeza.

Este código funciona con esta librería

el ejemplo parecido al tuyo corresponde a la misma librería.
las funciones rtc.getDOWStr no existe asi que bajé la librería sugerida por Arduino y no tuve problemas.
Adjunto sketch y proteus.

// Example sketch for interfacing with the DS1302 timekeeping chip.
//
// Copyright (c) 2009, Matt Sparks
// All rights reserved.
//
// http://quadpoint.org/projects/arduino-ds1302
#include <stdio.h>
#include <DS1302.h>

namespace {
    // Set the appropriate digital I/O pin connections. These are the pin
    // assignments for the Arduino as well for as the DS1302 chip. See the DS1302
    // datasheet:
    //
    // http://datasheets.maximintegrated.com/en/ds/DS1302.pdf
    const int kCePin = 5; // Chip Enable
    const int kIoPin = 6; // Input/Output
    const int kSclkPin = 7; // Serial Clock
    // Create a DS1302 object.
    DS1302 rtc(kCePin, kIoPin, kSclkPin);
    String dayAsString(const Time::Day day) {
        switch (day) {
          case Time::kSunday: return "Domingo";
          case Time::kMonday: return "Lunes";
          case Time::kTuesday: return "Martes";
          case Time::kWednesday: return "Miercoles";
          case Time::kThursday: return "Jueves";
          case Time::kFriday: return "Viernes";
          case Time::kSaturday: return "Sabado";
        }
        return "(dia desconocido)";
    }
    void printTime() {
      // Get the current time and date from the chip.
      Time t = rtc.time();
      // Name the day of the week.
      const String day = dayAsString(t.day);
      // Format the time and date and insert into the temporary buffer.
      char buf[50];
      snprintf(buf, sizeof(buf), "%s %04d-%02d-%02d %02d:%02d:%02d",
      day.c_str(),
      t.yr, t.mon, t.date,
      t.hr, t.min, t.sec);
      // Print the formatted string to serial so we can see the time.
      Serial.println(buf);
      }
} // namespace

void setup() {
  Serial.begin(9600);
  // Initialize a new chip by turning off write protection and clearing the
  // clock halt flag. These methods needn't always be called. See the DS1302
  // datasheet for details.
  rtc.writeProtect(false);
  rtc.halt(false);
  // Make a new time object to set the date and time.
  // Sunday, September 22, 2013 at 01:38:50.
  Time t(2013, 9, 22, 1, 38, 50, Time::kSunday);
  // Set the time and date on the chip.
  rtc.time(t);
}
// Loop and print the time every second.
void loop() {
  printTime();
  delay(1000);
}

Arduino 328.pdsprj (21.4 KB)

DS1302_forum.ino (958 Bytes)

Alvaroal1:
Muchas gracias Derty-2. ya e conseguido q medio funcione xD. Por que ahora me da un valor correcto, y al segundo siguiente me da otro erróneo, y así continuamente. Adjunto la foto con lo que me muestra el monitor. Gracias de nuevo!!

Ya habrás solucionado el tema, pero dejar reflejado que poniéndolo a 3.3v queda resuelto.

Hola,

Me pasaba lo mismo que a Alvaroal1 , me daba el valor correcto y al segundo me daba otro erroneo.

Hice lo que frmonge sugeria y puse VCC del modulo a 3,5 v y funciona todas las lecturas bien. Pero si quieres cambiar la hora, si el VCC del modulo RTC esta conectado a 3,5 V NO cambia la hora.

En mi caso para cambiar la hora hay que conectarlo a 5v.

Un saludo

Hola gente, despues de mucho probar y nada que conseguia hacer funcionar el modulo, no al menos como yo queria. El caso es que busque y encontre esta pagina que tiene todo muy bien explicado, claro esta que DEBES usar la libreria incluida en la pagina, pero te aseguro que entenderas rapidamente.

Les dejo el link, Suerte. http://librearduino.blogspot.com.co/2014/01/rtc-arduino-modulo-reloj-tiempo-real-tutorial.html