Buttonhandling.ino 2.1 KB

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