if(input & 0x80)在I2C中是怎么样一步步写入数据的?

input & 0x80判断真假过程

我们先放一段if(input & 0x80)在I2C写字节的代码

 1 /************************************************
 2 *函数名称 : void I2C_WriteByte
 3 *功    能 : I2C写一个字节
 4 *参    数 : dat:传输数据
 5 *返 回 值 : 无
 6 *************************************************/
 7 void I2C_WriteByte(uint8_t  input)
 8 {
 9     uint8_t  i;
10     SDA_OUT();
11     for(i=0; i<8; i++)
12     {
13         IIC_SCL = 0;
14         delay_ms(5);
15 
16         if(input & 0x80)
17         {
18             IIC_SDA = 1;
19             //delaymm(10);
20         }
21         else
22         {
23             IIC_SDA = 0;
24             //delaymm(10);
25         }
26 
27         IIC_SCL = 1;
28         delay_ms(5);
29 
30         input = (input<<1);
31     }
32 
33     IIC_SCL = 0;
34     delay_us(4);
35 
36     SDA_IN();
37     delay_us(4);
38 }    
I2C_WriteByte

下面的讲解会和上面的循环一起讲,注意for循环

调用这个函数需要导入一个uint8_t input参数
我们假设我们导入的参数是0x71
下面记录一下I2C_WriteByte写入数据的过程

0x71 ---> 0111 0001
0x80 ---> 1000 0000

i=0时,第一次判断if(input & 0x80)
0111 0001
1000 0000 &
---------------
0000 0000

if(input & 0x80)判断为假,IIC_SDA = 0;

判断完以后执行下面语句有一个input = (input<<1)
那么0x71要向左移一位
原来: 0111 0001
左移一位: 1110 0010
左移也就是最高位丢掉,其余位向左移一位,最后一位补0

左移以后的i=1,我们第二次判断if(input & 0x80)
此时是左移一位后的0x71 & 0x80

1110 0010
1000 0000 &
----------------
1000 0000

if(input & 0x80)判断为真,IIC_SDA = 1;
之后也按照这种方法左移
这样代码循环8次,左移8次以后我们就可以把我们的0x71发送在SDA线上给从机了

最主要的就是上面的过程
在代码中的if(input & 0x80)
也有些代码写的是if(input & 0x80 == 0x80)
我在上面的代码I2C_WriteByte测试过,实际上他们的效果都是一样的
都是判断最高位是不是为1

到这里就结束了,如果有错误或者有更好的补充可以在评论留言

猜你喜欢

转载自www.cnblogs.com/hjf-log/p/i2c.html