/* SPI code for interfacing w/ SPI Real Time Clock chip Pin Description 1 - X1 - 32.768 kHz crystal input 2 - X2 - crystal output 3 - ~RST - reset Output - NC - low if RSTIN1 or RSTIN2 is low, if VCC falls below Vpfd 4 - WDI - watchdog input - NC 5 - ~RSTIN1 - reset input one (active low) - NC 6 - ~RSTIN2 - reset input two (active low) - NC 7 - VBAT - battery voltage - ~3V, battery GND common w/ VSS 8 - VSS - hook up to GND 9 - SDO - Serial Data Output (hooked up to B6 - MISO) 10 - SCL - Serial CLK (hooked up to B7 - SCK) - Max = 2 MHz 11 - SQW - Square Wave Output - NC 12 - SDI - Serial Data Input (hooked up to B5 - MOSI) 13 - TH - Power Off threshold select - set to GND 14 - NC 15 - ~E - Chip Enable (active low) - Hook up to B4 16 - VCC - 5V Notes - When VCC falls below Vpfd (power failure detect), E becomes disabled & high impedance resulting in severed communication until VCC restored. Power is switched over to battery at this time and clock will continue to increment. E remains disabled for ~0.1 s after VCC restored - need to wait some time before reads & writes can be made */ #include "spi_rtc.h" //returns read result from a specified RTC register unsigned char spi_read_reg (unsigned char reg){ unsigned char read; //temp variable for storing spi read PORTB.4=0; spi(reg); read = spi(0x00); PORTB.4=1; return read; } //writes byte to specified RTC register void spi_write_reg (unsigned char reg, unsigned char data){ PORTB.4=0; spi((0x80 | reg)); spi(data); PORTB.4=1; } //Initialize the RTC void spi_init(void){ unsigned char temp; // Set SPI CTRL & Status reg SPCR=0b01011101; //MCU is master, SPI enabled, MSB first, SCK = 1 MHz SPSR=0x00; //2xCK = off PORTB.4=1; //Chip Disabled PORTB.5=1; PORTB.6=1; PORTB.7=1; while((spi_read_reg(0x02)==0xFF)); //while E is high resistance spi_write_reg(0x0C,0x00); //Turn off HT bit temp = spi_read_reg(0x01); //Read seconds reg spi_write_reg(0x01,(temp & 0x7F)); //Turn off ST bit }