主函数文件:
#include <reg52.h>
#include "./delay/delay.h"
sbit SCL = P2^1;
sbit SDA = P2^2;
bit ack = 0;
#define SUCC 1
#define ERR 0
void iic_start()
{
SDA = 1;
SCL = 1;
delay_us(1);
SDA = 0;
delay_us(1);
SCL = 0;
}
void iic_stop()
{
SDA = 0;
SCL = 1;
delay_us(1);
SDA = 1;
delay_us(1);
SCL = 0;
}
bit iic_send_byte(unsigned char byte)
{
unsigned char i;
for(i = 0; i < 8; i++)
{
SDA = byte & 0x80;
SCL = 1;
delay_us(1);
SCL = 0;
delay_us(1);
byte <<= 1;
}
SCL = 1;
SDA = 1;
delay_us(1);
if(0 == SDA)
{
ack = 1;
}
else
{
ack = 0;
}
SCL = 0;
return ack;
}
unsigned char iic_rcv_byte()
{
unsigned char i;
unsigned char temp;
unsigned char a;
SDA = 1;
for(i = 0; i < 8; i++)
{
SCL = 0;
delay_us(1);
SCL = 1;
if(SDA)
{
a = 0x01;
}
else
{
a = 0;
}
temp |= (a <<(7 - i));
delay_us(1);
}
SCL = 0;
return temp;
}
void iic_ack()
{
SDA = 0;
SCL = 1;
delay_us(1);
SCL = 0;
}
void iic_noack()
{
SDA = 1;
SCL = 1;
delay_us(1);
SCL = 0;
}
unsigned char AT24C02_send_str(unsigned char devaddr,unsigned char romaddr,unsigned char *s,unsigned char num)
{
unsigned char i;
iic_start();
iic_send_byte(devaddr);
if(0 == ack) return ERR;
iic_send_byte(romaddr);
if(0 == ack) return ERR;
for(i = 0; i < num; i++)
{
iic_send_byte(*s);
if(0 == ack) return ERR;
s++;
}
iic_stop();
return SUCC;
}
unsigned char AT24C02_rcv_byte(unsigned char devaddr,unsigned char romaddr,unsigned char *s,unsigned char num)
{
unsigned char i;
iic_start();
iic_send_byte(devaddr);
if(0 == ack) return ERR;
iic_send_byte(romaddr);
if(0 == ack) return ERR;
iic_start();
iic_send_byte(devaddr + 1);
for(i = 0; i < num - 1; i++)
{
*s = iic_rcv_byte();
iic_ack();
s++;
}
*s = iic_rcv_byte();
iic_noack();
iic_stop();
return SUCC;
}
void main()
{
unsigned char test[10] = {'1','2','3','4','5','6','7','8','9'};
unsigned char temp[10];
AT24C02_send_str(0xae,100,test,10);
delay_ms(200);
AT24C02_rcv_byte(0xae,100,temp,10);
while(1)
{
iic_start();
iic_send_byte(0xae);
iic_stop();
delay_ms(5);
}
}
void delay_us(unsigned char t)
{
while(--t);
}
void delay_ms(unsigned char t)
{
while(t--)
{
delay_us(245);
delay_us(245);
}
}
void delay_s(unsigned char t)
{
while(t--)
{
delay_ms(200);
delay_ms(200);
delay_ms(200);
delay_ms(200);
delay_ms(200);
}
}