AVR單片機的24C02通信程序
#include
本文引用地址:http://m.butianyuan.cn/article/201807/383568.htm#define uchar unsigned char
#define uint unsigned int
#define setbit(sfr,bit) (sfr|=(1#define clrbit(sfr,bit) (sfr=~(1#define SDA_out() setbit(DDRD,0) //設(shè)置SDA為輸出
#define SCL_out() setbit(DDRD,2) //設(shè)置SCL為輸出
#define SDA_in() clrbit(DDRD,0) //設(shè)置SDA為輸入
#define SDA_high() setbit(PORTD,0) //設(shè)置SDA為高電平
#define SDA_low() clrbit(PORTD,0) //設(shè)置SDA為低電平
#define SCL_high() setbit(PORTD,2) //設(shè)置SCL為高電平
#define SCL_low() clrbit(PORTD,2) //設(shè)置SCL為低電平
void delay_us(uchar t)
{
uchar i;
for(i=0;i}
void delay_ms(uchar m)
{
uchar i;
for(i=0;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;i200;i++)
{
q = PIND0x01;
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;i8;i++)
{
if((w_byte0x80)!=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;i8;i++)
{
SCL_high();
delay_us(10);
read_byte=read_byte1;
if((PIND0x01)!=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(); //主機發(fā)送應(yīng)答信號
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;
}
}
評論