Solved: How to shuffle 8 inputs into a byte

I have been trawling the site, but to no avail. Maybe I'm searching the wrong thing.

Anyway, I want to take 8 inputs and put theses into a byte.
The inputs will be from different ports, so i cannot just read a port.

Input 1 to go into lsb or bit 0

I can do a digitalRead(pinX) but how do I get input information into a specific bit in the byte

Cheers and happy new year :slight_smile:

K

I can do a digitalRead(pinX) but how do I get input information into a specific bit in the byte

The bitWrite() function comes to mind.

Primo. Thanks a lot as I hadn't seen those byte instructions.
K

fiddler:
I can do a digitalRead(pinX) but how do I get input information into a specific bit in the byte

Here's the code I would write for that:

unsigned char bitPorts[] = {
  1, 3, 5, 7, 9, 2, 4, 6 // or whatever -- first is LSB, ... last one is MSB
};

unsigned char portsToByte() {
  unsigned char ret = 0;
  unsigned char bval = 1;
  for (int i = 0; i < 8; ++i) {
    if (digitalRead(bitPorts[i]) != 0) {
      ret = ret | bval;
    }
    bval = bval << 1;
  }
  return ret;
}

While this currently does work since LOW is currently defined as zero,

    if (digitalRead(bitPorts[i]) != 0) {

To be compliant with the digitalRead() api it should be:

    if (digitalRead(bitPorts[i]) != LOW) {

as the API does not guarantee that LOW is 0.

--- bill