Array from digital reads of 16 inputs

I am attempting to combine the state of 8 digital inputs into a single value.

Pin Number State
1 0 //LSB
2 1
3 1
4 1
5 1
6 1
7 1
8 1 //MSB

I will be sending this out over modbus as Binary 11111110 or Decimal 2046 or Hexidecimal FE

How do I convert the digital inputs into a single value? Can I just create an Array from a bunch of digital reads?

Familiarize yourself with the available functions.
https://www.arduino.cc/reference/en/language/functions/bits-and-bytes/bitset/

Welcome to the forum

Read the values and use bitSet() to set the appropriate bits of a byte variable

If you are using a Uno or similar Arduin then note that using pins 0 and 1 is not advisable dues to them being used by the Serial interface

Thanks for the quick response. I will give this a try. I just needed a jumping off point for my coding.
Have a great holiday.

Pin 1 is often reserved for serial communication.
Maybe better to use another pin...

Probably a few ways to do it... here's a couple.

uint8_t values[8] = {0,1,1,1,1,1,1,1};  // LSB first
byte data1, data2;

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

  for (uint8_t x = 0; x < 8; x++)
  {
    if (values[x] == 1)
    {
      bitSet(data1, x);
      data2 = data2 | (1 << x); 
    }
  }

  Serial.println(data1, HEX);
  Serial.println(data2, HEX);
}

void loop()
{}

... and yeah... don't use pins 0 & 1.

@JeromeJordan note that what you need to create is not an array nor has it got 16 bits despite the topic title

Instead of creating an array from the inputs and then putting the values together, you can get the data directly from the pins.

const uint8_t pinList[8] = {2, 3, 5, 4, A0, A1, A2, A3};  // LSB first
byte data;

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

  for (size_t i = 0; i < 8; i++)
  {
    pinMode(pinList[i], INPUT_PULLUP);
  }

  data = 0;
  for (uint8_t i = 0; i < 8; i++)
  {
    if (digitalRead(pinList[i]) == HIGH)
    {
      bitSet(data, i);
    }
  }

  Serial.println(data, HEX);
}

void loop() {}
1 Like

I've been contemplating an API that would read or write "all the pins" (or at least D0-D13) into a single call. It would default to multiple digitalRead() and ORing into a uint16, but could be customized to be much faster (two port reads on Uno)

1 Like

The Mega has a port with consecutively mapped pins, on the end connector. So you can read all of those pins in one line of code.

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.