DS1302 always gets 255 when reading seconds (all return high)

        code show as below

foreword

       When using the single-chip microcomputer of the Blue Bridge Cup single-chip competition, I found that ds1302 only returned high level. I searched a lot of results on the Internet but couldn't find the reason. After continuous debugging and comparison, I finally found the reason.

#include <REGX52.H>
#include "DS1302.h"
#include "LCD1602.h"
 unsigned char a;

int main()
{
     LCD_Init();
     DS1302_Init();
    while(1)
    {
    a=DS1302_ReadByte(0x80);
     LCD_ShowNum(1,1,a,3);
    }
}
#include <REGX52.H>
sbit DS1302_SCLK=P3^6;
sbit DS1302_IO=P3^4;
sbit DS1302_CE=P3^5;
unsigned char DS1302_ReadByte(unsigned char Command)
{
	unsigned char i,Data=0x00;
	Command|=0x01;	//将指令转换为读指令
	DS1302_CE=1;
	for(i=0;i<8;i++)
	{
		DS1302_IO=Command&(0x01<<i);
		DS1302_SCLK=0;
		DS1302_SCLK=1;
	}
	for(i=0;i<8;i++)
	{
		DS1302_SCLK=1;
		DS1302_SCLK=0;
		if(DS1302_IO){Data|=(0x01<<i);}
	}
	DS1302_CE=0;
	DS1302_IO=0;	//读取后将IO设置为0,否则读出的数据会出错
	return Data;
}

reason:

         1. The write protection of the chip has not been lifted. (This is the result generally found on the Internet)

         2. The initial value is not written into the hour, minute and second. (This is the result of my experiment)

Solution:

        1. Write the release code Write_Ds1302_Byte(0x8E,0x00) before the main function; note that 0x00 is to release the write protection, and 0x80 is to add write protection, and the operations on the chip after writing 0x80 are invalid;

        2. Assign an initial value to ds1302, even if it is 0.

Guess you like

Origin blog.csdn.net/wcl501375/article/details/128906004