DS1302与430接口程序
--------------------------------------------------------------------------------
#include <msp430x14x.h>
#include <math.h>
#define uchar unsigned char
#define uint unsigned int
#define DS1302_CLK_High P2OUT |=BIT4
#define DS1302_CLK_Low P2OUT &=~BIT4
#define DS1302_IO_High P2OUT |= BIT3
#define DS1302_IO_Low P2OUT &= ~BIT3
#define DS1302_CE_High P2OUT |= BIT2
#define DS1302_CE_Low P2OUT &= ~BIT2
#define DS1302_IO_IN P2DIR &= ~BIT3
#define DS1302_IO_OUT P2DIR |= BIT3
#define SomeNOP() _NOP();_NOP();_NOP();_NOP();_NOP();
char cur_time[7]={0x45,0x18,0x16,0x28,0x03,0x02,0x10};
//sec,min, hour,date,month,week,year//
/*get time from ds1302 related function*/
void spi_write(uchar byte1)
{
char count=8;
do
{
DS1302_CLK_Low;
if(byte1&0x01)
DS1302_IO_High;
else
DS1302_IO_Low;
DS1302_CLK_High;
SomeNOP();
byte1>>=1;
}while(--count);
}
uchar spi_read(void)
{
uchar count=8;
uchar data=0;
DS1302_IO_IN;
do
{
data>>=1;
DS1302_CLK_Low;
SomeNOP();
if(P2IN&BIT3)
data|=0x80;
DS1302_CLK_High;
SomeNOP();
}while(--count);
return(data);
}
void set_time(uchar addr,uchar time)
{
uchar time1=0;
DS1302_CE_High;
spi_write(0x8e);
spi_write(0x00);
DS1302_CLK_Low;
DS1302_CE_Low;
_NOP();
DS1302_CE_High;
_NOP();
spi_write(addr);
spi_write(time);
spi_write(0x8e);
spi_write(0x80);
DS1302_CLK_Low;
DS1302_CE_Low;
}
void init_time(void)//burst write mode
{
uchar i=0;
DS1302_CE_High;
spi_write(0x8e);
spi_write(0x00);
DS1302_CLK_Low;
DS1302_CE_Low;
_NOP();
DS1302_CE_High;
_NOP();
spi_write(0xbe);
for(i=0;i<7;i++)
spi_write(cur_time[i]);
spi_write(0x8e);
spi_write(0x80);
DS1302_CLK_Low;
DS1302_CE_Low;
}
void get_time(void)
{
uchar i=0;
DS1302_CE_High;
SomeNOP();
spi_write(0xbf);
for(i=0;i<7;i++)
cur_time[i]=spi_read();
DS1302_CLK_Low;
DS1302_CE_Low;
DS1302_IO_OUT;
}
void main(void)
{
WDTCTL = WDTPW + WDTHOLD; // Stop watchdog timer
P2DIR|=0x1c;
P2OUT&=0xe3;
init_time();
get_time();
set_time(0x8c,05);
while(1)
{get_time();}
}