新聞中心

51單片機-AT24C

作者: 時間:2016-12-02 來源:網絡 收藏
寫入EEPROM一個2,然后讀出,在數碼管上顯示出來: #include <reg52.h>
#define uchar unsigned char
#define uint unsigned int
sbit SCL = P3^6;
sbit SDA = P3^7;
void delay()
{ ;; } //5us
void delay1(uchar x)
{
uchar a,b;
for(a=x;a>0;a--)
for(b=100;b>0;b--);
}
void Init(){
SCL = 1;
SDA = 1;
}
void start(){
SDA = 1;
delay();
SCL = 1;
delay();
SDA = 0;
delay();
}
void stop(){
SDA = 0;
delay();
SCL = 1;
delay();
SDA = 1;
delay();
}
void write(uchar date)
{
uchar i,temp;
temp=date;
for(i=0;i<8;i++)
{
temp=temp<<1;
SCL=0;
delay();
SDA=CY;
delay();
SCL=1;
delay();
}
SCL=0;
delay();
SDA=1;
delay();
}
uchar read()
{
uchar i,k;
SCL=0;
delay();
SDA=1;
delay();
for(i=0;i<8;i++)
{
SCL=1;
delay();
k=(k<<1)|SDA; // 將SDA賦給K的每一位
SCL=0;
delay();
}
return k;
}
void response(){
int i;
SCL = 1; //在SCL為高電平期間,進行應答
delay();
while((SDA == 1) && (i < 170))i++; //SCL釋放總線,等待從設備應答,從設備會把SDA拉低
SCL = 0;
delay();
}
void At24c_Write(uchar address, uchar value){
start();
write(0xa0); //寫入設備地址
response();
write(address); //寫入首地址
response();
write(value); //寫入數據
response();
stop();
}
uchar At24c_Read(uchar address){
uchar value;
start();
write(0xa0); //偽寫,先寫入設備地址
response();
write(address); //再寫入要讀取數據的首地址
response();
start(); //再次
write(0xa1); //寫入要讀取數據的地址,方向為1
response();
value = read(); //讀取數據
stop();
return value;
}
void main(){
P1 = 0x0; // 位選,使最地位數碼管被選中
Init();
At24c_Write(23,0x5b); // 在EEPROM的23這個地址上寫數據0x5b
delay1(100); // 在寫和讀之間要多延時一會兒,否則器件處理不完
P2 = At24c_Read(23); // 讀取23地址的數據,也就是剛才寫入的數據
while(1);
}
掉電后數據不丟失,復位后,仍然從剛才掉電的數字開始往下顯示。從0"9
#include <reg52.h>
#define uchar unsigned char
#define uint unsigned int
sbit SCL = P3^6;
sbit SDA = P3^7;
uchar temp, sum;
uint flag;
unsigned char code duan[]={
0x3F,0x06,0x5B,0x4F,0x66,0x6D,0x7D,0x07,0x7F,0x6F,
0x77,0x7C,0x39,0x5E,0x79,0x71};
void delay()
{ ;; } //5us
void delay1(uchar x)
{
uchar a,b;
for(a=x;a>0;a--)
for(b=100;b>0;b--);
}
void Init(){
SCL = 1;
SDA = 1;
}
void start(){
SDA = 1;
delay();
SCL = 1;
delay();
SDA = 0;
delay();
}
void stop(){
SDA = 0;
delay();
SCL = 1;
delay();
SDA = 1;
delay();

評論


技術專區(qū)

關閉