1

I'm trying to record the state of some pins over time. To save memory, I'm thinking about encoding the pin states into a single integer, like this:

Pin 1: TRUE
Pin 2: FALSE
Pin 3: FALSE
Pin 4: TRUE
Pin 1 = 1, Pin 2 = 2, Pin 3 = 4, Pin 4 = 8
1 +たす 0 +たす 0 +たす 8
Result: 9

This is pretty efficient. But how do I decode the pin states from this best? Or do you recommend a better way to do this?

asked Jul 8, 2017 at 17:21

2 Answers 2

0

Use the AND operator.

For example:

Pin 2's state would be: (result & 0x02) ? TRUE:FLASE

answered Jul 8, 2017 at 17:40
1
  • It took me a minute (well, more like 5 ;) ) to figure out these are hex values, but the solution is simple and working perfect. Thank you! Commented Jul 8, 2017 at 18:06
5

You are almost there with that. Personally I'd use OR not +:

This is a better way of defining the pins instead of using 1, 2, 4 etc. It results in the same thing, but you can see the bit number in there. The << is left shift.

#define PIN0 (1 << 0)
#define PIN1 (1 << 1)
#define PIN2 (1 << 2)
#define PIN3 (1 << 4)

Now you can combine:

uint8_t val = PIN0 | PIN3; // 9

And you can check if one is set:

if (val & PIN3) {
 // ....
}

To loop through the pins you can use the << again:

for (uint8_t pin = 0; pin < 8; pin++) {
 if (val & (1 << pin)) {
 // ....
 }
}

etc.

answered Jul 8, 2017 at 17:40
1
  • Pretty cool. I will keep that in mind as another great solution, thank you for your help. Commented Jul 8, 2017 at 18:06

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.