Hi all, just thought I'd leave this here as i couldn't find it myself so I wrote it for anyone to use:
Using a binary rotary micro switch (eeco micro dip 3500) to control cases.
// Pins connected to the rotary dip switch using the values 1,2,4,5
#define SWITCH_PIN_1 7
#define SWITCH_PIN_2 4
#define SWITCH_PIN_4 6
#define SWITCH_PIN_8 5
const int switchPins[4] = {SWITCH_PIN_1, SWITCH_PIN_2, SWITCH_PIN_4, SWITCH_PIN_8};
int sizeofswitch = sizeof(switchPins) / sizeof(int);
void setup() {
// Configure switch pins as inputs
Serial.begin(57600);
Serial.println("Power on ...");
Serial.println(sizeofswitch);
pinMode(SWITCH_PIN_1, INPUT_PULLUP);
Serial.println("Pin");
Serial.println(SWITCH_PIN_1);
Serial.println("turned on");
pinMode(SWITCH_PIN_2, INPUT_PULLUP);
Serial.println("Pin");
Serial.println(SWITCH_PIN_2);
Serial.println("turned on");
pinMode(SWITCH_PIN_4, INPUT_PULLUP);
Serial.println("Pin");
Serial.println(SWITCH_PIN_4);
Serial.println("turned on");
pinMode(SWITCH_PIN_8, INPUT_PULLUP);
Serial.println("Pin");
Serial.println(SWITCH_PIN_8);
Serial.println("turned on");
}
void loop() {
int value = readDipSwitch();
switch (value) {
case 0:
// Perform action for value 0
// ...
Serial.println("0");
break;
case 1:
// Perform action for value 1
// ...
Serial.println("1");
break;
case 2:
// Perform action for value 2
// ...
Serial.println("2");
break;
case 3:
// Perform action for value 3
// ...
Serial.println("3");
break;
case 4:
// Perform action for value 4
// ...
Serial.println("4");
break;
case 5:
// Perform action for value 5
// ...
Serial.println("5");
break;
case 6:
// Perform action for value 6
// ...
break;
case 7:
// Perform action for value 7
// ...
break;
case 8:
// Perform action for value 8
// ...
break;
case 9:
// Perform action for value 9
// ...
break;
// Add more cases as needed
default:
// Default action if the value doesn't match any case
// ...
break;
}
}
int readDipSwitch() {
int value = 0;
// Read the state of each switch pin
for (int k = 0; k < sizeofswitch; k++) {
if (digitalRead(switchPins[k]) == HIGH) {
value |= (1 << k);// If the pin is HIGH, set the corresponding bit in the value
}
}
return value;
}
Many thanks.