#define SDA FP23
#define SCL FP24
void start(void)
// 开始位
{
SDA = 1;
NOP(2);
SCL = 1;
NOP(4);
SDA = 0;
NOP(4);
SCL = 0;
}
void stop(void)
// 停止位
{
SDA = 0;
NOP(2);
SCL = 1;
NOP(4);
SDA = 1;
}
unsigned char shin(void)
// 从AT24Cxx移入数据到MCU
{
unsigned char i,read_data;
SDA=1;
FP23M=0;
for(i = 0; i < 8; i++)
{
SCL = 1;
NOP(2);
read_data <<= 1;
read_data |= (unsigned char)SDA;
SCL = 0;
NOP(3);
}
FP23M=1;
return(read_data);
}
unsigned char shout(unsigned char write_data)
// 从MCU移出数据到AT24Cxx
{
unsigned char i;
//bit ack_bit;
for(i = 0; i < 8; i++) // 循环移入8个位
{
if((write_data & 0x80)==1)
SDA = 1;
else SDA = 0;
NOP(5);
SCL = 1;
NOP(4);
write_data <<= 1;
SCL = 0;
NOP(2);
}
SDA=1;
FP23M=0; // 读取应答
NOP(4);
SCL = 1;
NOP(4);
i = SDA;
SCL = 0;
FP23M=1;
return i; // 返回AT24Cxx应答位
}
void write_byte(unsigned char addr, unsigned char write_data)
// 在指定地址addr处写入数据write_data
{ unsigned char i=0;;
start();
do
{i=shout(0xa0);}
while(i!=0);
do
{i=shout(addr);}
while(i!=0);
do
{i=shout(write_data);}
while(i!=0);
stop();
//delayms(10); // 写入周期
for(i=0;i<250;i++)NOP(1);
for(i=0;i<250;i++)NOP(1);
for(i=0;i<250;i++)NOP(1);
}
unsigned char read_current(void)
// 在当前地址读取
{
unsigned char read_data;
start();
shout(0xa1);
read_data = shin();
stop();
return read_data;
}
unsigned char read_random(unsigned char random_addr)
// 在指定地址读取
{ unsigned char read_data,i;
start();
do i=shout(0xa1);
while(i!=0);
do i=shout(random_addr);
while(i!=0);
/*
start();
do i=shout(0xa1);
while(i!=0);
read_data = shin();
stop();*/
return (read_current());
}
每次读时无法通过循环,在发送字节地址处接收到的反馈是1不是0 |