my prototype PCF8563's library
Fork of PCF8563 by
PCF8563.cpp
- Committer:
- irsanjul
- Date:
- 2016-01-22
- Revision:
- 0:47c63ed3af91
- Child:
- 1:bcea5c3f58f4
File content as of revision 0:47c63ed3af91:
#include "mbed.h" #include "PCF8563.h" extern Serial dbg; PCF8563::PCF8563(PinName sda, PinName scl) : pcf8563_i2c (sda, scl) { pcf8563_i2c.frequency(PCF8563_FREQ); } time_t PCF8563::now() { struct tm now; char start = 0x02; char buffer[7]; if(pcf8563_i2c.write(W8563_ADDR, &start, 1) != 0) return 0; if(pcf8563_i2c.read(R8563_ADDR, buffer, 7) != 0) return 0; now.tm_sec = bcdToDecimal(buffer[0] & 0x7F); now.tm_min = bcdToDecimal(buffer[1] & 0x7F); now.tm_hour = bcdToDecimal(buffer[2] & 0x3F); now.tm_mday = bcdToDecimal(buffer[3] & 0x3F); now.tm_mon = bcdToDecimal(buffer[5] & 0x1F) - 1; now.tm_year = bcdToDecimal(buffer[6]) + 2000 - 1900; return mktime(&now); } bool PCF8563::set_time(time_t time) { struct tm *now; char buffer[8]; now = localtime(&time); buffer[0] = 0x02; // memory address buffer[1] = decimalToBcd(now->tm_sec) & 0x7F; // VL = 0 buffer[2] = decimalToBcd(now->tm_min) & 0x7F; buffer[3] = decimalToBcd(now->tm_hour) & 0x3F; buffer[4] = now->tm_wday + 1; buffer[5] = decimalToBcd(now->tm_mday) & 0x3F; buffer[6] = decimalToBcd(now->tm_mon+1) & 0x1F; buffer[7] = decimalToBcd(now->tm_year + 1900 - 2000); if(pcf8563_i2c.write(W8563_ADDR, buffer, 9) != 0) return 0; return true; } bool PCF8563::set_alarm(time_t time) { struct tm *now; char buffer[5]; now = localtime(&time); buffer[0] = 0x09; // memory address buffer[1] = decimalToBcd(now->tm_min) & 0x80; buffer[2] = decimalToBcd(now->tm_hour) & 0x80; buffer[3] = decimalToBcd(now->tm_mday) & 0x80; buffer[4] = (now->tm_wday + 1) & 0x80; if(pcf8563_i2c.write(W8563_ADDR, buffer, 4) != 0) return 0; char Int[2]; Int[0] = 0x01; // control address Int[1] = 0x02; // set AIE to 1 for INT pin if(pcf8563_i2c.write(W8563_ADDR, Int, 2) != 0) return 0; return true; } bool PCF8563::alarmOff() { char start = 0x01; char buffer; if(pcf8563_i2c.write(W8563_ADDR, &start, 1) != 0) return 0; //if(pcf8563_i2c.read(R8563_ADDR, buffer, 1) != 0) return 0; pcf8563_i2c.start(); pcf8563_i2c.write(R8563_ADDR); buffer = pcf8563_i2c.read(0); pcf8563_i2c.stop(); buffer = buffer - 0x08; // clear AF to turn off alarm char send[2]; send[0] = 0x01; //control 1 address send[1] = buffer; if(pcf8563_i2c.write(W8563_ADDR, send, 2) != 0) return 0; return true; } bool PCF8563::check_alarm() { char start = 0x01; char buffer; if(pcf8563_i2c.write(W8563_ADDR, &start, 1) != 0) return 0; //if(pcf8563_i2c.read(R8563_ADDR, buffer, 1) != 0) return 0; pcf8563_i2c.start(); pcf8563_i2c.write(R8563_ADDR); buffer = pcf8563_i2c.read(0); pcf8563_i2c.stop(); buffer = buffer & 0x08; if(buffer == 0x08) { dbg.printf("== ALARM ON ==\r\n"); wait_ms(200); alarmOff(); } return true; }