您的位置:首页 > 其它

I2C总线的相关程序

2016-09-19 19:10 302 查看
sbit SCL = P2^0;
sbit SDA = P2^1;
sbit RS = P2^4;
sbit RW = P2^5;
sbit E = P2^6;void iic_start()//起始信号
{
SDA = 1;
SCL = 1;
delay_us(1);
SDA = 0;
delay_us(1);

SCL = 0;//钳住总线
}
void iic_stop()  //终止信号
{
SDA = 0;
SCL = 1;
delay_us(1);
SDA = 1;
delay_us(1);

SCL = 0;//钳住总线
}
//下面是发送字节和接受字节的程序:
bit iic_send_byte(unsigned char byte)
{
unsigned char i;
for(i = 0; i < 8; i++)
{
SDA = byte & 0x80;//非0值,SDA=1,否则SDA=0
SCL = 1;
delay_us(1);
SCL = 0;
byte <<= 1;
}
SCL = 1;
SDA = 1;
delay_us(1);
if(0 == SDA)
{
ack = 1;
}
else
{
ack = 0;
}
SCL = 0;

return 0;
}
unsigned char iic_rcv_byte()
{
unsigned char i;
unsigned char temp = 0;
unsigned char a;
SDA = 1;
for(i = 0; i < 8; i++)
{
SCL = 0;
delay_us(1);
SCL = 1;
if(SDA)
{
a = 0x01;
}
else
{
a = 0;
}
temp |= (a << (7 - i));
delay_us(1);
}
SCL = 0;
return temp;
}
下面是应答和非应答信号:
void iic_ack()
{
SDA = 0;
SCL = 1;
delay_us(1);

SCL = 0;
}
void iic_noack()
{
SDA = 1;
SCL = 1;
delay_us(1);

SCL = 1;
}


                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: