标题: 为什么单片机读取24c02读不到我写入的值?是哪里出错了 [打印本页]

作者: 51萌新小朋友    时间: 2020-7-2 11:27
标题: 为什么单片机读取24c02读不到我写入的值?是哪里出错了
void nop()
{
        _nop_();
        _nop_();
}
/////////24C02读写驱动程序////////////////////
void delay1(unsigned int m)
{        unsigned int n;
          for(n=0;n<m;n++);
}

void init()  //24c02初始化子程序
{
        scl=1;
        nop();
        sda=1;
        nop();
}

void start()        //启动I2C总线
{
        sda=1;
        nop();
        scl=1;
        nop();
        sda=0;
        nop();
        scl=0;
        nop();
}

void stop()         //停止I2C总线
{
        sda=0;
        nop();
        scl=1;
        nop();
        sda=1;
        nop();
}

void writebyte(unsigned char j)  //写一个字节
{
        unsigned char i,temp;
           temp=j;
           for (i=0;i<8;i++)
   {
           temp=temp<<1;
           scl=0;
           nop();
           sda=CY;                //temp左移时,移出的值放入了CY中
           nop();
           scl=1;                //待sda线上的数据稳定后,将scl拉高
           nop();
   }
   scl=0;
   nop();
   sda=1;
   nop();
}

unsigned char readbyte()   //读一个字节
{
   unsigned char i,j,k=0;
   scl=0; nop(); sda=1;
   for (i=0;i<8;i++)
   {  
                nop(); scl=1; nop();
              if(sda==1)
                j=1;
              else
                j=0;
              k=(k<<1)|j;
                  scl=0;
        }
           nop();
        return(k);
}

void clock()         //I2C总线时钟
{
   unsigned char i=0;
   scl=1;
   nop();
   while((sda==1)&&(i<255))
             i++;
   scl=0;
   nop();
}

////////从24c02的地址address中读取一个字节数据/////
unsigned char read24c02(unsigned char address)
{
   unsigned char i;
   start();
   writebyte(0xa0);
   clock();
   writebyte(address);
   clock();
   start();
   writebyte(0xa1);
   clock();
   i=readbyte();
   stop();
   delay1(100);
   return(i);
}

//////向24c02的address地址中写入一字节数据info/////
void write24c02(unsigned char address,unsigned char info)
{
   start();
   writebyte(0xa0);
   clock();
   writebyte(address);
   clock();
   writebyte(info);
   clock();
   stop();
   delay1(5000); //这个延时一定要足够长,否则会出错。因为24c02在从sda上取得数据后,还需要一定时间的烧录过程。
}

        write24c02(0,1);
        write24c02(1,2);//24c02的第110到115地址单元作为密码存储区
        write24c02(2,3);
        write24c02(3,4);
        write24c02(4,5);
        write24c02(5,6);
        
        password[0]=read24c02(0);
        password[1]=read24c02(1);
        password[2]=read24c02(2);
        password[3]=read24c02(3);
        password[4]=read24c02(4);
        password[5]=read24c02(5);

51hei.png (26.41 KB, 下载次数: 67)

51hei.png

作者: MikeCai    时间: 2020-7-2 15:49
1)先严格按 I2C通讯协议 来完成 读写 程序,特别注意 起始,停止条件, ACK 应答 时钟 等。
2)再验证单位读写 效果
作者: 51萌新小朋友    时间: 2020-7-2 15:55
问题已解决    是我自己protues图没画好
作者: 权威人物    时间: 2020-7-2 16:07
验证时序是否有问题,24C02的读写保护使能端是否为低电平,地址段选择是否正确,检测电源与连线




欢迎光临 (http://www.51hei.com/bbs/) Powered by Discuz! X3.1