51单片机EEPROM应用24C02

硬件说明

  • 单片机型号 :STC89C52
  • 晶振频率:11.0592MHZ

参考代码

#include <REG52.H>
#include <intrins.h>

/*     自定义变量类型    */
typedef unsigned char uchar;   //0~255
typedef unsigned int uint;     //0~65535

//共阴数码管码表
uchar SMG[] = {0x3f,0x06,0x5b,0x4f,0x66,0x6d,0x7d,0x07,0x7f,0x6f,0x77,0x7c,0x39,0x5e,0x79,0x71,0X00};

sbit SCL = P2^1;
sbit SDA = P2^0;

void delay()
{
    _nop_(); _nop_(); _nop_(); _nop_();
    _nop_(); _nop_(); _nop_(); _nop_();
}

void start(void)    //起始信号
{
    SDA = 1;
    delay();
    SCL = 1;
    delay();
    SDA = 0;
    delay();
}
void stop()        //终止信号
{
    SDA = 0;
    delay();
    SCL = 1;
    delay();
    SDA = 1;
    delay();
}
void ack()         //应答信号
{
    uchar i = 0;
    SCL = 1;
    delay();
    while (SDA==1&&i<200) i++;
    SCL = 0;
    delay();
}
void noack()      //非应答信号
{
    SDA = 1;
    delay();
    SCL = 1;
    delay();
    SCL = 0;
    delay();
}

void iic_write_byte(uchar date) //写一个字节
{
    uchar i;
    SCL = 0;
    for (i = 0; i < 8; i++)
    {
        if(date&0x80)
        {
            SDA = 1;
        }
        else
        {
            SDA = 0;
        }
        date <<= 1;
        delay();
        SCL = 1;
        delay();
        SCL = 0;
        delay();
    }
    SDA = 1;
    delay();
}
uchar iic_read_byte() //读一个字节
{
    uchar i;
    uchar date;
    SCL = 0;
    delay();
    SDA = 1;
    delay();
    for (i = 0; i < 8; i++)
    {
        SCL = 1;
        delay();
        date <<= 1;
        if(SDA)
        {
            date++;
        }
        SCL = 0;
        delay();
    }
    return date;

}

void iint()
{
    SDA = 1;
    SCL = 1;
}
void delay1()
{
    uint a = 30000;
    while (a--);
}
void write_byte(uchar add,uchar date) //写
{
    iint();
    start();
    iic_write_byte(0xa0);
    ack();
    iic_write_byte(add);
    ack();
    iic_write_byte(date);
    ack();
    stop();
    delay1();
}
uchar read_byte(uchar add)  //随机读
{
    uchar a;
    iint();
    start();
    iic_write_byte(0xa0);
    ack();
    iic_write_byte(add);
    ack();
    start();

    //当前地址读
    iic_write_byte(0xa1);
    ack();
    a = iic_read_byte();
    noack();
    stop();
    return a;
}
//实验现象:数码管显示开机的次数
void main()
{
    uchar k = 0;
    k = read_byte(7);
    k = k%10;
    P0 = SMG[k];
    k++;
    write_byte(7,k);

    while(1);
}

猜你喜欢

转载自blog.csdn.net/qq_39592312/article/details/107518909