DIP switch with Arduino

DIP switch with Arduino

Here is a use­ful func­tion to read DIP switch­es with Arduino. Wire the switch­es to ground, as this uses pull-up resis­tors:

Photograph of a DIP switch

 

  1. int myDip­Pins[] = {2, 3, 4, 5, 6}; //DIP Switch Pins
  2. void set­up()
  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 resis­tor on DIP switch pins
  9. }
  10. delay(100);
  11. }
  12. void loop()
  13. {
  14. byte DIP­Val­ue = readDIP(myDipPins, 5);
  15. Serial.print(DIPValue, BIN);
  16. Serial.print(“\n”);
  17. switch (DIP­Val­ue)
  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 bina­ry from DIP switches
  41. byte readDIP(int* dip­Pins, int numPins)
  42. {
  43. byte j = 0;
  44. //byte j;
  45. //Get the switch­es 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 ’ sym­bols haven’t been made fan­cy by Word­Press, or you’ll have errors in your code.

Continuing electronics

Continuing electronics

I’m con­tin­u­ing my learn­ing of elec­tron­ics, and I seem to be much bet­ter at it than the first time around. It is sat­is­fy­ing when a cir­cuit works first time.