我正在与Arduino合作,并开始使用端口寄存器。我喜欢速度提升和同时更改多个端口的能力。但是,我不知道如何使用端口寄存器观察单个引脚更改。 (我认为可以用bitmath完成,但我甚至不知道如何开始。)
所以当我检查我的端口寄存器时,我应该得到这样的东西:
PINB = B000xxxxx
x
是我的引脚值。任何这些引脚都可能已经改变。我想知道最右边(最不重要的?)位何时发生了变化。如何使用bitmath检查最后一个是否已从0
切换为1
?
答案 0 :(得分:2)
“Bitmath”确实是问题的答案。在您的情况下:x & 0x01
将“掩盖”除最低位之外的所有位置。可以根据您的意愿将结果与0
或1
进行比较。
常用习语是:
x & 0x01 // get only the lowest bit
x & ~0x01 // clear only the lowest bit
x & 0xFE // same: clear only the lowest bit
x | 0x01 // set the lowest bit (others keep their state)
答案 1 :(得分:1)
要确定该位是否已更改,您需要使用之前的值,您可以屏蔽其他人所说的 -
int lastValue = PINB & 0x01;
然后在您的代码中执行
int currentValue = PINB & 0x01;
获取当前引脚值的LSB。
确定您想要“异或”(^)运算符的位是否有变化 - 当且仅当两位不同时才为“真”。
if (lastValue ^ currentValue) {
// Code to execute goes here
// Now save "last" as "current" so you can detect the next change
lastValue = currentValue;
}