RTC Implementation

RTC

Data Sheet

https://www.analog.com/media/en/technical-documentation/data-sheets/DS1307.pdf

Circuit

RTC

Protocol Overview

  • Bus Address (Page 12)
  • 1101000
  • LSB
    • 0 Read
    • 1 Write

Addressing Constants

int CLOCK_READ = 0xD1;
int CLOCK_WRITE = 0xD0;

I2C Communications

https://os.mbed.com/docs/mbed-os/v6.16/apis/i2c.html

I2C i2c(I2C_SDA , I2C_SCL);

Reading the Time

Reading the Time

RTC Read

Reading the Time

  • Read will return the last register used. (pg 12, point 2)
  • This may be something different to seconds
  • Write a 0 to set seconds register as expected

Writing a Start Byte

 int status;
  //Send Start Signal to I2C
  i2c.start();

  //Write Seconds
  status = i2c.write(CLOCK_WRITE);
  printf("Status was %d\n", status);  //Debugging check acknowledgement
  i2c.write(0x00) ; //Seconds Register

  //Send Read Signal
  i2c.stop();

Fetching the Rest of the data

  • Clock Will now return all 7 time registers sequentially.
  • First 6 Receives should have an ACK
  • Final one should not

Fetching the Rest of the Data

 i2c.start();

  status = i2c.write(CLOCK_READ);     /* slave address with read mode */
  printf("Read Status was %d\n", status); //Check for Ack
  int  seconds = i2c.read(1);  // Read the slave with ACK
  int  minutes= i2c.read(1);
  int  hour = i2c.read(1);
  int  day = i2c.read(1);
  int   date = i2c.read(1);
  int   month = i2c.read(1);
  int  year = i2c.read(0);     // Read the slave with not-ACK 

  //Stop
  i2c.stop();

Processing Data

RTC Registers

Processing Data

  • Data is in BCD format
  • Seconds have an Junk Bit in Bit 7

Processing Data

  • Remove MSB from Seconds with logical AND
int newSeconds = seconds & 0x7f;

Processing Data BCD

int bcdtodec( int bcd) {
    int low = 0;
    int high = 0;
    high = bcd / 16;
    low = bcd - (high * 16);
    return ((high * 10) + low);
}

Using a library

Using a Library

  • Driver Code can be hard
  • Fortunately we have a working library
  • (Code in GitHub)

Reading the API

  • https://os.mbed.com/teams/Iot-Ox/code/RTC-DS1307/docs/tip/

Using the API

#include "Rtc_Ds1307.h"

Rtc_Ds1307 rtc(I2C_SDA, I2C_SCL);

Using the API, Setting the Initial Time

  Rtc_Ds1307::Time_rtc rtcTime;
  
  rtcTime.year=2023;
  rtcTime.date=23;
  rtcTime.mon=3;
  rtcTime.hour=12;
  rtcTime.min=30;
  rtcTime.sec = 12;

  rtc.setTime(rtcTime, true, false);

Using the API, Reading the Time

rtc.getTime(rtcTime);

printf("%d:%d:%d  Year %d\n", rtcTime.hour, rtcTime.min, rtcTime.sec, rtcTime.year);

Task

  • Grab the Code from Github
  • Try interfacing with the RTC board.
  • Try to work out how to set the clock to compile time.
    • Get Compilation time….
    • printf(“
// reveal.js plugins