我正在使用 Arduino 并开始使用端口寄存器。我喜欢速度的提高和同时更改多个端口的能力。但是,我不知道如何使用端口寄存器观察单个引脚的变化。(我认为它可以用bitmath来完成,但我什至不知道如何开始。)
所以当我检查我的端口寄存器时,我应该得到这样的东西:
PINB = B000xxxxx
x
我的引脚值在哪里。这些引脚中的任何一个都可能发生了变化。我想知道最右边的(最不重要的?)位何时发生了变化。如何使用 bitmath 检查最后一个是否已从 a 切换0
到 a 1
?
“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)
要确定该位是否已更改,您需要先前的值,正如其他人所说,您将其屏蔽掉——
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;
}