專注電子技術(shù)學(xué)習(xí)與研究
當(dāng)前位置:單片機(jī)教程網(wǎng) >> MCU設(shè)計(jì)實(shí)例 >> 瀏覽文章

51單片機(jī)i2c存儲器24c02驅(qū)動程序

作者:佚名   來源:本站原創(chuàng)   點(diǎn)擊數(shù):  更新時間:2013年10月16日   【字體:


這是電路圖,這是從這個項(xiàng)目中取得的文件里面有電路圖和仿真文件:http://www.torrancerestoration.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()//應(yīng)答信號
{
 unsigned char i = 0;
 SCL = 1;
 delay();
 while(SDA == 1 && i < 255)//等待應(yīng)答,過一段時間不應(yīng)答退出循環(huán)
  i++;
 SCL = 0;
 delay();
}
void writebyte(unsigned char date)//寫一個字節(jié)
{
 unsigned char i,temp;
 temp = date;
 for(i = 0; i < 8; i++)
 {
  temp <<= 1;//temp左移一位后高位進(jìn)CY
  SCL = 0;
  delay();
  SDA = CY;
  delay();
  SCL = 1;
  delay();
 } 
 SCL = 0;//應(yīng)答信號中SCL = 1,所以這里要置0
 delay();
 SDA = 1;//用完要釋放數(shù)據(jù)總線
 delay();
}
unsigned char readbyte()//讀一個字節(jié)
{
 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)//向地址寫一個字節(jié)數(shù)據(jù)
{
 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)//向地址讀一個字節(jié)數(shù)據(jù)
{
 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個字節(jié)數(shù)據(jù),數(shù)據(jù)存放在指針P指的數(shù)組中
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);//一定要適當(dāng)延時,不然寫不進(jìn)去
 }
}
//向地址讀n個字節(jié)數(shù)據(jù),數(shù)據(jù)存放在指針P指的數(shù)組中
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);
  
 }
}

 

關(guān)閉窗口

相關(guān)文章