#include
extern void LcdInit();
extern void LcdShowStr(unsigned char x, unsigned char y, const unsigned char *str);
extern void I2CStart();
extern void I2CStop();
extern unsigned char I2CReadACK();
extern unsigned char I2CReadNAK();
extern bit I2CWrite(unsigned char dat);
void E2Read(unsigned char *buf, unsigned char addr, unsigned char len);
void E2Write(unsigned char *buf, unsigned char addr, unsigned char len);
void ArrayToHexStr(unsigned char *str, unsigned char *array, unsigned char len);
void main ()
{
unsigned char i;
unsigned char buf[5];
unsigned char str[20];
LcdInit(); //初始化液晶
E2Read(buf, 0x90, sizeof(buf)); //从E2中读取一段数据
ArrayToHexStr(str, buf, sizeof(buf)); //转换为十六进制字符串
LcdShowStr(0, 0, str); //显示到液晶上
for (i=0; i { buf[ i] = buf[ i] + 1 + i; } E2Write(buf, 0x90, sizeof(buf)); //再写回到E2中 while(1) {} } void ArrayToHexStr(unsigned char *str, unsigned char *array, unsigned char len) //把一个字节数组转换为十六进制字符串的格式 { unsigned char tmp; while (len--) { tmp = *array >> 4; //先取高4位 if (tmp <= 9) //转换为0-9或A-F *str = tmp + '0'; else *str = tmp - 10 + 'A'; str++; tmp = *array & 0x0F; //再取低4位 if (tmp <= 9) //转换为0-9或A-F *str = tmp + '0'; else *str = tmp - 10 + 'A'; str++; *str = ' '; //转换完一个字节添加一个空格 str++; array++; } } void E2Read(unsigned char *buf, unsigned char addr, unsigned char len) //E2读取函数,数据接收指针buf,E2中的起始地址addr,读取长度len { do { //用寻址操作查询当前是否可进行读写操作 I2CStart(); if (I2CWrite(0x50<<1)) //器件应答则跳出循环,继续执行,非应答则进行下一次查询 break; I2CStop(); } while(1); I2CWrite(addr); //写入起始地址 I2CStart(); //发送重复启动信号 I2CWrite((0x50<<1)|0x01); //寻址器件,后续为读操作 while (len > 1) //连续读取len-1个字节 { *buf = I2CReadACK(); //最后字节之前为读取操作+应答 buf++; len--; } *buf = I2CReadNAK(); //最后一个字节为读取操作+非应答 I2CStop(); } void E2Write(unsigned char *buf, unsigned char addr, unsigned char len) //E2写入函数,源数据指针buf,E2中的起始地址addr,写入长度len { while (len--) { do { //用寻址操作查询当前是否可进行读写操作,即等待上一次写入操作完成 I2CStart(); if (I2CWrite(0x50<<1)) //器件应答则跳出循环,继续执行,非应答则进行下一次查询 break; I2CStop(); } while(1); I2CWrite(addr); //写入起始地址 I2CWrite(*buf); //写入一个字节数据 I2CStop(); //结束写操作,以等待写入完成 buf++; //数据指针递增 addr++; //E2地址递增 } }