|
给一个以前能用的你参考一下
- #include
- #include
- #define MULTI_ROM_EN 0
- sbit TIMERST =P1^2;
- sbit TIMECLK =P1^1;
- sbit TIMEIO =P1^0;
- //打开DS1302
- void TimeSpiOpen(void)
- {
- TIMECLK = 0;
- TIMERST = 0;//禁止DS1302
- TIMEIO = 1;//释放数据总线
- TIMERST = 1;//使能DS1302
- }
- //关闭DS1302
- void TimeSpiClose(void)
- {
- TIMERST = 0;//禁止DS1302
- TIMEIO = 1;//释放数据总线
- TIMECLK = 1;
- }
- //读写DS1302
- unsigned char TimeSpiReadWrite(unsigned char val)
- {
- extern void _rrca(void);
- unsigned char i;
- ACC = val;//取8位数据
- for (i = 8;i > 0; i--)
- {
- TIMECLK = 0;//时钟下降沿输入数据(DS1302读)
- _nop_();//延时
- CY = TIMEIO;//接收串行数据到CY
- #pragma asm
- RRC A //右移一位数据到CY(先存后取)
- #pragma endasm
- TIMEIO = CY;//发送串行数据
- TIMECLK = 1;//时钟上升沿打入数据(DS1302写)
- TIMEIO = 1;//释放数据总线
- }
- val = ACC;
- return val;
- }
- //读DS1302字节
- unsigned char TimeByteRead(unsigned char address)
- {
- TimeSpiOpen();//打开DS1302
- TimeSpiReadWrite(address);//写入DS1302命令
- address = TimeSpiReadWrite(0xff);//读入DS1302数据
- TimeSpiClose();//关闭DS1302
- return address;//返回数据
- }
- //读DS1302RAM字节
- #if MULTI_ROM_EN > 0
- unsigned char TimeRamByteRead(unsigned char address)
- {
- TimeSpiOpen();//打开DS1302
- TimeSpiReadWrite((address << 1) | 0xc1);//写入DS1302命令
- address = TimeSpiReadWrite(0xff);//读入DS1302数据
- TimeSpiClose();//关闭DS1302
- return address;//返回数据
- }
- #endif
- //写DS1302字节
- void TimeByteWrite(unsigned char address, unsigned char val)
- {
- TimeSpiOpen();//打开DS1302
- TimeSpiReadWrite(address);//写地址
- TimeSpiReadWrite(val);//写数据
- TimeSpiClose();//关闭DS1302
- }
- //写DS1302RAM字节
- #if MULTI_ROM_EN > 0
- void TimeRamByteWrite(unsigned char address, unsigned char val)
- {
- TimeSpiOpen();//打开DS1302
- TimeSpiReadWrite((address << 1) | 0xc0);//写地址
- TimeSpiReadWrite(val);//写数据
- TimeSpiClose();//关闭DS1302
- }
- #endif
- //使能DS1302写保护
- void TimeWriteEnable(void)
- {
- TimeByteWrite(0x8e,0x80);//使能DS1302写保护
- }
- //开放DS1302写保护
- void TimeWrieDisbale(void)
- {
- TimeByteWrite(0x8e,0);//开放DS1302写保护
- }
- //DS1302工作开始
- void TimeWorkStart(void)
- {
- unsigned char val;
- TimeWrieDisbale();//开放DS1302写保护
- TimeByteWrite(0x8c, 0x00); //清零年,月,日,时,分,秒
- TimeByteWrite(0x8a, 0x00);
- TimeByteWrite(0x88, 0x00);
- TimeByteWrite(0x86, 0x00);
- TimeByteWrite(0x84, 0x00);
- TimeByteWrite(0x82, 0x00);
- TimeByteWrite(0x80, 0x00);
- val = TimeByteRead(0x81);//读秒寄存器数据
- val &= 0x7f;//打开振荡器
- TimeByteWrite(0x80, val);//打开振荡器
- TimeByteWrite(0x90, 0xa5);//打开充电二极管
- val = TimeByteRead(0x85);//读时寄存器数据
- val &= 0x3f;//24小时制
- TimeByteWrite(0x84, val);//24小时制
- TimeWriteEnable();//使能DS1302写保护
- }
复制代码 |
|