test rtc

PCF85263AT.cpp

Committer:
irsanjul
Date:
2020-06-17
Revision:
0:fa906a89a756

File content as of revision 0:fa906a89a756:

#include "mbed.h"
#include "PCF85263AT.h"

extern Serial dbg;

PCF85263AT::PCF85263AT(PinName sda, PinName scl) : i2c (sda, scl)
{
    i2c.frequency(100000);
}

PCF85263AT::~PCF85263AT()
{
    
}

bool PCF85263AT::write(char adr, char data)
{
    w[0] = adr;
    w[1] = data;
    if (i2c.write(address, w, 2) != 0) return 0;
    
    return true;
}

char PCF85263AT::read(char adr)
{
    char start = adr;
    if (i2c.write(address, &start, 1, true) != 0) return 0;
    if (i2c.read(address, r, 1) != 0) return 0;
    
    return r[0];
}

time_t PCF85263AT::now()
{
    struct tm now;
    
    char buffer[6];
    
    buffer [0] = read(SEC);
    buffer [1] = read(MIN);
    buffer [2] = read(HOUR);
    buffer [3] = read(DAY);
    buffer [4] = read(MONTH);
    buffer [5] = read(YEAR);
    
    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[4] & 0x1F) - 1;
    now.tm_year = bcdToDecimal(buffer[5] & 0xFF) + 2000 - 1900;
    
    return mktime(&now);
}

bool PCF85263AT::set_time(time_t time)
{
    struct tm *now;
    char buffer[9];
    
    now = localtime(&time);
	
	// send stop signal
	buffer[0] = 0x01;
	if(!write(STOPEN, buffer[0]))return 0;
	
	// clear prescaler
	buffer[0] = 0xA4;
	if(!write(RESET, buffer[0]))return 0;
	
    // set time
    buffer[0] = decimalToBcd(now->tm_sec) & 0x7F; // VL = 0
    buffer[1] = decimalToBcd(now->tm_min) & 0x7F;
    buffer[2] = decimalToBcd(now->tm_hour) & 0x3F;
    buffer[3] = decimalToBcd(now->tm_mday) & 0x3F;
    buffer[4] = now->tm_wday + 1;
    buffer[5] = decimalToBcd(now->tm_mon+1) & 0x1F;
    buffer[6] = decimalToBcd(now->tm_year + 1900 - 2000);
    
    if(!write(SEC, buffer[0]))return 0;
    if(!write(MIN, buffer[1]))return 0;
    if(!write(HOUR, buffer[2]))return 0;
    if(!write(DAY, buffer[3]))return 0;
    if(!write(WDAY, buffer[4]))return 0;
    if(!write(MONTH, buffer[5]))return 0;
    if(!write(YEAR, buffer[6]))return 0;
	
	// clear stop signal
	buffer[0] = 0x00;
	if(!write(STOPEN, buffer[0]))return 0;
    
    return true;
}

bool PCF85263AT::IsConnected()
{
    bool ok = false;
    
    i2c.start();
    i2c.stop();
    
    if (i2c.read(address, &data[0], 1) != 0)
    {
//        dbg.printf("PCF85263AT is not detected\r\n");
        ok = false;
    }
    else
    {
//        dbg.printf("PCF85263AT is detected\r\n");
        ok = true;
    }
        
    data[0] = 0;
    i2c.start();
    i2c.stop();
    
    return ok;
}

bool PCF85263AT::software_reset()
{
    char buffer = 0x2C;
    
    if(!write(RESET, buffer)) return 0;
    
    return 1;
}