連接多個(gè)相同地址I2C設(shè)備的C51程序
本人初學(xué)C,曾為這個(gè)問(wèn)題大傷腦筋^_^,就是一個(gè)單片機(jī)系統(tǒng)有兩個(gè)以上的相同地址的I2C設(shè)備,無(wú)法用兩個(gè)同一對(duì)SDA/SCL引腳
#include "stc89c51.h"
#include "iic.h"
sbit scl0=P3^5;
sbit sda0 = P3^4;
sbit scl1= P3^3;
sbit sda1 = P3^2;
//這里只寫了兩個(gè)I2C設(shè)備,如果需要可以再加上 sbit scl2=xx; sbit sda2=xx; 實(shí)際上多個(gè)設(shè)備的scl腳可以共用
unsignedchariic_delay_time = 8;
voidscl(device,value);
voidsda(device,value);
bit sdasense(chardevice);
// delay
voidiic_delay(unsignedcharm)
{
unsignedcharn;
for(n=0;n } // voidscl(device,value) { if(device==0) //設(shè)備1 scl1=value; if(device==1) //設(shè)備2 scl2=value; } voidsda(device,value) { if(device==0) //設(shè)備1 sda1=value; if(device==1) //設(shè)備2 sda2=value; } bit sdasense(chardevice) { switch(device) { case1:returnsda1; break; case2:returnsda2; break; } } //啟動(dòng)I2C總線的函數(shù),當(dāng)scl為高電平時(shí)使sda產(chǎn)生一個(gè)負(fù)跳變 voidiic_start(device) { sda(device,1); scl(device,1); iic_delay(iic_delay_time); sda(device,0); iic_delay(iic_delay_time); scl(device,0); iic_delay(iic_delay_time/2); } //終止I2C總線,當(dāng)scl為高電平時(shí)使sda產(chǎn)生一個(gè)正跳變 voidiic_stop(device) { scl(device,0); sda(device,0); scl(device,1); iic_delay(iic_delay_time); sda(device,1); iic_delay(iic_delay_time); } //發(fā)送應(yīng)答信號(hào) voidiic_ack(device) { sda(device,0); scl(device,1); scl(device,0); sda(device,1); } //發(fā)送無(wú)應(yīng)答信號(hào) voidiic_noack(device) { sda(device,1); scl(device,1); scl(device,0); } //檢測(cè)應(yīng)答信號(hào) bit iic_testack(device) { bit errorbit; //真確應(yīng)答,返回0 sda(device,1); iic_delay(iic_delay_time); scl(device,1); iic_delay(iic_delay_time); errorbit=sdasense(device); scl(device,0); iic_delay(iic_delay_time); return(errorbit); } //發(fā)送一個(gè)字節(jié) voidiic_write8bit(device,unsignedcharinput) { unsignedchartemp; for(temp=0;temp<8;temp++) { if((input< sda(device,1); else sda(device,0); scl(device,1); iic_delay(iic_delay_time); scl(device,0); } } //讀一個(gè)字節(jié) unsignedchariic_read8bit(device) { unsignedchartemp,rbyte=0; for(temp=0;temp<8;temp++) { scl(device,1); iic_delay(iic_delay_time); if(sdasense(device)) rbyte=(rbyte<<1)+1; else rbyte=rbyte<<1; scl(device,0); } return(rbyte); }