DIP switch with Arduino

Here is a useful function to read DIP switches with Arduino. Wire the switches to ground, as this uses pull-up resistors:

Photograph of a DIP switch

 

  1. int myDipPins[] = {2, 3, 4, 5, 6}; //DIP Switch Pins
  2. void setup()
  3. {
  4. Serial.begin(9600);
  5. for(int i = 0; i <= 4; i++)
  6. {
  7. pinMode(myDipPins[i], INPUT);       //Set DIP switch pins as inputs
  8. digitalWrite(myDipPins[i], HIGH); //Set pullup resistor on DIP switch pins
  9. }
  10. delay(100);
  11. }
  12. void loop()
  13. {
  14. byte DIPValue = readDIP(myDipPins, 5);
  15. Serial.print(DIPValue, BIN);
  16. Serial.print(“\n”);
  17. switch (DIPValue)
  18. {
  19. case B00000:
  20. Serial.print(“Match 00000\n”);
  21. break;
  22. case B00100:
  23. Serial.print(“Match 00100\n”);
  24. break;
  25. case B11011:
  26. Serial.print(“Match 11011\n”);
  27. break;
  28. case B11111:
  29. Serial.print(“Match 11111\n”);
  30. break;
  31. case B01001:
  32. Serial.print(“Match 01001\n”);
  33. break;
  34. case B10000:
  35. Serial.print(“Match 10000\n”);
  36. break;
  37. }
  38. delay(1000);
  39. }
  40. //Read binary from DIP switches
  41. byte readDIP(int* dipPins, int numPins)
  42. {
  43. byte j = 0;
  44. //byte j;
  45. //Get the switches state
  46. for(int i = 0; i < numPins; i++)
  47. {
  48. if (!digitalRead(dipPins[i]))
  49. {
  50. j += 1<<(numPins – 1 – i);
  51. }
  52. }
  53. return j; //Return result
  54. }

 

 

Be sure to check ” and ‘ symbols haven’t been made fancy by WordPress, or you’ll have errors in your code.