Kyle Hotchkiss
Kyle Hotchkiss

Reputation: 11112

How do you watch for changes in the least significant bit?

I'm working with Arduino and am beginning to work with port registers. I love the speed increases and ability to change multiple ports at the same time. However, I don't know how to watch for a single pin changing using the port registers. (I think it can be done with bitmath, but I don't even know how to start with that.)

So when I check my port register I should get something like this:

PINB = B000xxxxx

Where x are my pin values. Any of those pins could have changed. I want to know when just the rightmost (least significant?) bit has changed. How can I use bitmath to check that just the last one has switched from a 0 to a 1?

Upvotes: 1

Views: 188

Answers (2)

Julie in Austin
Julie in Austin

Reputation: 1003

To find out if the bit has changed, you need the previous value, which you mask out as the others have said --

int lastValue = PINB & 0x01;

Then in your code you do

int currentValue = PINB & 0x01;

to get the LSB of the current pin value.

To determine if there was a change to the bit you want the "exclusive OR" (^) operator -- it is "true" if and only if the two bits are different.

if (lastValue ^ currentValue) {
  // Code to execute goes here

  // Now save "last" as "current" so you can detect the next change
  lastValue = currentValue;
}

Upvotes: 1

A.H.
A.H.

Reputation: 66273

"Bitmath" is indeed the answer to the problem. In your case: x & 0x01 will "mask" all but the lowest bit. The result can be compared to 0 or 1 at your wish.

Common idioms are:

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)

Upvotes: 2

Related Questions