连接多个相同地址I2C设备的C51程序
扫描二维码
随时随地手机看文章
本人初学C,曾为这个问题大伤脑筋^_^,就是一个单片机系统有两个以上的相同地址的I2C设备,无法用两个同一对SDA/SCL引脚
#include "stc89c51.h"
#include "iic.h"
sbit scl0=P3^5;
sbit sda0 = P3^4;
sbit scl1= P3^3;
sbit sda1 = P3^2;
//这里只写了两个I2C设备,如果需要可以再加上 sbit scl2=xx; sbit sda2=xx; 实际上多个设备的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) //设备1 scl1=value; if(device==1) //设备2 scl2=value; } voidsda(device,value) { if(device==0) //设备1 sda1=value; if(device==1) //设备2 sda2=value; } bit sdasense(chardevice) { switch(device) { case1:returnsda1; break; case2:returnsda2; break; } } //启动I2C总线的函数,当scl为高电平时使sda产生一个负跳变 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总线,当scl为高电平时使sda产生一个正跳变 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); } //发送应答信号 voidiic_ack(device) { sda(device,0); scl(device,1); scl(device,0); sda(device,1); } //发送无应答信号 voidiic_noack(device) { sda(device,1); scl(device,1); scl(device,0); } //检测应答信号 bit iic_testack(device) { bit errorbit; //真确应答,返回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); } //发送一个字节 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); } } //读一个字节 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); }