AVR单片机的24C02通信程序

时间:2018-07-24来源:网络

#include

#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) //设置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}

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(); //主机发送应答信号

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;

}

}

关键词: AVR单片机 24C02 通信程序

加入微信
获取电子行业最新资讯
搜索微信公众号:EEPW

或用微信扫描左侧二维码

相关文章

查看电脑版