Go Down

Topic: Programming Multi Integers Concatenation (Read 864 times) previous topic - next topic



I have a Arduino Diecimila up and running.

3 pins on the Arduino are setup as inputs.
I have a device connected to the Arduino on the 3 input pins.

The device ouputs a single integer value of 1 (High) or 0 (Low).
So Arduino sees 3 values say
input1 sees 1
input2 sees 0
input3 sees 1

How can I assign these values to a single variable?
Or in other words if I have a variable assigned to each value how do I concatenate them so that I have a single string that looks like this: 101

Based on that single string I would then do comparisons like;
if 101 do this, if 111 do this, if 001 do this.



Aug 08, 2008, 06:33 pm Last Edit: Aug 09, 2008, 06:45 am by mem Reason: 1
Hi Ani,

The most common way of doing that is to treat the three inputs as binary values. You can do that in a number of ways.

For example:
 Value  =  (input3 *  4) + (input2 * 2) + input1;

In your example where input1 and input 3 are high and input2 is low, value is set equalt to 5 which is binary 101;

You could also do it by shifting bits:
 Value =  (input3 << 2) + (input2 <<1) + input1;

There is no difference between these two approaches, the compiler will actually produce identical machine code.

A good C reference  on binary numbers and bit arithmetic can give you more information on how to work with this.

Have fun!


Hey, thanks for the reply.
That was very helpful and works for me.


Glad to help. I just noticed (and quitely fixed) a typo in the example, its now correct


You could also do it by shifting bits:
 Value =  (input3 < 2) + (input2 <1) + input1;

Did the second character of the << get lost somewhere?




Hey you can also group your inputs onto 1 port and read them all at once.  For example put you inputs on digital pins 8,9,10.  According to the "Ardino pin mapping" document these correspond to PB0, PB1,PB2.  These can be read in mass with "inputvariable = PINB"  Then shift or masks out the high bits.

This is more difficult to understand than the other posts but it has the advantage of reading all 3 inputs at the same instant. (in case you care)

As has been mentioned check out the binary math tutorials.

Good Luck!


Go Up

Please enter a valid email to subscribe

Confirm your email address

We need to confirm your email address.
To complete the subscription, please click the link in the email we just sent you.

Thank you for subscribing!

via Egeo 16
Torino, 10131