How to put 4 digital inputs in to a byte

Hi everyone!

I am a full complete newbie, I have mainly program in ladder for PLC programming.
What I am trying to do is to read 4 digital pin ( 5 to 8 ) were the first input (5) will represent bit 0, second input (6) bit 1 and so on, after reading the inputs I will have a “number” that I would tell me what subroutine the program need to go.
Basically what I am trying to develop is a test program that depending of the connection to the fixture it will go to the subroutine that will test the product, I have read the bitwrite and bitread commands but I do not totally understand them.

Any help on this I would like to thank you in advance

Alberto

I have read the bitwrite and bitread commands but I do not totally understand them.

I'd persist with bitWrite a while longer

Hi Alberto!

You can do simply a digitalRead() and then make a number with bitwise logical operators.

Try this and tell me if is enough:

#define LENGTH 4
const int pins[LENGTH] = {5, 6, 7, 8};

int pinState;
int statusWord;

int statusLast;

void setup() {
   
   Serial.begin(9600);

  for (int i=0; i<LENGTH; i++) {
     pinMode(pins[i], INPUT);
  }
}


void loop() {
  statusWord = 0;
  
  for (int i=0; i<LENGTH; i++) {
     pinState = digitalRead(pins[i]);
     if (pinState == HIGH) {
        statusWord |= 1 << i;
     }
  }
  
  if (statusWord != statusLast) {
     Serial.print("Status: ");
     Serial.println(statusWord, BIN);
     statusLast=statusWord;
  }
  
}

If you arrange for the inputs to be connected to pins in a single Atmega I/O port you can read them all at once.

For example pins 8,9,10 and 11 are bits 0,1,2,3 of Port B and you can read it with

myByte = PINB;

but you also have the data in bits 4,5,6,7 which is irrelevant and can be removed with

myByte &= 0b00001111;

So with two lines of code you have the whole thing

...R