# 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"

{
}

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

{
unsigned int address = 0;
unsigned int value = 0;

if (Wire.available())
{
}
Wire.endTransmission();

for (int i = 0; i < 8; i++)
{
address += (value & (1<<i)) > 0;
}

}
``````
• A 8 position DIP switch can have 256 positions. And you are just calculating the sum of bits. Aug 20 '18 at 21:38
• First of all, you must be sure that the _address has the right i2c address of the pcf8574, then you can do a Wire.requestFrom(_address,1) and a return(Wire.read()). That's all, two lines, nothing else.
– Jot
Aug 20 '18 at 22:39
• it is unclear what this means .... `without being able to get the proper byte data` Aug 20 '18 at 23:48
• since you have only one sensor board on any given Arduino, why do you need a unique address on the sensor board? Aug 20 '18 at 23:50
• determine what is the value of `Wire.read()` at this line `value = Wire.read();` .... you may be surprised Aug 21 '18 at 0:25

As @jsotola noted the solution was simple:

``````int DipSwitchI2C::read()
{
unsigned int address = 1;

if (Wire.available())
{
}
Wire.endTransmission();

}
``````

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<10; i++){