Go Down

Topic: Solved: How to shuffle 8 inputs into a byte (Read 586 times) previous topic - next topic

fiddler

Jan 02, 2012, 12:18 am Last Edit: Jan 02, 2012, 01:30 am by fiddler Reason: 1
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 :-)

K

PaulS

Quote
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.

fiddler

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

jwatte


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:

Code: [Select]

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;
}


bperrybap

While this currently does work since LOW is currently defined as zero,
Code: [Select]
    if (digitalRead(bitPorts[i]) != 0) {

To be compliant with the digitalRead() api it should be:
Code: [Select]
    if (digitalRead(bitPorts[i]) != LOW) {

as the API does not guarantee that LOW is 0.

--- bill

Go Up