51單片機(jī)i2c存儲(chǔ)器24c02驅(qū)動(dòng)程序
void writebyte(unsigned char date)//寫一個(gè)字節(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)答信號(hào)中SCL = 1,所以這里要置0
delay();
SDA = 1;//用完要釋放數(shù)據(jù)總線
delay();
}
unsigned char readbyte()//讀一個(gè)字節(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)//向地址寫一個(gè)字節(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)//向地址讀一個(gè)字節(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;
}本文引用地址:http://m.butianyuan.cn/article/201611/323840.htm
//向地址寫n個(gè)字節(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)延時(shí),不然寫不進(jìn)去
}
}
//向地址讀n個(gè)字節(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);
}
}
評(píng)論