#include<avr/io.h>
#define uchar unsigned
char
#define uint
unsigned int
#define setbit(sfr,bit)
(sfr|=(1<<bit))
#define clrbit(sfr,bit)
(sfr&=~(1<<bit))
#define SDA_out()
setbit(DDRD,0)
//设置SDA为输出
#define SCL_out()
setbit(DDRD,2)
//设置SCL为输出
#define
SDA_in()
clrbit(DDRD,0)
//设置SDA为输入
#define SDA_high()
setbit(PORTD,0)
//设置SDA为高电平
#define SDA_low()
clrbit(PORTD,0)
//设置SDA为低电平
#define SCL_high()
setbit(PORTD,2)
//设置SCL为高电平
#define SCL_low()
clrbit(PORTD,2) //设置SCL为低电平
void delay_us(uchar t)
{
uchar i;
for(i=0;i<t;i++);
}
void delay_ms(uchar m)
{
uchar i;
for(i=0;i<m;i++)
{
delay_us(250);
//延时250us
delay_us(250);
delay_us(250);
delay_us(250);
}
}
void init()
{
SDA_out();
SCL_out();
//SCL_low();
MCUCR =
0x00;
//使能上拉
}
void start_signed()
{
SDA_out();
SDA_high();
SCL_high();
delay_us(4);
SDA_low();
delay_us(4);
SCL_low();
}
void stop_signed()
{
SDA_out();
SDA_low();
SCL_high();
delay_us(4);
SDA_high();
delay_us(4);
SCL_low();
}
uchar ACK_signed()
{
uchar q=1,i;
SDA_in();
SCL_high();
for(i=0;i<200;i++)
{
q =
PIND&0x01;
if(!q)break;
else
i = 0;
}
delay_us(4);
SCL_low();
return q;
}
uchar mask_ack()
{
SDA_out();
SCL_low();
delay_us(2);
SDA_low();
delay_us(4);
SCL_high();
delay_us(4);
}
void write_byte(uchar w_byte)
{
uchar i;
SDA_out();
SCL_out();
for(i=0;i<8;i++)
{
if((w_byte&0x80)!=0)SDA_high();
else
SDA_low();
w_byte<<=1;
SCL_high();
delay_us(4);
SCL_low();
delay_us(4);
}
}
uchar read_byte()
{
uchar i,read_byte;
SDA_in();
for(i=0;i<8;i++)
{
SCL_high();
delay_us(10);
read_byte=read_byte<<1;
if((PIND&0x01)!=0)read_byte|=0x01;
delay_us(10);
SCL_low();
delay_us(10);
}
return read_byte;
}
write_24c02(uchar addr,uchar w_data)
{
start_signed();
write_byte(0xa0);
if(ACK_signed())return;
write_byte(addr);
if(ACK_signed())return;
write_byte(w_data);
if(ACK_signed())return;
stop_signed();
delay_ms(10);
//延时10MS等待写操作完成
}
uchar read_24c02(uchar addr)
{
uchar temp;
start_signed();
write_byte(0xa0);
if(ACK_signed())return;
write_byte(addr);
if(ACK_signed())return;
start_signed();
//从新开始
write_byte(0xa1);
if(ACK_signed())return;
temp = read_byte();
mask_ack();
//主机发送应答信号
stop_signed();
return temp;
}
uchar main()
{
uchar p = 0xff;
init();
DDRB = 0xff;
PORTB = 0xff;
while(1)
{
write_24c02(0x03,0x43);
delay_ms(10);
p =
read_24c02(0x03);
PORTB = p;
}
}