Loading...
Pages: [1] 2   Go Down
Author Topic: Alguien monto el RTC con el DS1703 (Circuito)  (Read 1381 times)
0 Members and 1 Guest are viewing this topic.
Offline Offline
Newbie
*
Karma: 0
Posts: 25
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Yo estoy siguiendo este esquema: http://tronixstuff.files.wordpress.com/2010/05/ds1307exampleuse.jpg

Espero sea correcto. Supongo que todas las masas se pueden unir, ya se de 5v o 3v de la pila...
Logged

Spain
Offline Offline
God Member
*****
Karma: 22
Posts: 858
Arduino rocks
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Yo lo tengo montado asi:



Las masas son las mismas.
Logged

CUIDADO !! MIS POST NO SON APTOS PARA MENORES. SI ERES MENOR DE 14 AÑOS DEBES DE LEERLOS ACOMPAÑADO DE UN ADULTO

En diseño te tienen que gustar más las preguntas que las respuestas [.Jray.]


Si estas empezando:
1- Comienza a usar Arduino
2- Guías de iniciación a Arduino
3- Ejemplos
4- Referencia del Lenguaje
5- Conceptos básicos
6- Guia de usuario de arduino

Offline Offline
Newbie
*
Karma: 0
Posts: 25
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Que librerías usáis? Algún tutorial?

Si es el mismo circuito. Lo único que también monte el SQW que en principio no se usa. Pues voy a soldar el GND y probar si funciona!

Los nuevos llevan?

(Creo que vale la pena comprarlo hecho porque si vale 15€ casi en material seguro que sale por 10€ y con lo que se tarda...)

Gracias

Nota: también tiene un condensador multicapa 100k entre la patilla 8 y massa.
Logged

0
Offline Offline
Edison Member
*
Karma: 8
Posts: 1040
Arduino rocks
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

La libreria wire.h viene por defecto con el IDE de arduino.

Puedes usar este codigo.
Code:
//

// Maurice Ribble

// 4-17-2008

// http://www.glacialwanderer.com/hobbyrobotics



// This code tests the DS1307 Real Time clock on the Arduino board.

// The ds1307 works in binary coded decimal or BCD.  You can look up

// bcd in google if you aren't familior with it.  There can output

// a square wave, but I don't expose that in this code.  See the

// ds1307 for it's full capabilities.



#include "Wire.h"

#define DS1307_I2C_ADDRESS 0x68



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

}



// Stops the DS1307, but it has the side effect of setting seconds to 0

// Probably only want to use this for testing

/*void stopDs1307()

{

  Wire.beginTransmission(DS1307_I2C_ADDRESS);

  Wire.send(0);

  Wire.send(0x80);

  Wire.endTransmission();

}*/



// 1) Sets the date and time on the ds1307

// 2) Starts the clock

// 3) Sets hour mode to 24 hour clock

// Assumes you're passing in valid numbers

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.send(0);

   Wire.send(decToBcd(second));    // 0 to bit 7 starts the clock

   Wire.send(decToBcd(minute));

   Wire.send(decToBcd(hour));      // If you want 12 hour am/pm you need to set

                                   // bit 6 (also need to change readDateDs1307)

   Wire.send(decToBcd(dayOfWeek));

   Wire.send(decToBcd(dayOfMonth));

   Wire.send(decToBcd(month));

   Wire.send(decToBcd(year));

   Wire.endTransmission();

}



// Gets the date and time from the ds1307

void getDateDs1307(byte *second,

          byte *minute,

          byte *hour,

          byte *dayOfWeek,

          byte *dayOfMonth,

          byte *month,

          byte *year)

{

  // Reset the register pointer

  Wire.beginTransmission(DS1307_I2C_ADDRESS);

  Wire.send(0);

  Wire.endTransmission();



  Wire.requestFrom(DS1307_I2C_ADDRESS, 7);



  // A few of these need masks because certain bits are control bits

  *second     = bcdToDec(Wire.receive() & 0x7f);

  *minute     = bcdToDec(Wire.receive());

  *hour       = bcdToDec(Wire.receive() & 0x3f);  // Need to change this if 12 hour am/pm

  *dayOfWeek  = bcdToDec(Wire.receive());

  *dayOfMonth = bcdToDec(Wire.receive());

  *month      = bcdToDec(Wire.receive());

  *year       = bcdToDec(Wire.receive());

}



void setup()

{

  byte second, minute, hour, dayOfWeek, dayOfMonth, month, year;

  Wire.begin();

  Serial.begin(9600);



  // Change these values to what you want to set your clock to.

  // You probably only want to set your clock once and then remove

  // the setDateDs1307 call.

  second = 45;

  minute = 3;

  hour = 7;

  dayOfWeek = 5;

  dayOfMonth = 17;

  month = 4;

  year = 8;

  setDateDs1307(second, minute, hour, dayOfWeek, dayOfMonth, month, year);

}



void loop()

{

  byte second, minute, hour, dayOfWeek, dayOfMonth, month, year;



  getDateDs1307(&second, &minute, &hour, &dayOfWeek, &dayOfMonth, &month, &year);

  Serial.print(hour, DEC);

  Serial.print(":");

  Serial.print(minute, DEC);

  Serial.print(":");

  Serial.print(second, DEC);

  Serial.print("  ");

  Serial.print(month, DEC);

  Serial.print("/");

  Serial.print(dayOfMonth, DEC);

  Serial.print("/");

  Serial.print(year, DEC);

  Serial.print("  Day_of_week:");

  Serial.println(dayOfWeek, DEC);



  delay(1000);

}
Logged

Trabajando en ...

    * Control Domotico (En montaje ...)
    http://casitadomotica.blogspot.com/
 


0
Offline Offline
Edison Member
*
Karma: 13
Posts: 1265
Arduino rocks
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Que librerías usáis? Algún tutorial?

Si es el mismo circuito. Lo único que también monte el SQW que en principio no se usa. Pues voy a soldar el GND y probar si funciona!

Los nuevos llevan?

(Creo que vale la pena comprarlo hecho porque si vale 15€ casi en material seguro que sale por 10€ y con lo que se tarda...)

Gracias

Nota: también tiene un condensador multicapa 100k entre la patilla 8 y massa.

usa la libreria que viene con el programa, hoy mismo he estado trasteandola por primera vez y funciona perfectamente, incluso te actualiza la fecha y hora en base a la de tu ordenador en el momento de compilar el programa !! una bendición vamos !! eso si recuerda luego comentar la linea de ajuste de fecha y hora y volver a cargar el programa sino cada vez que se resetee te metera la fecha y hora de cuando se compilo.

yo compre 2 kits montados por ebay y me salieron muy bien de precio, te lo busco...
encontrado
http://myworld.ebay.es/i.control/
Logged

* Si preguntas, pon el código de tu programa, hace mucho mas fácil ayudarte. Y me ahorro un mensaje pidiendo que lo hagas.
* Si consigues solucionar tu problema, dedica unos minutos a explicar en tu post como lo conseguiste para beneficio de todos.
* Cambia el 'Subject' de tu hilo y añade 'SOLUCIONADO' cuando hayas llegado a una solución al problema que planteaste.
* Utiliza un 'Subject' para tu hilo que explique de que va el hilo.
Si estas empezando:
* Comienza a usar Arduino
* Guías de iniciación a Arduino
* Ejemplos
* Referencia del Lenguaje
* Conceptos básicos
Guia de usuario de arduino
Tutoriales en Ingles
Si necesitas que alguien te escriba el código: http://www.freelancer.com/  o esta  http://www.guru.com/

Spain
Offline Offline
God Member
*****
Karma: 22
Posts: 858
Arduino rocks
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset


usa la libreria que viene con el programa, hoy mismo he estado trasteandola por primera vez y funciona perfectamente, incluso te actualiza la fecha y hora en base a la de tu ordenador en el momento de compilar el programa !! una bendición vamos !! eso si recuerda luego comentar la linea de ajuste de fecha y hora y volver a cargar el programa sino cada vez que se resetee te metera la fecha y hora de cuando se compilo.

SergeGsx

¿Donde esta esa opcion que te actualiza la hora en el momento de compilar con la de tu ordenador?

No encuentro en wire esa opcion ni ejemplo

Es que lo estoy haciendo manualmente y seria genial olvidarte de eso

Un saludo de un Gsf
« Last Edit: August 06, 2011, 04:16:47 am by Heke » Logged

CUIDADO !! MIS POST NO SON APTOS PARA MENORES. SI ERES MENOR DE 14 AÑOS DEBES DE LEERLOS ACOMPAÑADO DE UN ADULTO

En diseño te tienen que gustar más las preguntas que las respuestas [.Jray.]


Si estas empezando:
1- Comienza a usar Arduino
2- Guías de iniciación a Arduino
3- Ejemplos
4- Referencia del Lenguaje
5- Conceptos básicos
6- Guia de usuario de arduino

Madrid
Offline Offline
Newbie
*
Karma: 1
Posts: 22
Arduino rocks
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Hola a todos. Hay que tener en cuenta una nota de aplicación, que ahora no soy capaz de encontrar, que dice que es imperativo cubrir con un plano de masa la cara opuesta de las pista del cristal y el cristal.Os recomiendo que dejeis habilitado el pin SQW pués es muy util, para aprovecharlo para interrupciones etc.
Un saludo a todos.
Logged

0
Offline Offline
Edison Member
*
Karma: 13
Posts: 1265
Arduino rocks
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset


usa la libreria que viene con el programa, hoy mismo he estado trasteandola por primera vez y funciona perfectamente, incluso te actualiza la fecha y hora en base a la de tu ordenador en el momento de compilar el programa !! una bendición vamos !! eso si recuerda luego comentar la linea de ajuste de fecha y hora y volver a cargar el programa sino cada vez que se resetee te metera la fecha y hora de cuando se compilo.

SergeGsx

¿Donde esta esa opcion que te actualiza la hora en el momento de compilar con la de tu ordenador?

No encuentro en wire esa opcion ni ejemplo

Es que lo estoy haciendo manualmente y seria genial olvidarte de eso

Un saludo de un Gsf

Lo tienes en el Arduino 22, entras en File...Examples...RTCLib...ds1307, te lo copio aqui de todas formas

Code:
// Date and time functions using a DS1307 RTC connected via I2C and Wire lib

#include <Wire.h>
#include "RTClib.h"

RTC_DS1307 RTC;

void setup () {
    Serial.begin(57600);
    Wire.begin();
    RTC.begin();

  if (! RTC.isrunning()) {
    Serial.println("RTC is NOT running!");
    // following line sets the RTC to the date & time this sketch was compiled
    RTC.adjust(DateTime(__DATE__, __TIME__));
  }
}

void loop () {
    DateTime now = RTC.now();
   
    Serial.print(now.year(), DEC);
    Serial.print('/');
    Serial.print(now.month(), DEC);
    Serial.print('/');
    Serial.print(now.day(), DEC);
    Serial.print(' ');
    Serial.print(now.hour(), DEC);
    Serial.print(':');
    Serial.print(now.minute(), DEC);
    Serial.print(':');
    Serial.print(now.second(), DEC);
    Serial.println();
   
    Serial.print(" since midnight 1/1/1970 = ");
    Serial.print(now.unixtime());
    Serial.print("s = ");
    Serial.print(now.unixtime() / 86400L);
    Serial.println("d");
   
    // calculate a date which is 7 days and 30 seconds into the future
    DateTime future (now.unixtime() + 7 * 86400L + 30);
   
    Serial.print(" now + 7d + 30s: ");
    Serial.print(future.year(), DEC);
    Serial.print('/');
    Serial.print(future.month(), DEC);
    Serial.print('/');
    Serial.print(future.day(), DEC);
    Serial.print(' ');
    Serial.print(future.hour(), DEC);
    Serial.print(':');
    Serial.print(future.minute(), DEC);
    Serial.print(':');
    Serial.print(future.second(), DEC);
    Serial.println();
   
    Serial.println();
    delay(3000);
}


esta es la linea que ajusta el reloj, pero recuerda que una vez este ajustado, debes quitar ese programa del arduino o comentar dicha linea y volver a cargar el programa, sino cada vez que se resetee volvera a establecer la fecha y hora de cuando se compilo y ya no sera valida.
Code:
    RTC.adjust(DateTime(__DATE__, __TIME__));
Logged

* Si preguntas, pon el código de tu programa, hace mucho mas fácil ayudarte. Y me ahorro un mensaje pidiendo que lo hagas.
* Si consigues solucionar tu problema, dedica unos minutos a explicar en tu post como lo conseguiste para beneficio de todos.
* Cambia el 'Subject' de tu hilo y añade 'SOLUCIONADO' cuando hayas llegado a una solución al problema que planteaste.
* Utiliza un 'Subject' para tu hilo que explique de que va el hilo.
Si estas empezando:
* Comienza a usar Arduino
* Guías de iniciación a Arduino
* Ejemplos
* Referencia del Lenguaje
* Conceptos básicos
Guia de usuario de arduino
Tutoriales en Ingles
Si necesitas que alguien te escriba el código: http://www.freelancer.com/  o esta  http://www.guru.com/

Spain
Offline Offline
God Member
*****
Karma: 22
Posts: 858
Arduino rocks
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Muchas Gracias

Voy a probar ahora mismo.

Ni lo habia visto, es que aun sigo con la version 18 de arduino, no he actualizado al 22 por miedo a fallara algo... esto de ir con tantas prisas...

Un saludo.
Logged

CUIDADO !! MIS POST NO SON APTOS PARA MENORES. SI ERES MENOR DE 14 AÑOS DEBES DE LEERLOS ACOMPAÑADO DE UN ADULTO

En diseño te tienen que gustar más las preguntas que las respuestas [.Jray.]


Si estas empezando:
1- Comienza a usar Arduino
2- Guías de iniciación a Arduino
3- Ejemplos
4- Referencia del Lenguaje
5- Conceptos básicos
6- Guia de usuario de arduino

Spain
Offline Offline
God Member
*****
Karma: 22
Posts: 858
Arduino rocks
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

No hay forma...

He descargado el ide 022 y no tiene ese ejemplo o libreria, he probado ejemplos que trae de time pero no encuentro esa funcion...

buscare por la web a ver si encuentro algo...

Añado lo que he conseguido por el momento:
  La libreria no la trae el ide del arduino, es de adafruit (añado y edito, no solo adafruit, jeelabs tambien).
 he conseguido meterlo el pde del ejemplo pero no coge la fecha bien del PC

Mi fecha y hora es esta: 
   6 de agosto de 2011 y hora 21:25

El arduino dice esta otra: 
  2011/8/6 21:43:0
    since midnight 1/1/1970 = 1312666980s = 15192d
    now + 7d + 30s: 2011/8/13 21:43:30

Que es la hora que hace tiempo le programe y sigue avanzando pero desfasada, es que no cambia la hora con la del PC
¿Alguna idea?

.....  respondo despues de algunas horas de pelear...
He encontrado diferencias entre librerias, unas tienen la cabecera de JeeLabs, otras de Sjunnesson y hay varias versiones.

Al final he conseguido que coja la hora con el ide 018, y una libreria antigua pero eliminando la llamada a:
   if (! RTC.isrunning()) {     que se ve no estaba implementada, quitado esto, he conseguido que se actualice automatico.

Ahora tengo que ver que problema hay de version y si es del ide, de la libreria RTC, de wire o lo que sea... pero ya no sera hoy.

Un saludo.
« Last Edit: August 06, 2011, 04:57:54 pm by Heke » Logged

CUIDADO !! MIS POST NO SON APTOS PARA MENORES. SI ERES MENOR DE 14 AÑOS DEBES DE LEERLOS ACOMPAÑADO DE UN ADULTO

En diseño te tienen que gustar más las preguntas que las respuestas [.Jray.]


Si estas empezando:
1- Comienza a usar Arduino
2- Guías de iniciación a Arduino
3- Ejemplos
4- Referencia del Lenguaje
5- Conceptos básicos
6- Guia de usuario de arduino

0
Offline Offline
Edison Member
*
Karma: 13
Posts: 1265
Arduino rocks
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

me alegro que lo hayas solucionado.
si quieres puedo pasarte la libreria y los ejemplos que tengo yo. bueno mas facil lo pongo aqui y ya esta.
para no tener que copiar el archivo comprimido  a un servidor que luego puede que falle, te copio los dos archivos de la libreria y el archivo del ejemplo.

Libreria

RTClib.h
Code:
// Code by JeeLabs http://news.jeelabs.org/code/
// Released to the public domain! Enjoy!

// Simple general-purpose date/time class (no TZ / DST / leap second handling!)
class DateTime {
public:
    DateTime (uint32_t t =0);
    DateTime (uint16_t year, uint8_t month, uint8_t day,
                uint8_t hour =0, uint8_t min =0, uint8_t sec =0);
    DateTime (const char* date, const char* time);
    uint16_t year() const       { return 2000 + yOff; }
    uint8_t month() const       { return m; }
    uint8_t day() const         { return d; }
    uint8_t hour() const        { return hh; }
    uint8_t minute() const      { return mm; }
    uint8_t second() const      { return ss; }
    uint8_t dayOfWeek() const;

    // 32-bit times as seconds since 1/1/2000
    long secondstime() const;   
    // 32-bit times as seconds since 1/1/1970
    uint32_t unixtime(void) const;

protected:
    uint8_t yOff, m, d, hh, mm, ss;
};

// RTC based on the DS1307 chip connected via I2C and the Wire library
class RTC_DS1307 {
public:
  static uint8_t begin(void);
    static void adjust(const DateTime& dt);
    uint8_t isrunning(void);
    static DateTime now();
};

// RTC using the internal millis() clock, has to be initialized before use
// NOTE: this clock won't be correct once the millis() timer rolls over (>49d?)
class RTC_Millis {
public:
    static void begin(const DateTime& dt) { adjust(dt); }
    static void adjust(const DateTime& dt);
    static DateTime now();

protected:
    static long offset;
};


RCTlib.cpp
Code:
// Code by JeeLabs http://news.jeelabs.org/code/
// Released to the public domain! Enjoy!

#include <Wire.h>
#include <avr/pgmspace.h>
#include "RTClib.h"
#include <WProgram.h>

#define DS1307_ADDRESS 0x68
#define SECONDS_PER_DAY 86400L

#define SECONDS_FROM_1970_TO_2000 946684800

////////////////////////////////////////////////////////////////////////////////
// utility code, some of this could be exposed in the DateTime API if needed

static uint8_t daysInMonth [] PROGMEM = { 31,28,31,30,31,30,31,31,30,31,30,31 };

// number of days since 2000/01/01, valid for 2001..2099
static uint16_t date2days(uint16_t y, uint8_t m, uint8_t d) {
    if (y >= 2000)
        y -= 2000;
    uint16_t days = d;
    for (uint8_t i = 1; i < m; ++i)
        days += pgm_read_byte(daysInMonth + i - 1);
    if (m > 2 && y % 4 == 0)
        ++days;
    return days + 365 * y + (y + 3) / 4 - 1;
}

static long time2long(uint16_t days, uint8_t h, uint8_t m, uint8_t s) {
    return ((days * 24L + h) * 60 + m) * 60 + s;
}

////////////////////////////////////////////////////////////////////////////////
// DateTime implementation - ignores time zones and DST changes
// NOTE: also ignores leap seconds, see http://en.wikipedia.org/wiki/Leap_second

DateTime::DateTime (uint32_t t) {
  t -= SECONDS_FROM_1970_TO_2000;    // bring to 2000 timestamp from 1970

    ss = t % 60;
    t /= 60;
    mm = t % 60;
    t /= 60;
    hh = t % 24;
    uint16_t days = t / 24;
    uint8_t leap;
    for (yOff = 0; ; ++yOff) {
        leap = yOff % 4 == 0;
        if (days < 365 + leap)
            break;
        days -= 365 + leap;
    }
    for (m = 1; ; ++m) {
        uint8_t daysPerMonth = pgm_read_byte(daysInMonth + m - 1);
        if (leap && m == 2)
            ++daysPerMonth;
        if (days < daysPerMonth)
            break;
        days -= daysPerMonth;
    }
    d = days + 1;
}

DateTime::DateTime (uint16_t year, uint8_t month, uint8_t day, uint8_t hour, uint8_t min, uint8_t sec) {
    if (year >= 2000)
        year -= 2000;
    yOff = year;
    m = month;
    d = day;
    hh = hour;
    mm = min;
    ss = sec;
}

static uint8_t conv2d(const char* p) {
    uint8_t v = 0;
    if ('0' <= *p && *p <= '9')
        v = *p - '0';
    return 10 * v + *++p - '0';
}

// A convenient constructor for using "the compiler's time":
//   DateTime now (__DATE__, __TIME__);
// NOTE: using PSTR would further reduce the RAM footprint
DateTime::DateTime (const char* date, const char* time) {
    // sample input: date = "Dec 26 2009", time = "12:34:56"
    yOff = conv2d(date + 9);
    // Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec
    switch (date[0]) {
        case 'J': m = date[1] == 'a' ? 1 : m = date[2] == 'n' ? 6 : 7; break;
        case 'F': m = 2; break;
        case 'A': m = date[2] == 'r' ? 4 : 8; break;
        case 'M': m = date[2] == 'r' ? 3 : 5; break;
        case 'S': m = 9; break;
        case 'O': m = 10; break;
        case 'N': m = 11; break;
        case 'D': m = 12; break;
    }
    d = conv2d(date + 4);
    hh = conv2d(time);
    mm = conv2d(time + 3);
    ss = conv2d(time + 6);
}

uint8_t DateTime::dayOfWeek() const {   
    uint16_t day = date2days(yOff, m, d);
    return (day + 6) % 7; // Jan 1, 2000 is a Saturday, i.e. returns 6
}

uint32_t DateTime::unixtime(void) const {
  uint32_t t;
  uint16_t days = date2days(yOff, m, d);
  t = time2long(days, hh, mm, ss);
  t += SECONDS_FROM_1970_TO_2000;  // seconds from 1970 to 2000

  return t;
}

////////////////////////////////////////////////////////////////////////////////
// RTC_DS1307 implementation

static uint8_t bcd2bin (uint8_t val) { return val - 6 * (val >> 4); }
static uint8_t bin2bcd (uint8_t val) { return val + 6 * (val / 10); }

uint8_t RTC_DS1307::begin(void) {
  return 1;
}

uint8_t RTC_DS1307::isrunning(void) {
  Wire.beginTransmission(DS1307_ADDRESS);
  Wire.send(0);
  Wire.endTransmission();

  Wire.requestFrom(DS1307_ADDRESS, 1);
  uint8_t ss = Wire.receive();
  return !(ss>>7);
}

void RTC_DS1307::adjust(const DateTime& dt) {
    Wire.beginTransmission(DS1307_ADDRESS);
    Wire.send(0);
    Wire.send(bin2bcd(dt.second()));
    Wire.send(bin2bcd(dt.minute()));
    Wire.send(bin2bcd(dt.hour()));
    Wire.send(bin2bcd(0));
    Wire.send(bin2bcd(dt.day()));
    Wire.send(bin2bcd(dt.month()));
    Wire.send(bin2bcd(dt.year() - 2000));
    Wire.send(0);
    Wire.endTransmission();
}

DateTime RTC_DS1307::now() {
  Wire.beginTransmission(DS1307_ADDRESS);
  Wire.send(0);
  Wire.endTransmission();
 
  Wire.requestFrom(DS1307_ADDRESS, 7);
  uint8_t ss = bcd2bin(Wire.receive() & 0x7F);
  uint8_t mm = bcd2bin(Wire.receive());
  uint8_t hh = bcd2bin(Wire.receive());
  Wire.receive();
  uint8_t d = bcd2bin(Wire.receive());
  uint8_t m = bcd2bin(Wire.receive());
  uint16_t y = bcd2bin(Wire.receive()) + 2000;
 
  return DateTime (y, m, d, hh, mm, ss);
}

////////////////////////////////////////////////////////////////////////////////
// RTC_Millis implementation

long RTC_Millis::offset = 0;

void RTC_Millis::adjust(const DateTime& dt) {
    offset = dt.unixtime() - millis() / 1000;
}

DateTime RTC_Millis::now() {
  return (uint32_t)(offset + millis() / 1000);
}

////////////////////////////////////////////////////////////////////////////////

Ejemplo que me funciona con IDE 22

ds1307.pde
Code:
// Date and time functions using a DS1307 RTC connected via I2C and Wire lib

#include <Wire.h>
#include "RTClib.h"

RTC_DS1307 RTC;

void setup () {
    Serial.begin(57600);
    Wire.begin();
    RTC.begin();

  if (! RTC.isrunning()) {
    Serial.println("RTC is NOT running!");
    // following line sets the RTC to the date & time this sketch was compiled
    RTC.adjust(DateTime(__DATE__, __TIME__));
  }
}

void loop () {
    DateTime now = RTC.now();
   
    Serial.print(now.year(), DEC);
    Serial.print('/');
    Serial.print(now.month(), DEC);
    Serial.print('/');
    Serial.print(now.day(), DEC);
    Serial.print(' ');
    Serial.print(now.hour(), DEC);
    Serial.print(':');
    Serial.print(now.minute(), DEC);
    Serial.print(':');
    Serial.print(now.second(), DEC);
    Serial.println();
   
    Serial.print(" since midnight 1/1/1970 = ");
    Serial.print(now.unixtime());
    Serial.print("s = ");
    Serial.print(now.unixtime() / 86400L);
    Serial.println("d");
   
    // calculate a date which is 7 days and 30 seconds into the future
    DateTime future (now.unixtime() + 7 * 86400L + 30);
   
    Serial.print(" now + 7d + 30s: ");
    Serial.print(future.year(), DEC);
    Serial.print('/');
    Serial.print(future.month(), DEC);
    Serial.print('/');
    Serial.print(future.day(), DEC);
    Serial.print(' ');
    Serial.print(future.hour(), DEC);
    Serial.print(':');
    Serial.print(future.minute(), DEC);
    Serial.print(':');
    Serial.print(future.second(), DEC);
    Serial.println();
   
    Serial.println();
    delay(3000);
}
Logged

* Si preguntas, pon el código de tu programa, hace mucho mas fácil ayudarte. Y me ahorro un mensaje pidiendo que lo hagas.
* Si consigues solucionar tu problema, dedica unos minutos a explicar en tu post como lo conseguiste para beneficio de todos.
* Cambia el 'Subject' de tu hilo y añade 'SOLUCIONADO' cuando hayas llegado a una solución al problema que planteaste.
* Utiliza un 'Subject' para tu hilo que explique de que va el hilo.
Si estas empezando:
* Comienza a usar Arduino
* Guías de iniciación a Arduino
* Ejemplos
* Referencia del Lenguaje
* Conceptos básicos
Guia de usuario de arduino
Tutoriales en Ingles
Si necesitas que alguien te escriba el código: http://www.freelancer.com/  o esta  http://www.guru.com/

Spain
Offline Offline
God Member
*****
Karma: 22
Posts: 858
Arduino rocks
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Muchas gracias SergeGsx

Esta mañana lo he puesto (tu codigo y libreria en el 022) y tampoco me funcionaba, pero he cambiado esto en el codigo y ya funciona:
He sustituido esta llamada a la comprobacion de que el RTC esta funcionando:
Code:
  if (! RTC.isrunning()) {
    Serial.println("RTC is NOT running!");
    // following line sets the RTC to the date & time this sketch was compiled
    RTC.adjust(DateTime(__DATE__, __TIME__));
  }

Por este otro codigo:
Code:
  if (RTC.isrunning()) {
    // following line sets the RTC to the date & time this sketch was compiled
    RTC.adjust(DateTime(__DATE__, __TIME__));
    }
    else{
    Serial.println("RTC is NOT running!");
    }

Y ahora si que actualiza.
Yo interpreto que el condicional dice  algo asi como que "si el RTC no esta corriendo, ajusta la hora" y he pensado que debia decir algo asi como que "si el RTC no esta corriendo >manda mensaje que no corre en caso contrario, ajusta la hora"

Pero bueno, salvo ese detalle que no lo entiendo, ahora va la mar de bien.

Muchisimas Gracias y un saludo.

PD: Se me ha ocurrido que para que no ejecute de nuevo la actualizacion de hora en caso de reset o falta de alimentacion, ponerle un condicional de que >si la hora actual es mayor que la de la hora de compilacion =no actualizar y en caso contrario Si, lo malo es que el problema sea que el RTC en vez de retrasar, adelante.
   Otra posibilidad, dejar una entrada de configuracion y a la hora de mandarle el programa compilado, que este cortocircuitada, al leerla ve que hay que actualizar la hora y nada mas mandarlo y antes que se resetee o se quede sin electricidad, quitarle ese jumper, por ejemplo.

PD2: he encontrado otra libreria lamada DS1307RTC con copyright de Michael Margolis 2009

« Last Edit: August 07, 2011, 05:52:29 am by Heke » Logged

CUIDADO !! MIS POST NO SON APTOS PARA MENORES. SI ERES MENOR DE 14 AÑOS DEBES DE LEERLOS ACOMPAÑADO DE UN ADULTO

En diseño te tienen que gustar más las preguntas que las respuestas [.Jray.]


Si estas empezando:
1- Comienza a usar Arduino
2- Guías de iniciación a Arduino
3- Ejemplos
4- Referencia del Lenguaje
5- Conceptos básicos
6- Guia de usuario de arduino

0
Offline Offline
Edison Member
*
Karma: 13
Posts: 1265
Arduino rocks
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

me alegro que ya te funcione, yo tambien pensaba que esa parte del codigo no esta bien escrita y tu forma me gusta mas pero como me funcionaba no me puse a cambiarlo.

yo prefiero programar el RCT y quitar cualquier cosa que pueda modificarmelo, al fin y al cabo si metes el proyecto en el arduino y se supone que va a estar funcionando sin un ordenador no va a tener la fecha y hora actualizadas del compilador nunca mas. pero bueno lo q dices no es mala opcion
Logged

* Si preguntas, pon el código de tu programa, hace mucho mas fácil ayudarte. Y me ahorro un mensaje pidiendo que lo hagas.
* Si consigues solucionar tu problema, dedica unos minutos a explicar en tu post como lo conseguiste para beneficio de todos.
* Cambia el 'Subject' de tu hilo y añade 'SOLUCIONADO' cuando hayas llegado a una solución al problema que planteaste.
* Utiliza un 'Subject' para tu hilo que explique de que va el hilo.
Si estas empezando:
* Comienza a usar Arduino
* Guías de iniciación a Arduino
* Ejemplos
* Referencia del Lenguaje
* Conceptos básicos
Guia de usuario de arduino
Tutoriales en Ingles
Si necesitas que alguien te escriba el código: http://www.freelancer.com/  o esta  http://www.guru.com/

Euskadi
Offline Offline
God Member
*****
Karma: 10
Posts: 613
Arduinotarrak
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Hola,
yo conozco el DS1307. Si este topic se refiere a ese reloj, mejor corregir la errata.
Logged

Spain
Offline Offline
God Member
*****
Karma: 22
Posts: 858
Arduino rocks
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

He pensado que igual no es una errata.

Es posible que el codigo original pueda ser valido para cuando el RTC no ha sido inicializado  y no tiene ninguna hora, entonces en ese caso si tendria explicacion, es decir, el RTC no esta corriendo y entonces lo inicializa con la hora.

En la modificacion que yo he puesto se supone que el RTC ya esta corriendo, por lo que nunca saldria de la opcion  "if (! RTC.isrunning()) " y hace falta cambiar el condicional y actualizar "si" o "si".

De todas formas son suposiciones porque desconozco la funcion  <RTC.isrunning()> de donde saca el parametro, ni lo que chequea, pero estos pensamientos parecen logicos.

El codigo es utilisimo en mi caso, pues no me complico en inicializar horas, le cargo un sketch exclusivo para ponerlo en hora y despues sin resetear le cargo el bueno y ya me deja el RTC corriendo actualizado y de la forma mas facil.
Logged

CUIDADO !! MIS POST NO SON APTOS PARA MENORES. SI ERES MENOR DE 14 AÑOS DEBES DE LEERLOS ACOMPAÑADO DE UN ADULTO

En diseño te tienen que gustar más las preguntas que las respuestas [.Jray.]


Si estas empezando:
1- Comienza a usar Arduino
2- Guías de iniciación a Arduino
3- Ejemplos
4- Referencia del Lenguaje
5- Conceptos básicos
6- Guia de usuario de arduino

Pages: [1] 2   Go Up
Print
 
Jump to: