libpropeller
Making PropellerGCC Easier
 All Classes Files Functions Variables Enumerations Enumerator Macros Pages
pcf8523.h
Go to the documentation of this file.
1 #ifndef LIBPROPELLER_PCF8523_H_
2 #define LIBPROPELLER_PCF8523_H_
3 
4 #include <propeller.h>
5 #include "libpropeller/i2c/i2c.h"
6 
20 class PCF8523 {
21 public:
22 
26  PCF8523() {
27  bus_ = NULL;
28  status_ = false;
29  }
30 
65  bool Init(I2C * newbus) {
66  bus_ = newbus;
67  GetStatus();
68  if (status_ == false) {
69  return false; //No device
70  }
71 
72  //Initialize the device
73  bus_->Put(kDeviceAddress, kCONTROL_1, 0b10000000);
74  bus_->Put(kDeviceAddress, kCONTROL_2, 0b00000000);
75  bus_->Put(kDeviceAddress, kCONTROL_3, 0b00000000);
76  return status_;
77  }
78 
83  bool GetStatus() {
84  if (bus_ == NULL) {
85  status_ = false;
86  } else {
87  status_ = bus_->Ping(kDeviceAddress);
88  }
89  return status_;
90  }
91 
109  bool SetClock(const int year, const int month, const int day,
110  const int hour, const int minute, const int second, const int weekday = 0) {
111  if (!status_) {
112  return false;
113  }
114 
115  char clock[7];
116  clock[0] = ConvertToBCD(second);
117  clock[1] = ConvertToBCD(minute);
118  clock[2] = ConvertToBCD(hour);
119  clock[3] = ConvertToBCD(day);
120  clock[4] = ConvertToBCD(weekday);
121  clock[5] = ConvertToBCD(month);
122  clock[6] = ConvertToBCD(year);
123 
124  clock[0] &= 0b01111111; //Clear OS bit
125 
126  bus_->Put(kDeviceAddress, kSECONDS, clock, 7);
127 
128  return true;
129  }
130 
144  bool GetClock(int & year, int & month, int & day,
145  int & hour, int & minute, int & second, int & weekday) {
146  if (!status_) {
147  return false;
148  }
149 
150  char clock[7];
151  bus_->Get(kDeviceAddress, kSECONDS, clock, 7);
152  second = ConvertFromBCD(clock[0]);
153  minute = ConvertFromBCD(clock[1]);
154  hour = ConvertFromBCD(clock[2]);
155  day = ConvertFromBCD(clock[3]);
156  weekday = ConvertFromBCD(clock[4]);
157  month = ConvertFromBCD(clock[5]);
158  year = ConvertFromBCD(clock[6]);
159 
160  return true;
161  }
162 
175  bool GetClock(int & year, int & month, int & day,
176  int & hour, int & minute, int & second) {
177  int temp;
178  return GetClock(year, month, day, hour, minute, second, temp);
179  }
180 
181 
182 private:
183  I2C * bus_;
184  bool status_;
185 
186 
187  const static unsigned char kDeviceAddress = 0b11010000;
188 
189  const static unsigned char kCONTROL_1 = 0x00;
190  const static unsigned char kCONTROL_2 = 0x01;
191  const static unsigned char kCONTROL_3 = 0x02;
192  const static unsigned char kSECONDS = 0x03;
193 
203  char ConvertToBCD(const int number) const {
204  int unit = number % 10;
205  int tens = (number % 100) / 10;
206 
207  return (tens << 4) | unit;
208  }
209 
218  int ConvertFromBCD(const unsigned char bcd) const {
219  return ((bcd >> 4) * 10) + (bcd & 0xF);
220  }
221 
222 public:
223  friend class UnityTests;
224 };
225 
226 
227 #endif // LIBPROPELLER_PCF8523_H_