Hello all,
After several projects using DIP switches, with each switch connecting to a single input, I read an interesting article about how to use a resistor ladder and single analog input to read DIP switch settings. Especially when miniaturizing projects with often a limited number of I/O ports, this comes in handy.
First part of this to select your DIP switch and resistors. See attached picture for my particular setup. Once you build this with real components you'll need to run the following code to find your table values:
const int ledPin = 13;
int previousA0Value = 0;
void setup()
{
pinMode(ledPin, OUTPUT);
Serial.begin(9600);
}
void loop()
{
int A0value = analogRead(A0);
if ( A0value != previousA0Value ) {
Serial.print("value = "); Serial.println(A0value);
previousA0Value = A0value;
}
digitalWrite(ledPin, HIGH); delay(500);
digitalWrite(ledPin, LOW); delay(500);
}
If your components are exactly to specification, you will find the following values for all 16 combinations:
0, 114, 205, 279, //0, 1, 2, 3
341, 394, 438, 477, //4, 5, 6, 7
512, 542, 568, 592, //8, 9, 10, 11
614, 633, 651, 667 //12, 13, 14, 15
This table can then be used in code to find your DIP Switch setting, which then can be used for any other logic statements in your code. This is where I run into a roadblock; it seems I can't get the DIP switch setting to show up on the serial monitor. Here is the code I'm running (please note that I left void loop content to determine table values in the code, but it can be omitted):
const int ledPin = 13;
int previousA0Value = 0;
void setup()
{
pinMode(ledPin, OUTPUT);
Serial.begin(9600);
}
void loop()
{
int A0value = analogRead(A0);
if ( A0value != previousA0Value ) {
Serial.print("value = "); Serial.println(A0value);
previousA0Value = A0value;
}
digitalWrite(ledPin, HIGH); delay(500);
digitalWrite(ledPin, LOW); delay(500);
}
byte readIDSwitch(){
byte id;
// this table is derived from measuring voltages / resistance
// from the resistor ladder circuit
const int id_table[] = {
0, 114, 205, 279, //0, 1, 2, 3
341, 394, 438, 477, //4, 5, 6, 7
512, 542, 568, 592, //8, 9, 10, 11
614, 633, 651, 667 //12, 13, 14, 15
};
const int epsilon = 10;
short v = analogRead(A0); //Wherever the signal goes to from resistors
Serial.println("buttons " + String(v) );
// use a lookup table, because the voltages are not linear
for (int i = 0 ; i < 16; i++ ) {
if ( (id_table[i] - epsilon < v) &&
(v < id_table[i] + epsilon) ) {
id = i;
Serial.println("id " + String(id) );
return id;
}
}
return 0;
}
I'm fairly new at this, and spent about a week on Google and this forum to look for tutorials to no avail. What am I doing wrong?