⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 ds1302.c

📁 内部HFGHGFHGFHGFHGFHGFHGFHGFHG
💻 C
字号:
#include "config.h"

sbit   RST  = P0^3;
sbit   IO   = P0^4;
sbit   CLOCK=P0^5;

uint8   ReadTimeCnt;
uint8   sec,min,hour,day,month,year;



void    reset_3w(void);
void    wbyte_3w(uint8 W_Byte);
uint8	rbyte_3w(void);

void    WriteByte(uint8 add, uint8 sdata);
uint8   ReadByte(uint8 addr);
void    ReadTime(void);
void    Ds1302Init(void);

void    reset_3w(void)	/* ----- reset and enable the 3-wire interface ------ */
{
   	CLOCK = 0;
    RST   = 0;
   	RST   = 1;
}


void    wbyte_3w(uint8 W_Byte)	/* ------ write one byte to the device ------- */
{
    uint8 i;
	for(i = 0; i < 8; i++)
    {
	    IO = 0;
	    if(W_Byte & 0x01)
		{
			IO = 1;	/* set port pin high to read data */
		}
	    CLOCK = 0;
    	CLOCK = 1;
	    W_Byte >>= 1;
    }
}
uint8 	rbyte_3w(void)	/* ------- read one byte from the device -------- */
{
    uint8  i;
    uint8  R_Byte;
    uint8  TmpByte;
	R_Byte = 0x00;
	IO = 1;
	for(i = 0; i < 8; i++)
    {
	    CLOCK = 1;
	    CLOCK = 0;
	    TmpByte = (uint8)IO;
	    TmpByte <<= 7;
	    R_Byte >>= 1;
	    R_Byte |= TmpByte;
    }
	return R_Byte;
}






void WriteByte(uint8 add, uint8 sdata)
{
	reset_3w();
	wbyte_3w(add);
	wbyte_3w(sdata);
	reset_3w();
}

uint8 ReadByte(uint8 addr)
{   
    uint8 readtemp;
	reset_3w();
	wbyte_3w(addr);
	readtemp = rbyte_3w();
	reset_3w();
	return readtemp;
}


void    Ds1302Init(void)
{
	WriteByte(0x8e,0x00);          //写使能
    sec   = ReadByte(DS1302SEC_R) & 0x7f;      // clk_sec
	min   = ReadByte(DS1302MIN_R) & 0x7f;      // clk_min 1 0 0 0 0 0 1 1
	hour  = ReadByte(DS1302HOUR_R) & 0x3f;      // clk_hour

	day   = ReadByte(DS1302DAY_R) & 0x3f;      // clk_day
    if(day==0)
    {
        day=1;
    }
	month = ReadByte(DS1302MONTH_R);      // clk_month
    if(month==0)
    {
        month=1;
    }
	year  = ReadByte(DS1302YEAR_R);      // clk_year*/


    WriteByte(DS1302SEC_W,sec);            //秒,并且启动时钟
    WriteByte(DS1302MIN_W,min);            //分
    WriteByte(DS1302HOUR_W,hour);           //时
    WriteByte(DS1302DAY_W,day);            //日
    WriteByte(DS1302MONTH_W,month);          //月
    WriteByte(DS1302YEAR_W,year);           //年
}




void    ReadTime(void)
{
    if( ReadTimeCnt > 20 )
    {
        ReadTimeCnt = 0;
        sec   = ReadByte(DS1302SEC_R)&0x7f;
        min   = ReadByte(DS1302MIN_R)&0x7f;
        hour  = ReadByte(DS1302HOUR_R)&0x3f;
        day   = ReadByte(DS1302DAY_R)&0x3f;
        month = ReadByte(DS1302MONTH_R)&0x1f;
        year  = ReadByte(DS1302YEAR_R)&0xff;
    }
}


⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -