单片机I2C驱动程序
扫描二维码
随时随地手机看文章
void delay()
{; ;}
void delay1ms ( uint z )
{
uint x, y;
for ( x = z; x > 0; x -- )
for ( y = 110; y > 0; y -- );
}
I2C启动:在SCL为高电平期间,SDA出现下降沿
void start_I2C ( ) /
{
sda = 1;
delay ();
scl= 1;
delay ();
sda = 0;
delay ();
}
I2C停止:在SCL高电平期间,SDA上产生一上升沿
void stop_I2C () //停止
{
sda = 0;
delay ();
scl = 1;
delay ();
sda = 1;
delay ();
}
总线初始化:将总线拉高以释放总线
void init_I2C ()
{
sda = 1;
delay ();
scl = 1;
delay ();
}
应答信号:在SCL高电平期间,SDA被从设备拉低表示应答
void response ()//应答
{
uchar i;
scl = 1;
delay ();
while ( ( sda == 1 ) && ( i < 250 ) ) i ++; // i < 255这里只是表示没有应答时,若i > 255就直接退出,才不至于死循环。
scl = 0;
delay ();
}
写一个字节:只有在SCL低电平期间,SDA上的高电平或低电平才可以变化
void write_byte ( uchar date )
{
uchar i, temp;
temp = date;
for ( i = 0; i < 8; i ++ )
{
temp = temp << 1; //将最高位移入CY里面
scl = 0;
delay ();
sda = CY;
delay ();
scl = 1;
delay ();
}
scl = 0;
delay ();
sda = 1;
delay ();
}
读一个字节:
uchar read_byte ()
{
uchar i, k;
scl = 0;
delay ();
sda = 1;
delay ();
for ( i = 0; i < 8; i ++ )
{
scl = 1;
delay ();
k = ( k << 1 ) " sda; //也是从最高位开始读
scl = 0;
delay ();
}
return k;
}