?? wl007.c
字號:
#include <reg51.h>
#include <intrins.h>
#define OP_READ 0xa1 // 器件地址以及讀取操作
#define OP_WRITE 0xa0 // 器件地址以及寫入操作
#define MAX_ADDR 0x7f // AT24C02最大地址
unsigned char code dis_code[] = {0x7e,0xbd,0xdb,0xe7,0xdb,0xbd,0x7e,0xff};
// 寫入到AT24C01的數據串
sbit SDA = P3^4;
sbit SCL = P3^3;
void start();
void stop();
unsigned char shin();
bit shout(unsigned char write_data);
unsigned char read_random(unsigned char random_addr);
void write_byte( unsigned char addr, unsigned char write_data);
void fill_byte(unsigned char fill_data);
void delayms(unsigned char ms);
main(void)
{
unsigned char i;
SDA = 1;
SCL = 1;
fill_byte(0xff); // 全部填充0xff
for(i = 0 ; i < 8; i++) //寫入顯示代碼到AT24Cxx
{
write_byte(i, dis_code[i]);
}
i = 0;
while(1)
{
P0 = read_random(i); // 循環讀取24Cxx內容,并輸出到P0口
i++;
i &= 0x07; // 循環讀取范圍為0x00~0x07
delayms(250);
}
}
void start()
// 開始位
{
SDA = 1;
SCL = 1;
_nop_();
_nop_();
SDA = 0;
_nop_();
_nop_();
_nop_();
_nop_();
SCL = 0;
}
void stop()
// 停止位
{
SDA = 0;
_nop_();
_nop_();
SCL = 1;
_nop_();
_nop_();
_nop_();
_nop_();
SDA = 1;
}
unsigned char shin()
// 從AT24Cxx移入數據到MCU
{
unsigned char i,read_data;
for(i = 0; i < 8; i++)
{
SCL = 1;
read_data <<= 1;
read_data |= (unsigned char)SDA;
SCL = 0;
}
return(read_data);
}
bit shout(unsigned char write_data)
// 從MCU移出數據到AT24Cxx
{
unsigned char i;
bit ack_bit;
for(i = 0; i < 8; i++) // 循環移入8個位
{
SDA = (bit)(write_data & 0x80);
_nop_();
SCL = 1;
_nop_();
_nop_();
SCL = 0;
write_data <<= 1;
}
SDA = 1; // 讀取應答
_nop_();
_nop_();
SCL = 1;
_nop_();
_nop_();
_nop_();
_nop_();
ack_bit = SDA;
SCL = 0;
return ack_bit; // 返回AT24Cxx應答位
}
void write_byte(unsigned char addr, unsigned char write_data)
// 在指定地址addr處寫入數據write_data
{
start();
shout(OP_WRITE);
shout(addr);
shout(write_data);
stop();
delayms(10); // 寫入周期
}
void fill_byte(unsigned char fill_data)
// 填充數據fill_data到EEPROM內
{
unsigned char i;
for(i = 0; i < MAX_ADDR; i++)
{
write_byte(i, fill_data);
}
}
unsigned char read_current()
// 在當前地址讀取
{
unsigned char read_data;
start();
shout(OP_READ);
read_data = shin();
stop();
return read_data;
}
unsigned char read_random(unsigned char random_addr)
// 在指定地址讀取
{
start();
shout(OP_WRITE);
shout(random_addr);
return(read_current());
}
void delayms(unsigned char ms)
// 延時子程序
{
unsigned char i;
while(ms--)
{
for(i = 0; i < 120; i++);
}
}
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -