[编程]

atmega16驱动at24c02

[复制链接]
2512|0
手机看帖
扫描二维码
随时随地手机跟帖
qazplm3218|  楼主 | 2017-3-29 21:04 | 显示全部楼层 |阅读模式

unsigned char at24c02_sda_io(void)  //修改IO口方向
{
DDRD&=~(BIT(5));
PORTD|=(BIT(5));
if((PIND&0x20)==0x00){return 0;}
else{return 1;}
}
void at24c02_init(void)   //at24c02初始化,开始状态都为"空闲"
{
at24c02_sda_set;
delayus(5);
at24c02_scl_set;
delayus(5);
}
void at24c02_start(void)   //at2c02启动信号;SCL高电平下,SDA从高电平到低电平的跳变
{
at24c02_sda_set;
delayus(5);
at24c02_scl_set;
delayus(5);
at24c02_sda_clr;
delayus(5);
}
void at24c02_stop(void)   //at24c02停止信号;SCL高电平下,SDA从低电平到高电平的跳变
{
at24c02_sda_clr;
delayus(5);
at24c02_scl_set;
delayus(5);
at24c02_sda_set;
delayus(5);
}
void at24c02_response(void)  //at24c02应答响应信号;SCL高电平下,如果at24c02收到数据,则会SDA拉低
{
  unsigned int x=0;
  at24c02_scl_set;
  delayus(5);
  while((at24c02_sda_io())&&(x<1000))x++;   //等待是否有应答,如果一段时间应答不成功,则默认为应答成功
  at24c02_scl_clr;
  delayus(5);
}
unsigned char at24c02_read_byte(void)    //从at24c02读出数据
{
unsigned char x,y;
at24c02_scl_clr;
delayus(5);
at24c02_sda_set;
delayus(5);
for(x=0;x<8;x++)
{
  at24c02_scl_clr;
  delayus(5);
  y=(y<<1)|at24c02_sda_io();
  delayus(5);
  at24c02_scl_set;
  delayus(5);
}
return y;
}
void at24c02_write_byte(unsigned char byte)    //向at24c02写入数据
{
unsigned char x,y;
for(x=0;x<8;x++)
{
  y=byte&0x80;
  at24c02_scl_clr;
  delayus(5);
  if(y==0){at24c02_sda_clr;}
  else{at24c02_sda_set;}
  delayus(5);
  at24c02_scl_set;
  delayus(5);
  byte=byte<<1;
  delayus(5);
}
at24c02_scl_clr;
delayus(5);
at24c02_sda_clr;
delayus(5);
}
void at24c02_write_data(unsigned char add,unsigned char data)    //给at24c02指定地址写入数据
{
at24c02_start();
at24c02_write_byte(0xA0);   //0xA0:写数据,0xA1:读数据;
at24c02_response();
at24c02_write_byte(add);
at24c02_response();
at24c02_write_byte(data);
at24c02_response();
at24c02_stop();
delayms(10);
}
unsigned char at24c02_read_data(unsigned char add)    //从A24C02指定地址中读出数据
{//0xA0:写数据,0xA1:读数据;
unsigned char data;
at24c02_start();
at24c02_write_byte(0xA0);   
at24c02_response();
at24c02_write_byte(add);
at24c02_response();
at24c02_start();
at24c02_write_byte(0xA1);   
at24c02_response();
data=at24c02_read_byte();
at24c02_stop();
delayms(10);
return data;
}

为什么连续写入两次数据,才能存入数据,并且正确的读出数据?如果写入一次数据的话,读出的数据还是写入之前的数据(等于数据没有存进去)??


相关帖子

发新帖 我要提问
您需要登录后才可以回帖 登录 | 注册

本版积分规则

25

主题

67

帖子

1

粉丝