专注电子技术学习与研究
当前位置:单片机教程网 >> MCU设计实例 >> 浏览文章

51单片机i2c存储器24c02驱动程序

作者:佚名   来源:本站原创   点击数:  更新时间:2013年10月16日   【字体:


这是电路图,这是从这个项目中取得的文件里面有电路图和仿真文件:http://www.51hei.com/bbs/dpj-22586-1.html

下面是 i2c.c文件:
#include <reg52.h>
#include "i2c.h"
#include "delay_ms.h"
void delay()
{
 ;;
}
void i2cinit()//总线初始化
{
 SDA = 1;
 delay();
 SCL = 1;
 delay();
}
void start()//启动信号
{
 SDA = 1;
 SCL = 1;
 delay();
 SDA = 0;
 delay();
}
void stop()//停止信号
{
 SDA = 0;
 delay();
 SCL = 1;
 delay();
 SDA = 1;
 delay();
}
void respons()//应答信号
{
 unsigned char i = 0;
 SCL = 1;
 delay();
 while(SDA == 1 && i < 255)//等待应答,过一段时间不应答退出循环
  i++;
 SCL = 0;
 delay();
}
void writebyte(unsigned char date)//写一个字节
{
 unsigned char i,temp;
 temp = date;
 for(i = 0; i < 8; i++)
 {
  temp <<= 1;//temp左移一位后高位进CY
  SCL = 0;
  delay();
  SDA = CY;
  delay();
  SCL = 1;
  delay();
 } 
 SCL = 0;//应答信号中SCL = 1,所以这里要置0
 delay();
 SDA = 1;//用完要释放数据总线
 delay();
}
unsigned char readbyte()//读一个字节
{
 unsigned char i,k;
 SCL = 0;
 delay();
 SDA = 1;
 for(i = 0; i < 8; i++)
 {
  SCL = 1; 
  delay();
  k = (k << 1) | SDA; //和最低位或,一位位送到K
  SCL = 0;
  delay();
 }
 delay();
 return k;
}
void write_add(unsigned char address,unsigned char date)//向地址写一个字节数据
{
 start();
 writebyte(0xa0);//A0,A1,A2接地,AT24C02芯片地址为1010,送控制字为1010A2A1A0R/~W
 respons();
 writebyte(address);
 respons();
 writebyte(date);
 respons();
 stop();
}
unsigned char read_add(unsigned char address)//向地址读一个字节数据
{
 unsigned char date;
 start();
 writebyte(0xa0);//A0,A1,A2接地,AT24C02芯片地址为1010,送控制字为1010A2A1A0R/~W
 respons();
 writebyte(address);
 respons();
 start();
 writebyte(0xa1);//A0,A1,A2接地,AT24C02芯片地址为1010,送控制字为1010A2A1A0R/~W
 respons();
 date = readbyte();
 stop();
 return date;
}


//向地址写n个字节数据,数据存放在指针P指的数组中
void write_n_add(unsigned char * p,unsigned char address,unsigned char n)
{
 unsigned char i;
 for(i = 0; i < n; i++)
 {
  write_add((address + i),*(p + i));
  delay_ms(20);//一定要适当延时,不然写不进去
 }
}
//向地址读n个字节数据,数据存放在指针P指的数组中
void read_n_add(unsigned char * p,unsigned char address,unsigned char n)
{
 unsigned char i;
 for(i = 0; i < n; i++)
 {
  *(p + i) = read_add(address + i);
  
 }
}

 

关闭窗口

相关文章