Calculate sensor unique address with a 8 position DIP Switch I have a large amount of sensor boards that I need to be able to configure setting unique addresses. Each sensor is attached to it's own arduino, I'm using a 8 position DIP switch for setting the address.

I have tried diferent approaches. When I switch On and OFF I get random values. I understood that I would be able to get up to 255 possible positions, but without being able to get the proper byte data I would have to manually code each possibility, which seems wrong.

Schematic :



Code

#include "DipSwitchI2C.h"

DipSwitchI2C::DipSwitchI2C(int address)
{
    _address = address;
}

void DipSwitchI2C::begin()
{
    Wire.begin();
}

int DipSwitchI2C::read()
{
    unsigned int address = 0;
    unsigned int value = 0;

    Wire.requestFrom(_address, 1);
    if (Wire.available())
    {
        value = Wire.read();
    }
    Wire.endTransmission();

    for (int i = 0; i &lt; 8; i++)
    {
        address += (value &amp; (1&lt;&lt;i)) &gt; 0;
    }

    return address;
}
Assuming that your switches are on pins 2-9 on an UNO.  Change pins to match what you actually have. 

byte addressVal = 0;
for(int i = 2: i&lt;10; i++){
    addressVal &lt;&lt;= 1;
    addressVal += digitalRead(i);
}


This will check each switch and add a 1 to the end of the byte.  On each iteration it shifts the contents of that byte 1 place to the left.  After it reads all the pins you have a byte with a value 0 to 255 depending on the states of the pins.