使用一些掩码对 GPIO 进行按位操作
Bitwise manipulation on GPIO with some masks
我想对 GPIO 结果进行一些位操作,假设我有三个变量来定义某些 GPIO 设备的状态是打开还是关闭:
mask : 1 means bit is set, and need to be calculate
value : real gpio value 0 / 1
active_level; : 1 means high active, 0 means low active
假设我有:
mask : 0010 0001
value : 0000 0001
active: 0000 0001
有没有什么好的方法(目前我正在考虑循环)根据活动水平得到结果?在上述情况下,bit0 为高电平有效,bit5 为低电平有效,由于 bit0 值为高电平而 bit 5 为低电平,因此结果为:
result: 0010 0001
稍后,我想做的是检查结果是否==掩码,如果是,则表示 GPIO 设备状态已打开(例如,两个按钮同时按下)
谢谢
您可以考虑以下位操作。
将value
转换为“1表示有效”格式
value_in_activeness = value ^ (~active);
此操作将格式从“1 为高,0 为低”变为“1 为有效,0 为无效”。
active
代表"which bits are active-high and which are active-low"。方便地,它的补码 ~active
表示 "which bits I want to convert and which bits I want to keep"。 XOR 运算 ^
进行实际转换。
在您的示例中,value_in_activeness
将变为 1111 1111
。不过不用担心,因为我们还有下一步。
屏蔽掉 "I don't care" 位
bits_I_care = value_in_activeness & mask;
使用 &
进行位掩码非常基础,我不知道要解释什么或如何解释。
在您的示例中,结果为 0010 0001
。