I2C总线的连续读和连续写

想写个在给地址后能一直读或写的程序,因为郭天祥的教程里只有单个字节读写示例。可在网上找了好久没找到合适的示例,只好自己看着手册,慢慢摸索。皇天不负苦心人呀,终于出来了。

写完程序的同时也学会了怎样看手册的时序图。

 

还有此代码只实现了同时写读两个字节,至于在未达到芯片页面通信量的最大值的范围内都可以用FOR循环实现。下面就是代码: 

#include

#include

 

#define uchar unsigned char

sbit sda = P2^0;

sbit scl = P2^1;

 

delay()

{;;}

init()

{

//    sda = 1;

//    delay();

//    scl = 1;

//    delay();

}

 

start()

{

      sda = 1;

//    delay();

      scl = 1;

      delay();

      sda = 0;

      delay();

}

 

stop()

{

      sda = 0;

//    delay();

      scl = 1;

      delay();

      sda = 1;

      delay();

}

 

respons_i2c()

{

      uchar i;

      scl = 1;

      delay();

      while((sda == 1) && (i < 250)) i++;

      scl = 0;

      delay();

}

 

void write_byte_i2c(uchar date)

{

      uchar i;

      for(i=0;i<8;i++)

      {

             date = date<<1;

             scl = 0;

             delay();

             sda = CY;

             delay();

             scl = 1;

             delay();

      }

      scl = 0;

      delay();

      sda = 1;   //释放总线以收应答信号

      delay();

}

 

void write_i2c(uchar maddr,uchar addr,uchar length,uchar date[])

{

      uchar i;

      start();

      write_byte_i2c(maddr);

      respons_i2c();

      write_byte_i2c(addr);

      respons_i2c();

      for(i = 0; i

      {

             write_byte_i2c(date[i]);

             respons_i2c();

      }

      stop();

}

void delay1(uchar x)

{

      uchar a,b;

      for(a=x;a>0;a--)

       for(b=200;b>0;b--);

}

uchar read_byte_i2c()

{

      uchar i,date;

      scl = 0;

      delay();

      sda = 1;    //释放总线

      delay();

      for(i = 0; i<8; i++)

      {

             scl = 1;

             delay();

             date = (date<<1)|sda;

             scl = 0;

             delay();

      }

      return date;

}

uchar *read_i2c(uchar maddr,uchar addr,uchar length)

{

      uchar i =0;

      uchar date[2];

      start();

      write_byte_i2c(maddr&0xfe);

      respons_i2c();

      write_byte_i2c(addr);

      respons_i2c();

      start();

      write_byte_i2c(maddr);

      respons_i2c();

 

      date[0] = read_byte_i2c();

//    for(i = 1; i

      

 

      scl = 0;

      delay();

      sda = 0;

      delay();

      scl = 1;

      delay();

      date[1] = read_byte_i2c();

      stop();

      return date;

}

main()

{      

      uchar code a[]={0x55,0xaa};

      uchar b[2];

      init();

      write_i2c(0xa0,0x0a,2,a);

      delay1(100);

      strcpy(b, read_i2c(0xa1,0x0a,1));

      while(1) 

      {

             P1 = 0xff;

             P1 = b[1];

             delay1(255);

             P1 = 0xff;

             P1 = b[0];      

             delay1(255);

      }

}

【注释】此代码在TX-1C中通过

你可能感兴趣的:(单片机/ARM/硬件)