Concatenate Array Elements into a Single Variable

Hello.

I put a sketch together that reads the high or low status of the pins on a Dip Switch and stores the 1s or 0s in an array. It's a mini test sketch designed to be a proof of concept before I add the code to the main sketch.

The plan is to concatenate my 1s and 0s array elements into a single binary variable. I have looked to see if there is such a function but came up with nothing.

After searching I tried:

void loop() {

for (int i = 0; i < PinCount; i++) {
DipSwitchValues = digitalRead(ArduinoPins);
}

DipSwitchRead = 0;

for (int i = 0; i < PinCount; i++){
DipSwitchRead = DipSwitchRead + DipSwitchValues;
}
}

This just adds up the array elements , which on a second look makes sense.

This is the whole sketch:

//  --------------------------------------------
//  Avery Way Observatory
//  Rain Sensor Safety Monitor V7.0
//  Dip Switch Sensitivity Code Testing - sketch_apr14b
//  15/04/23
//  Graeme Durden FRAS
//  --------------------------------------------

int ArduinoPins[] = {                                 //  Array of Arduino Pin Numbers 
  4, 5, 6, 7, 8, 9, 10, 11
};   
int DipSwitchPins[] = {                               //  Array of Dip Switch Pin Numbers 
  1, 2, 3, 4, 5, 6, 7, 8
};   
int DipSwitchValues[] = {                             //  Array of Dip Switch Pin Values 
  0, 0, 0, 0, 0, 0, 0, 0
};    
int PinCount = 8;                                     //  Array Length
int Sensitivity = 0;                                  //  Sensitivity Value based on Dip Switch Settings
int DipSwitchRead = 0;                                //  Dip Switch Values Concatenated
int DelayTimer = 3000;                                //  Void Loop Delay  


void setup() {

  Serial.begin(9600);                                 //  Initialize the Serial Port

  for (int i = 0; i < PinCount; i++) {                //  Pin Mode for Loop
    pinMode(ArduinoPins[i], INPUT_PULLUP);            //  Set Arduino Pins to Input Pullup
  }
}


void loop() {

  for (int i = 0; i < PinCount; i++) {
    DipSwitchValues[i] = digitalRead(ArduinoPins[i]); //  Read Pin Values
  }
  DipSwitchRead = 0;
  //  Sensitivity = ???
  for (int i = 0; i < PinCount; i++){
    DipSwitchRead = DipSwitchRead + DipSwitchValues[i];
  }
  
  for (int i = 0; i < PinCount; i++) {                //  Print DipSwitch Values to the Serial Port
    Serial.print("DipSwitchValue ");
    Serial.print(DipSwitchPins[i]);
    Serial.print(" = ");
    Serial.println(DipSwitchValues[i]);
    Serial.print(" DipSwitchRead ");
    Serial.println(DipSwitchRead);
  }
  
  Serial.println("");

  delay(DelayTimer);                                  //  Void Loop Delay  
}

Is it possible to read all 8 array elements 0s and 1s and store them, in order, in a variable so that I then have a binary number that represents the dip switch settings?

Thanks

Regards

Graeme

Why not save them in the bits of a variable to start with instead of an array ?

CORRECTION
Take a look at the bitSet() bitWrite() function for a start

1 Like

Take a look at bitWrite in the reference

2 Likes
//  --------------------------------------------
//  Avery Way Observatory
//  Rain Sensor Safety Monitor V7.0
//  Dip Switch Sensitivity Code Testing - sketch_apr14b
//  15/04/23
//  Graeme Durden FRAS
//  -------------------------------------------

const byte PinCount = 8;                                     //  Array Length
const byte ArduinoPins[PinCount] = {                                 //  Array of Arduino Pin Numbers 
  4, 5, 6, 7, 8, 9, 10, 11
};   

byte DipSwitchValues;                             //  byte containing Dip Switch Pin values 

int Sensitivity = 0;                                  //  Sensitivity Value based on Dip Switch Settings
int DelayTimer = 3000;                                //  Void Loop Delay  


void setup() {

  Serial.begin(9600);                                 //  Initialize the Serial Port

  for (byte i = 0; i < PinCount; i++) {                //  Pin Mode for Loop
    pinMode(ArduinoPins[i], INPUT_PULLUP);            //  Set Arduino Pins to Input Pullup
  }
}


void loop() {
  DipSwitchRead = 0;
  for (byte i = 0; i < PinCount; i++) {
    byte v = 0;
    if (digitalRead(ArduinoPins[i]) == HIGH) v = 1;
    bitWrite(DipSwitchValues, i, v); //  Read Pin Values
    DipSwitchRead += v;
    Serial.print("DipSwitchValue ");
    Serial.print(i);
    Serial.print(" = ");
    Serial.println(v);
  }

  Serial.print(" DipSwitchRead ");
  Serial.println(DipSwitchRead);
  
  Serial.println("");

  delay(DelayTimer);                                  //  Void Loop Delay  
}
1 Like

I'd like to see

  Serial.print(" DipSwitchValues ");
  Serial.println(DipSwitchValues);

and might

  Serial.print(" DipSwitchValues ");
  Serial.println(DipSwitchValues, HEX);

or

  Serial.print(" DipSwitchValues ");
  Serial.println(DipSwitchValues, BIN);

since we looking at bits.

a7

1 Like

why not (tested with A1, A2, A3 pins)

const byte ArduinoPins[] = { 4, 5, 6, 7,   8, A1, A2, A3 };
const int PinCount = sizeof(ArduinoPins);

// -----------------------------------------------------------------------------
void loop ()
{
    unsigned bits = 0;

    for (int i = 0; i < PinCount; i++) {
        bits <<= 1;
        bits  |= digitalRead (ArduinoPins[i]);
    }

    Serial.println (bits, HEX);

    delay (1000);
}

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

    for (int i = 0; i < PinCount; i++) 
        pinMode (ArduinoPins[i], INPUT_PULLUP);
}
1 Like

Thanks for the help everybody, the support here is brilliant!

The forum auto suggested another thread as a response (that I can't find now!) This other thread used: x = (digitalRead (4))+(digitalRead (5)*2)+(digitalRead (6)*4)+(digitalRead (7)*8)+etc.

It would be more elegant in a for loop, but it does the job with a decimal result and I understand the code!

Cheers

Regards

Graeme

Since you asked, I guess...

Bit-shifting, binary and/or operators etc. are not easy for a beginner to understand, and very easy for them to get wrong. So Arduino provided ready-made functions like bitRead(), bitWrite() etc. I used those so it would be less scary.

We experts all know that LOW==0 and HIGH==1, but should we be encouraging beginners to make assumptions like that? This particular assumption is pretty safe, but beginners might learn that it's generally ok to make those kind of assumptions.

Ah, no. Like everything else, and no matter which way you do it, your way, my way, @gcjr 's way... it's all binary!

As the noob here, I have to say, grateful as I am, there's a lot in the responses here that I have no current understanding of. bitRead() and bitWrite() included. But I am very much enjoying learning Arduino coding.

Again, as the noob here I am reticent to disagree with the experts, but, the code I quoted takes the 1st binary digit, adds the 2nd binary digit multiplied by 2, adds the 3rd binary digit multiplied by 4, etc. In this way the dip switch binary readings are converted to decimal.

Graeme

The code you like and understand is the best. Revisit the other ideas when you need to, there are always many ways to do one thing.

If you didn't notice, those multiplicands 1, 2, 4, 8 and so forth are powers of two, and would be referred to in the sum as "weights" giving each digitalRead() value you gather control over one bit in the final value you calculate.

A first stop might be to take a look at the code for bitWrite() and bitRead() which manage that by shifting, which in binary is like multiple or dividing by… 2.*

No escaping binary, especially with this kind of low level real world programming.

* Well I looked and bitWrite() just calls bitSet() or bitClear() as appropriate. Both those use shifting to get at the nominated bit.

a7

do you understand what a shift (<<) is? and what OR (|) is?
(these fundamental digital logic operations)

What happened when you went to the documentation page? They are explained there. Did you have specific questions or issues?

No and yes.

Not sure what's happening there.

My history is high voltage rather than low voltage. I build electrical HV substations so I'm more used to 33kV than 5V! I've done some VBA and HTML but my Arduino is new to me.

Graeme

Yes, they are explained there but the forum auto suggested thread provided an answer to my question. And...

I'm sure I'll get into the Arduino coding more but I'm primarily an astrophotographer using my Arduino to detect a change of state on a sensor when it rains and passing that on to my astrophotography software which then sends a notification to my phone to wake me up when I've nodded off on the settee!

Graeme

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