#include<reg52.h>
#include<intrins.h>
#define uchar unsigned char
sbit SCL=P3^6; //I2C 时钟
sbit SDA=P3^7; //I2C 数据
sbit anjian_1=P3^4;
uchar code LED[]=
{0x3F,0x06,0x5B,0x4F,0x66,0x6D,0x7D,0x07,0x7F,0x6F,0x77,0x7C,0x39,0x5E,0x79,0x71};
void delay_us()
{
_nop_(); /*起始条件建立时间大于4.7us,延时*/
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
}
delay_ms()
{
unsigned int i;
for(i=0;i<20000;i++);
}
void delayms(unsigned int k)
{
unsigned int j,i;
for(j=k;j>0;j--)
for(i=110;i>0;i--);
}
void Start_I2c()
{
SDA=1; /*发送起始条件的数据信号*/
delay_us();
SCL=1;
delay_us();
SDA=0; /*发送起始信号*/
delay_us();
}
void Stop_I2c()
{
SDA=0; /*发送结束条件的数据信号*/
delay_us();
SCL=1;
delay_us();
SDA=1; /*发送I2C总线结束信号*/
delay_us();
}
void Ack_I2c() //应答函数
{
uchar i=0;
SCL=1;
delay_us();
while(SDA==1&&i<200)
i++;
SCL=0;
delay_us();
}
void No_ack() //非应答函数
{
SDA=1;
delay_us();
SCL=1;
delay_us();
SCL=0;
delay_us();
}
void init()
{
SDA=1;
SCL=1;
}
void wr_byte(uchar date) //写一个字节,该函数将数据写入24C02
{
uchar i;
SCL=0; //IC总线在写数据时,在时钟低电平的时候改变数据,高电平的时候传送数据
delay_us();
for(i=0;i<8;i++) /*要传送的数据长度为8位*/
{
if((date<<i)&0x80)
SDA=1; /*判断发送位*/
else
SDA=0;
delay_us();
SCL=1; // /*置时钟线为高,通知被控器开始接收数据位*/
//IC总线在写数据时,在时钟低电平的时候改变数据,高电平的时候传送数据
delay_us();
SCL=0;
delay_us();
}
SDA=1; /*8位发送完后释放数据线,准备接收应答位*/
delay_us();
}
uchar re_byte() //读一个字节,该函数将数据读出24C02
{
uchar i,temp=0;
SCL=0;
delay_us();
SDA=1;
delay_us();
for(i=0;i<8;i++)
{
temp<<=1;
if(SDA)
{
temp|=0x01;
}
SCL=1;
delay_us();
SCL=0;
}
return temp;
}
void write(uchar add,uchar dat)
{
init();
Start_I2c();
wr_byte(0xa0);
Ack_I2c();
wr_byte(add);
Ack_I2c();
wr_byte(dat);
Ack_I2c();
Stop_I2c();
}
uchar read(uchar add)
{
uchar value;
init();
Start_I2c();
wr_byte(0xa0); //写器件地址,前面四位是芯片24C02本身确定的,它不变,之后三位是引脚地址,因为我们都接地了,所以这三位都为0,最后一位位读写位,写的话为0,读为1
Ack_I2c();
wr_byte(add); //希望写到哪个地址
Ack_I2c();
Start_I2c();
wr_byte(0xa1); //写数据
Ack_I2c();
value=re_byte();
No_ack();
Stop_I2c();
return value;
}
void main()
{
uchar k;
delay_ms();
k=read(100); //上电后马上读取断电前的数据(必须的语句) 100为地址 k为地址,范围0-255
while(1)
{
if(anjian_1==0)
{
delayms(100);
if(anjian_1==0)
k++;
P2=LED[k];
if(k>9)
k=0;
}
write(100,k); //k为断电前需要保存的数据,100为地址,需要保存的数据用这条语句保存(必须的语句)
P2=LED[k];
}
}
联系客服