Advertisement
Guest User

Untitled

a guest
Nov 24th, 2014
136
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.24 KB | None | 0 0
  1. include <Wire.h>
  2. #if (ARDUINO >= 100)
  3. #define WireWrite Wire.write
  4. #define WireRead Wire.read()
  5. #else
  6. #define WireWrite Wire.send
  7. #define WireRead Wire.receive()
  8. #endif
  9.  
  10. // DS1307 Real Time Clock
  11. // SDA (pin 5) to Arduino A4
  12. // SCL (pin 6) to Arduino A5
  13. #define DS1307_ADDRESS 0x68
  14. typedef struct {
  15. byte second;
  16. byte minute;
  17. byte hour;
  18. byte weekDay;
  19. byte monthDay;
  20. byte month;
  21. int year;
  22. }
  23. s_dateTime;
  24. s_dateTime curDateTime;
  25.  
  26. byte bcdToDec(byte val) {
  27. return ((val/16*10)+(val%16));
  28. }
  29.  
  30. byte decToBcd(byte val){
  31. return ((val/10*16)+(val%10));
  32. }
  33.  
  34. void setDateTime() {
  35. Wire.beginTransmission(DS1307_ADDRESS);
  36. WireWrite(0);
  37. WireWrite(decToBcd(curDateTime.second));
  38. WireWrite(decToBcd(curDateTime.minute));
  39. WireWrite(decToBcd(curDateTime.hour));
  40. WireWrite(decToBcd(curDateTime.weekDay));
  41. WireWrite(decToBcd(curDateTime.monthDay));
  42. WireWrite(decToBcd(curDateTime.month));
  43. WireWrite(decToBcd(curDateTime.year-2000));
  44. WireWrite(0);
  45. Wire.endTransmission();
  46. }
  47.  
  48. void updateCurDateTime() {
  49. static unsigned long last_update = -200;
  50. if(millis()-last_update>100) {
  51.  
  52. Wire.beginTransmission(DS1307_ADDRESS);
  53. WireWrite(0);
  54. Wire.endTransmission();
  55. Wire.requestFrom(DS1307_ADDRESS, 7);
  56. curDateTime.second = bcdToDec(WireRead);
  57. curDateTime.minute = bcdToDec(WireRead);
  58. curDateTime.hour = bcdToDec(WireRead & 0b111111);
  59.  
  60. curDateTime.weekDay = bcdToDec(WireRead);
  61.  
  62. curDateTime.monthDay = bcdToDec(WireRead);
  63. curDateTime.month = bcdToDec(WireRead);
  64. curDateTime.year = bcdToDec(WireRead)+2000;
  65.  
  66. if(curDateTime.second & 0b1000000) {
  67. curDateTime.second = 0; // disable Clock Halt bit on fresh ds1307 chip
  68. setDateTime();
  69. }
  70. }
  71. }
  72.  
  73. void setup()
  74. {
  75. Serial.begin(115200);
  76. Wire.begin();
  77. curDateTime.year = 2014;
  78. curDateTime.month = 11;
  79. curDateTime.monthDay = 24;
  80. curDateTime.weekDay = 1;
  81. curDateTime.hour = 23;
  82. curDateTime.minute = 0;
  83. curDateTime.second = 0;
  84. setDateTime();
  85. delay(200);
  86. }
  87.  
  88. void loop()
  89. {
  90. updateCurDateTime();
  91. Serial.print(curDateTime.hour);
  92. Serial.print(":");
  93. Serial.print(curDateTime.minute);
  94. Serial.print(":");
  95. Serial.println(curDateTime.second);
  96. delay(1000);
  97. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement