#include <reg52.h>
#include <iic.h>
#include <intrins.h>
#define I2CDelay() {_nop_();_nop_();_nop_();_nop_();}
void
I2CStart()
{
I2C_SDA = 1;
I2C_SCL = 1;
I2CDelay();
I2C_SDA = 0;
I2CDelay();
I2C_SCL = 0;
}
void
I2CStop()
{
I2C_SCL = 0;
I2C_SDA = 0;
I2CDelay();
I2C_SCL = 1;
I2CDelay();
I2C_SDA = 1;
I2CDelay();
}
unsigned
char
I2CWrite(unsigned
char
dat)
{
unsigned
char
ack;
unsigned
char
mask;
for
(mask=0x80; mask!=0; mask>>=1)
{
if
((mask&dat) == 0)
I2C_SDA = 0;
else
I2C_SDA = 1;
I2CDelay();
I2C_SCL = 1;
I2CDelay();
I2C_SCL = 0;
}
I2C_SDA = 1;
I2CDelay();
I2C_SCL = 1;
ack = I2C_SDA;
I2CDelay();
I2C_SCL = 0;
return
(!ack);
}
unsigned
char
I2CReadNAK_OR_ACK(unsigned
char
nak_or_ack)
{
unsigned
char
mask;
unsigned
char
dat;
I2C_SDA = 1;
for
(mask=0x80; mask!=0; mask>>=1)
{
I2CDelay();
I2C_SCL = 1;
if
(I2C_SDA == 0)
dat &= ~mask;
else
dat |= mask;
I2CDelay();
I2C_SCL = 0;
}
I2C_SDA = nak_or_ack;
I2CDelay();
I2C_SCL = 1;
I2CDelay();
I2C_SCL = 0;
return
dat;
}
void
E2Read(unsigned
char
*buf, unsigned
char
addr, unsigned
char
len)
{
do
{
I2CStart();
if
(I2CWrite(0x50<<1))
{
break
;
}
I2CStop();
}
while
(1);
I2CWrite(addr);
I2CStart();
I2CWrite((0x50<<1)|0x01);
while
(len > 1)
{
*buf++ = I2CReadNAK_OR_ACK(0);
len--;
}
*buf = I2CReadNAK_OR_ACK(1);
I2CStop();
}
void
E2Write(unsigned
char
*buf, unsigned
char
addr, unsigned
char
len)
{
while
(len > 0)
{
do
{
I2CStart();
if
(I2CWrite(0x50<<1))
{
break
;
}
I2CStop();
}
while
(1);
I2CWrite(addr);
while
(len > 0)
{
I2CWrite(*buf++);
len--;
addr++;
if
((addr&0x07) == 0)
{
break
;
}
}
I2CStop();
}
}