Statistics
| Revision:

root / Ports / examples / rtc_demo / rtc_demo.pde

History | View | Annotate | Download (1.6 KB)

1
//>>> The latest version of this code can be found at https://github.com/jcw/ !!
2
3
// Hooking up a DS1307 (5V) or DS1340Z (3V) real time clock via I2C.
4
// see http://jeelabs.org/cp1
5
// 2009-09-17 <jcw@equi4.com> http://opensource.org/licenses/mit-license.php
6
// $Id: rtc_demo.pde 7763 2011-12-11 01:28:16Z jcw $
7
8
// the real-time clock is connected to port 1 in I2C mode (AIO = SCK, dIO = SDA)
9
10
#include <Ports.h>
11
#include <RF12.h> // needed to avoid a linker error :(
12
13
PortI2C myport (1 /*, PortI2C::KHZ400 */);
14
DeviceI2C rtc (myport, 0x68);
15
16
static byte bin2bcd (byte val) {
17
    return val + 6 * (val / 10);
18
}
19
20
static byte bcd2bin (byte val) {
21
    return val - 6 * (val >> 4);
22
}
23
24
static void setDate (byte yy, byte mm, byte dd, byte h, byte m, byte s) {
25
    rtc.send();
26
    rtc.write(0);
27
    rtc.write(bin2bcd(s));
28
    rtc.write(bin2bcd(m));
29
    rtc.write(bin2bcd(h));
30
    rtc.write(bin2bcd(0));
31
    rtc.write(bin2bcd(dd));
32
    rtc.write(bin2bcd(mm));
33
    rtc.write(bin2bcd(yy));
34
    rtc.write(0);
35
    rtc.stop();
36
}
37
38
static void getDate (byte* buf) {
39
	rtc.send();
40
	rtc.write(0);	
41
    rtc.stop();
42
43
	rtc.receive();
44
    buf[5] = bcd2bin(rtc.read(0));
45
    buf[4] = bcd2bin(rtc.read(0));
46
    buf[3] = bcd2bin(rtc.read(0));
47
    rtc.read(0);
48
    buf[2] = bcd2bin(rtc.read(0));
49
    buf[1] = bcd2bin(rtc.read(0));
50
    buf[0] = bcd2bin(rtc.read(1));
51
    rtc.stop();
52
}
53
54
void setup() {
55
    Serial.begin(57600);
56
    Serial.println("\n[rtc_demo]");
57
58
    // test code:
59
    setDate(9, 9, 17, 13, 18, 0);
60
}
61
62
void loop() {    
63
    byte now[6];
64
    getDate(now);
65
    
66
    Serial.print("rtc");
67
    for (byte i = 0; i < 6; ++i) {
68
        Serial.print(' ');
69
        Serial.print((int) now[i]);
70
    }
71
    Serial.println();
72
        
73
	delay(1000);
74
}