?? eeprom.c
字號:
/***********************************************************************************************
名 稱:寫入一個(gè)字節(jié)到24c512并讀出來驗(yàn)證
功能描述: 我們將24c512的兩條總線接在了P36和P37上,因此,必須先定義:
sbit SCL=P3^6; sbit SDA=P3^7; 在這個(gè)試驗(yàn)中,我們寫入了一組字節(jié)數(shù)值到24c512的0x0081為首的位置。
然后在將其讀出并在P1口顯示
創(chuàng)建日期:2009-04-25
***********************************************************************************************/
#include <reg51.h> //包括一個(gè)51標(biāo)準(zhǔn)內(nèi)核的頭文件
#define uchar unsigned char //定義一下方便使用
#define uint unsigned int
#define ulong unsigned long
#define WriteDeviceAddress 0xa0 //定義器件在IIC總線中的地址
#define ReadDviceAddress 0xa1
sbit SCL=P3^6;
sbit SDA=P3^7;
uchar data[6]={0x01;0x02;0x03;0x04;0x05;0x06}
uchar buf[6];
/************開始信號***************/
void I2cStart(void)
{
SCL=1;
SDA=1;
NOP;
SDA=0;
NOP;
SCL=0;
}
/**********停止信號*************/
void I2cStop(void)
{
SDA=0;
SCL=1;
NOP;
SDA=1;
NOP;
SCL=0;
}
/************應(yīng)答信號**************/
void I2cAck(bit ACK)
{
SDA=ACK;
NOP;
SCL=1;
NOP;
SCL=0;
SDA=1;
}
/**************向EEPROM寫入一個(gè)字節(jié)*******************/
void I2cWriteByte(unsigned char wbyte)
{
unsigned char i;
for(i=0;i<8;i++)
{
wbyte<<=1;
if(CY)SDA=1;
else SDA=0;
NOP;
SCL=1;
NOP;
SCL=0;
}
SDA=1;
NOP;
SCL=1;
while(SDA);
SCL=0;
}
/**************從EEPROM讀出一個(gè)字節(jié)******************/
unsigned char I2cReadByte(void)
{
unsigned char i,rbyte;
for(i=8;i--;)
{
SCL=1;
rbyte<<=1;
if(SDA)rbyte++;
SCL=0;
}
return rbyte;
}
/************************向EEPROM指定地址寫入一個(gè)字節(jié)********************************/
void EepromByteWrite(unsigned int addr,unsigned char wdata)
{
I2cStart();
I2cWriteByte(0xa0);
I2cWriteByte(*(char*)&addr);
I2cWriteByte(*(1+(char*)&addr));
I2cWriteByte(wdata);
I2cStop();
delay_ms(10);
}
/************************從EEPROM指定地址讀出一個(gè)字節(jié)********************************/
unsigned char EepromByteRead(unsigned int addr)
{
unsigned char i;
I2cStart();
I2cWriteByte(0xa0);
I2cWriteByte(*(char*)&addr);
I2cWriteByte(*(1+(char*)&addr));
I2cStart();
I2cWriteByte(0xa1);
i=I2cReadByte();
I2cStop();
return i;
}
/************************延時(shí) n 毫秒********************************/
void delay_ms(unsigned char delaytimes)
{
unsigned char dely;
while(delaytimes--)
{
dely=154;
for (;--dely;);
}
}
/************************主函數(shù)****************************/
main()
{
uchar i;
uint p;
p=0x0081;
for(i=0;i<6;i++)
{
EepromSequentialWrite(p++,data[i]); //從0x0081開始存入6個(gè)數(shù)據(jù)
}
delay(100); //延時(shí)一段時(shí)間后開始讀取剛才寫入的數(shù)據(jù)
p=0x0081;
for(i=0;i<6;i++)
{
buf[i]=EepromSequentialRead(p++); //從0x0081開始讀取數(shù)據(jù)并存入數(shù)據(jù)buf數(shù)組單元
P1=buf[i]; //取出一個(gè)數(shù)據(jù)后就送P1口顯示 P1口接8個(gè)LED指示燈
delay(5000); //延時(shí) 5 秒以便觀察,接著接收顯示下一個(gè)數(shù)
}
}
?? 快捷鍵說明
復(fù)制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -