Pages: [1]   Go Down
Author Topic: Solved: How to shuffle 8 inputs into a byte  (Read 525 times)
0 Members and 1 Guest are viewing this topic.
NZ
Offline Offline
Jr. Member
**
Karma: 1
Posts: 90
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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
« Last Edit: January 01, 2012, 07:30:42 pm by fiddler » Logged

Seattle, WA USA
Offline Offline
Brattain Member
*****
Karma: 601
Posts: 48543
Seattle, WA USA
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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

NZ
Offline Offline
Jr. Member
**
Karma: 1
Posts: 90
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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

Offline Offline
God Member
*****
Karma: 4
Posts: 813
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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

Dallas, TX USA
Offline Offline
Faraday Member
**
Karma: 62
Posts: 2635
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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

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

as the API does not guarantee that LOW is 0.

--- bill
Logged

Pages: [1]   Go Up
Jump to: