Here is a useful function to read DIP switches with Arduino. Wire the switches to ground, as this uses pull-up resistors:
- int myDipPins[] = {2, 3, 4, 5, 6}; //DIP Switch Pins
- void setup()
- {
- Serial.begin(9600);
- for(int i = 0; i <= 4; i++)
- {
- pinMode(myDipPins[i], INPUT); //Set DIP switch pins as inputs
- digitalWrite(myDipPins[i], HIGH); //Set pullup resistor on DIP switch pins
- }
- delay(100);
- }
- void loop()
- {
- byte DIPValue = readDIP(myDipPins, 5);
- Serial.print(DIPValue, BIN);
- Serial.print(“\n”);
- switch (DIPValue)
- {
- case B00000:
- Serial.print(“Match 00000\n”);
- break;
- case B00100:
- Serial.print(“Match 00100\n”);
- break;
- case B11011:
- Serial.print(“Match 11011\n”);
- break;
- case B11111:
- Serial.print(“Match 11111\n”);
- break;
- case B01001:
- Serial.print(“Match 01001\n”);
- break;
- case B10000:
- Serial.print(“Match 10000\n”);
- break;
- }
- delay(1000);
- }
- //Read binary from DIP switches
- byte readDIP(int* dipPins, int numPins)
- {
- byte j = 0;
- //byte j;
- //Get the switches state
- for(int i = 0; i < numPins; i++)
- {
- if (!digitalRead(dipPins[i]))
- {
- j += 1«(numPins — 1 — i);
- }
- }
- return j; //Return result
- }
Be sure to check ” and ’ symbols haven’t been made fancy by WordPress, or you’ll have errors in your code.