Sample program to set the time on the Real Time Clock, and to read the
time
#define RTC_READ_SECONDS 0x20
#define RTC_WRITE_SECONDS 0xa0
void put_spi(unsigned char c);
unsigned char get_spi(void);
main()
{
int i;
unsigned char time_data[] =
{0x00, /* Seconds: Address 0x20 0xA0 */
0x10, /* Minutes: Address 0x21 0xA1 */
0x14, /* Hours: Address 0x22 0xA2 */
0x04, /* Day of Week: Address 0x23 0xA3 */
0x03, /* Date of Month: Address 0x24 0xA4 */
0x04, /* Month: Address 0x25 0xA5 */
0x98, /* Year: Address 0x26 0xA6 */
0x00, /* Unused: Address 0x27 0xA7 */
0x00, /* Seconds Alarm: Address 0xA8 */
0x00, /* Minutes Alarm: Address 0xA9 */
0x07, /* Hours Alarm: Address 0xAA */
0x00, /* Unused: Address 0x2B 0xAB */
0x00, /* Unused: Address 0x2C 0xAC */
0x00, /* Unused: Address 0x2D 0xAD */
0x00, /* Unused: Address 0x2E 0xAE */
0x00, /* Unused: Address 0x2F 0xAF */
0x00, /* Status: Address 0x30 */
0x??, /* Interuupt Cntl: Address 0x31 0xB1 */
0x??}; /* Clock Control: Address 0x32 0xB2 */
/* Put SPI setup in here */
/* Write time to RTC */
PORTD |= 0x20; /* Select RTC */
put_spi(RTC_WRITE_SECONDS); /* Send address of seconds */
i = 0;
while (i <= 0x12)
{
put_spi(time_data[i]);
i = i + 1;
}
PORTD &= ~0x20; /* Deselect RTC */
/* Read time from RTC */
PORTD |= 0x20; /* Select RTC */
put_spi(RTC_READ_SECONDS); /* Send address of seconds */
i = 0;
while (i <= 7)
{
time_data[i] = get_spi();
i = i + 1;
}
PORTD &= ~0x20; /* Deselect RTC */
}
/* Function to send a byte to the Serial Peripheral Interface */
void put_spi(unsigned char c)
{
SPSR; /* First step in clearing SPIF */
SPDR = c; /* Send char over SPI */
while ((SPSR & 0x80) == 0) ; /* Wait for transfer to complete */
}
/* Function to read a byte from the Serial Peripheral Interface */
unsigned char get_spi(void)
{
SPSR; /* First step in clearing SPIF */
SPDR = 0; /* Send junk byte over SPI */
while ((SPSR & 0x80) == 0) ; /* Wait for transfer to complete */
return SPDR; /* Return byte read */
}