Buttonhandling.ino 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. bool buttonCurrentState[3] = {HIGH, HIGH, HIGH};
  2. bool buttonLastState[3] = {HIGH, HIGH, HIGH};
  3. unsigned long buttonDownMillis[3] = {0, 0, 0};
  4. unsigned long buttonHoldTime[3] = {0, 0, 0};
  5. bool buttonFired[3] = {false, false, false};
  6. bool buttonHoldFired[3] = {false, false, false};
  7. unsigned long lastButtonPress[3] = {0, 0, 0};
  8. int debounceTime = 120;
  9. void buttonAction(byte relnr) {
  10. lastSwitchSource[relnr] = 0;
  11. relaisToggle(relnr);
  12. }
  13. void buttonHoldAction(byte btn) {
  14. switch (btn) {
  15. case 0:
  16. mqttclient.publish(mqtt_topic_out_hold_1, mqtt_payload_out_hold_1);
  17. break;
  18. case 1:
  19. mqttclient.publish(mqtt_topic_out_hold_2, mqtt_payload_out_hold_2);
  20. break;
  21. case 2:
  22. mqttclient.publish(mqtt_topic_out_hold_3, mqtt_payload_out_hold_3);
  23. break;
  24. }
  25. }
  26. void checkButtonStates() {
  27. for (int i = 0; i < BUTTONS_COUNT; i++) {
  28. checkButtonState(i);
  29. }
  30. }
  31. void checkButtonState(byte btn) {
  32. buttonHoldTime[btn] = millis() - buttonDownMillis[btn];
  33. buttonCurrentState[btn] = digitalRead(buttons_pins[btn]);
  34. if (buttonCurrentState[btn] == LOW && buttonLastState[btn] == HIGH) { // button was unpressed and is millis() pressed
  35. buttonDownMillis[btn] = millis();
  36. buttonLastState[btn] = buttonCurrentState[btn];
  37. }
  38. else if (buttonCurrentState[btn] == LOW && buttonLastState[btn] == LOW) { // button is held
  39. if ( buttonHoldTime[btn] > debounceTime ) {
  40. buttonLastState[btn] = buttonCurrentState[btn];
  41. if ( buttonHoldTime[btn] > 750 && !buttonHoldFired[btn] ) {
  42. // button is held longer
  43. if ( (millis() - lastButtonPress[btn]) > 700 ) { // mitigate double triggering
  44. lastButtonPress[btn] = millis();
  45. Serial.print("Button ");
  46. Serial.print(btn + 1);
  47. Serial.println(" long pressed");
  48. buttonHoldAction(btn);
  49. buttonHoldFired[btn] = true;
  50. }
  51. }
  52. }
  53. }
  54. else if (buttonCurrentState[btn] == HIGH && buttonLastState[btn] == LOW) { // button is released again
  55. if (buttonHoldTime[btn] > debounceTime) { // entprellung
  56. buttonLastState[btn] = buttonCurrentState[btn];
  57. if (!buttonHoldFired[btn] && !buttonFired[btn]) {
  58. if ( (millis() - lastButtonPress[btn]) > 700 ) { // mitigate double triggering
  59. lastButtonPress[btn] = millis();
  60. Serial.print("Button ");
  61. Serial.print(btn + 1);
  62. Serial.println(" short pressed");
  63. buttonAction(btn);
  64. }
  65. }
  66. buttonFired[btn] = false;
  67. buttonHoldFired[btn] = false;
  68. }
  69. }
  70. }