As @KiraSan said, You need something larger than a byte for 9 bits. However:
int tally;
tally=0;
for (char pin=1; pin<=9; pin++) {
if (digitalRead(pin)==HIGH) {
tally|=1<<(9-pin);
}
}
This is done from memory and is untested, if anyone spots any errors, let me know.
Explanation: tally is the sum (you should do something with this at the end, obviously, or it has no effect). It is defined and set to 0. Then, for each pin (1-9), read the pin; if the pin is high: take the number '1', and double it (9-pin) times; so if pin=9, it is doubled 0 times; for pin=2, it is doubled once (for a total of 2), and so forth. Set this bit on the tally.
Note that this reads digital pin 1 (which happens to be the second pin, the first being pin 0) - this should be marked as "tx" to set in the first bit, not the one referred to as "pin1" (which might be a constant or a variable, and therefore could point to any given pin). This method also assumes the pins are in order - you could easily change it to start from 0, or 7, but they have to be in order.
If you want arbitrary pins, or variable pins, you might try this:
const PIN_COUNT=9;
char pins[PIN_COUNT]={13,2,5,4,3,6,7,8,9};
int tally;
tally=0;
for (char pin=0; pin<PIN_COUNT; pin++) {
if (digitalRead(pins[pin])==HIGH) {
tally|=1<<pin;
}
}
Changes: add PIN_COUNT as a constant at the start, set the order of the pins (which can include any digital pins, including repeating a given pin if you feel so inclined, even after the start of the code.). You can also change them by doing: pins[0]=1;
- note that they are numbered from 0-8 for 9 pins. Since they now start at 0, the line with << is now adjusted accordingly, as is the line that starts with for...
.