You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

106 lines
2.1 KiB

  1. /*
  2. Connections:
  3. - Volume control potentiometer
  4. - +5V -> pot MAX
  5. - A0 -> pot sweeper (center)
  6. - GND -> pot MIN
  7. - buttons
  8. - +5V -> [1k ohm] -> common connection to buttons
  9. - D2 -> button 1
  10. -> [1M ohm] -> GND
  11. - D3 -> button 2
  12. -> [1M ohm] -> GND
  13. - D4 -> button 3
  14. -> [1M ohm] -> GND
  15. - D5 -> button 4
  16. -> [1M ohm] -> GND
  17. (or drop the resistors completely and use the internal pull-down resistors)
  18. */
  19. #include <DebounceEvent.h>
  20. const int btns = 4;
  21. const int SWITCH_DEBOUNCE_DELAY = 500;
  22. DebounceEvent switches[btns] = {
  23. DebounceEvent(2, BUTTON_SWITCH, SWITCH_DEBOUNCE_DELAY),
  24. DebounceEvent(3, BUTTON_SWITCH, SWITCH_DEBOUNCE_DELAY),
  25. DebounceEvent(4, BUTTON_SWITCH, SWITCH_DEBOUNCE_DELAY),
  26. DebounceEvent(5, BUTTON_SWITCH, SWITCH_DEBOUNCE_DELAY)
  27. };
  28. const int volumePin = A0;
  29. const int volumeRawMin = 0;
  30. const int volumeRawMax = 850;
  31. const int volumeStep = 5;
  32. int volume = -1;
  33. // === Switches ===
  34. void switchesSetup() {
  35. for (int i = 0; i < btns; i++) {
  36. sendButtonEvent(i+1, switches[i].pressed());
  37. }
  38. }
  39. void switchesLoop() {
  40. for (int i = 0; i < btns; i++) {
  41. int event = switches[i].loop();
  42. if (event != EVENT_NONE) {
  43. sendButtonEvent(i+1, switches[i].pressed());
  44. }
  45. }
  46. }
  47. // === Volume ===
  48. void volumeInit() {
  49. pinMode(volumePin, INPUT);
  50. volume = volumeRead();
  51. sendVolumeEvent();
  52. }
  53. int volumeRead() {
  54. int volumeRaw = analogRead(volumePin);
  55. return map(volumeRaw, volumeRawMin, volumeRawMax, 0, 255);
  56. }
  57. void volumeLoop() {
  58. int newVolume = volumeRead();
  59. if (abs(volume - newVolume) >= volumeStep) {
  60. volume = newVolume;
  61. sendVolumeEvent();
  62. }
  63. }
  64. // === Serial Events ===
  65. void sendEvent(char *name, int value) {
  66. Serial.print(name);
  67. Serial.print("=");
  68. Serial.println(value);
  69. }
  70. void sendVolumeEvent() {
  71. sendEvent("volume", volume);
  72. }
  73. void sendButtonEvent(int buttonNumber, int state) {
  74. String name = "button";
  75. name.concat(buttonNumber);
  76. sendEvent(name.c_str(), state);
  77. }
  78. // === MAIN ===
  79. void setup() {
  80. Serial.begin(9600);
  81. switchesSetup();
  82. volumeInit();
  83. }
  84. void loop() {
  85. switchesLoop();
  86. volumeLoop();
  87. delay(100);
  88. }