ABC of Electronics cosycom.com
EMBEDDED SYSTEMS & MICROCONTROLLERS · PAGE 41

Real-Time Clocks

Keeping the date and time.

A real-time clock chip counts seconds from a small 32.768 kHz crystal and holds the date. A coin cell keeps it running when main power is off.

The MCU reads and sets the time over I2C or SPI. Values are often stored as binary-coded decimal, with one decimal digit per four bits, so convert them before use.

Crystal temperature changes cause drift, so correct the time now and then.

EXAMPLE
uint8_t bcd_to_dec(uint8_t b) { return (b >> 4) * 10 + (b & 0x0F); }
uint8_t dec_to_bcd(uint8_t d) { return ((d / 10) << 4) | (d % 10); }