为什么我的程序不能正确读取PCF8583呢?下面附有程序,请大家帮忙看看
#define SDA PTDD_PTDD5
#define SCL PTDD_PTDD6
void I2C_Delay(void) //0.18us*27=4.86us
{
asm("nop");asm("nop");asm("nop");asm("nop");asm("nop");asm"nop");asm("nop");asm("nop");asm("nop");asm("nop");asm("nop");asm("nop");asm("nop");asm("nop");asm("nop");asm("nop");asm
("nop");asm("nop");asm("nop");asm("nop");asm("nop");asm("nop");asm("nop");asm("nop");asm("nop");asm("nop");asm("nop");
}
void I2C_Start(void)
{
PTDDD_PTDDD5=1; //SDA set output
PTDDD_PTDDD6=1; //SCL set output
SDA=1;
I2C_Delay();
SCL=1;
I2C_Delay(); //起始条件建立时间大于4.7us,延时
SDA=0;
I2C_Delay(); //起始条件锁定时间大于4μs
SCL=0;
I2C_Delay();
}
void I2C_Stop(void)
{
PTDDD_PTDDD5=1; //SDA set output
PTDDD_PTDDD6=1; //SCL set output
SDA=0;
I2C_Delay();
//SCL=0;
//I2C_Delay(); //结束条件建立时间大于4μs
SCL=1;
I2C_Delay(); //结束条件建立时间大于4μs
SDA=1;
I2C_Delay(); //结束条件锁定时间大于4.7μs
}
void Write_ACK(void)
{
PTDDD_PTDDD5=1; //SDA set output
PTDDD_PTDDD6=1; //SCL set output
SDA=0;
I2C_Delay();
SCL=1;
I2C_Delay(); //SCL保持高电平大于4μs
SCL=0;
I2C_Delay();
}
void Write_NoAck(void)
{
PTDDD_PTDDD5=1; //SDA set output
PTDDD_PTDDD6=1; //SCL set output
SDA=1;
I2C_Delay();
SCL=1;
I2C_Delay(); //SCL保持高电平大于4μs
SCL=0;
I2C_Delay();
}
void Wait_ACK(void)
{
u8 errtime=20; //20
PTDDD_PTDDD5=1; //SDA set output
PTDDD_PTDDD6=1; //SCL set output
SDA=1;
I2C_Delay();
PTDDD_PTDDD5=0; //SDA set input
SCL=1;
I2C_Delay();
while((SDA==1)&&(errtime>0))
{
errtime--;
if(!errtime)
{
I2C_Stop();
//Led_On();
}
}
SCL=0;
I2C_Delay();
}
void Write_Byte(u8 wdata)
{
u8 i;
PTDDD_PTDDD5=1; //SDA set output
PTDDD_PTDDD6=1; //SCL set output
for(i=0;i<8;i++)
{
if(wdata&0x80) SDA=1;
else SDA=0;
wdata<<=1;
I2C_Delay();
SCL=1;
I2C_Delay(); //SCL保持高电平大于4μs
SCL=0;
I2C_Delay();
}
Wait_ACK();
}
u8 Read_Byte(void)
{
u8 i,bytedata;
PTDDD_PTDDD5=1; //SDA set output
PTDDD_PTDDD6=1; //SCL set output
SDA=1;
PTDDD_PTDDD5=0; //SDA set input
for(i=0;i<8;i++)
{
SCL=1;
I2C_Delay();
bytedata<<=1;
//bytedata|=SDA;
if(SDA) bytedata|=0x01;
SCL=0;
I2C_Delay();
}
return(bytedata);
}
void Write_Data(u8 address,u8 mdata)
{
I2C_Start();
Write_Byte(0xA0); /*写命令*/
Write_Byte(address); /*写地址*/
Write_Byte(mdata); /*写数据*/
I2C_Stop();
}
u8 Read_Data(u8 address) /*单字节选择性读*/
{
u8 rdata;
I2C_Start();
Write_Byte(0xA0); /*写命令*/
Write_Byte(address); /*写地址*/
I2C_Start();
Write_Byte(0xA1); /*读命令*/
rdata=Read_Byte();
Write_NoAck();
I2C_Stop();
return(rdata);
}
void Read_All_Data(u8 address,u8 count,u8 *buff) /*多字节连续读*/
{
u8 i;
I2C_Start();
Write_Byte(0xA0); /*写命令*/
Write_Byte(address); /*写地址*/
I2C_Start();
Write_Byte(0xA1); /*读命令*/
for(i=0;i<count;i++)
{
buff[i]=Read_Byte();
if(i<count-1)
{
Write_ACK();
}
}
Write_NoAck();
I2C_Stop();
}
void P8583_Init(void)
{
Write_Data(0x00,0x00); /*设置状态寄存器 32.768kHz,未屏蔽 禁止报警 */
PTDPE |= 0x60; //内部上拉SDA/SCL线
} |