Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- include <Wire.h>
- #if (ARDUINO >= 100)
- #define WireWrite Wire.write
- #define WireRead Wire.read()
- #else
- #define WireWrite Wire.send
- #define WireRead Wire.receive()
- #endif
- // DS1307 Real Time Clock
- // SDA (pin 5) to Arduino A4
- // SCL (pin 6) to Arduino A5
- #define DS1307_ADDRESS 0x68
- typedef struct {
- byte second;
- byte minute;
- byte hour;
- byte weekDay;
- byte monthDay;
- byte month;
- int year;
- }
- s_dateTime;
- s_dateTime curDateTime;
- byte bcdToDec(byte val) {
- return ((val/16*10)+(val%16));
- }
- byte decToBcd(byte val){
- return ((val/10*16)+(val%10));
- }
- void setDateTime() {
- Wire.beginTransmission(DS1307_ADDRESS);
- WireWrite(0);
- WireWrite(decToBcd(curDateTime.second));
- WireWrite(decToBcd(curDateTime.minute));
- WireWrite(decToBcd(curDateTime.hour));
- WireWrite(decToBcd(curDateTime.weekDay));
- WireWrite(decToBcd(curDateTime.monthDay));
- WireWrite(decToBcd(curDateTime.month));
- WireWrite(decToBcd(curDateTime.year-2000));
- WireWrite(0);
- Wire.endTransmission();
- }
- void updateCurDateTime() {
- static unsigned long last_update = -200;
- if(millis()-last_update>100) {
- Wire.beginTransmission(DS1307_ADDRESS);
- WireWrite(0);
- Wire.endTransmission();
- Wire.requestFrom(DS1307_ADDRESS, 7);
- curDateTime.second = bcdToDec(WireRead);
- curDateTime.minute = bcdToDec(WireRead);
- curDateTime.hour = bcdToDec(WireRead & 0b111111);
- curDateTime.weekDay = bcdToDec(WireRead);
- curDateTime.monthDay = bcdToDec(WireRead);
- curDateTime.month = bcdToDec(WireRead);
- curDateTime.year = bcdToDec(WireRead)+2000;
- if(curDateTime.second & 0b1000000) {
- curDateTime.second = 0; // disable Clock Halt bit on fresh ds1307 chip
- setDateTime();
- }
- }
- }
- void setup()
- {
- Serial.begin(115200);
- Wire.begin();
- curDateTime.year = 2014;
- curDateTime.month = 11;
- curDateTime.monthDay = 24;
- curDateTime.weekDay = 1;
- curDateTime.hour = 23;
- curDateTime.minute = 0;
- curDateTime.second = 0;
- setDateTime();
- delay(200);
- }
- void loop()
- {
- updateCurDateTime();
- Serial.print(curDateTime.hour);
- Serial.print(":");
- Serial.print(curDateTime.minute);
- Serial.print(":");
- Serial.println(curDateTime.second);
- delay(1000);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement