Buttonhandling.ino 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  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. mqttclient.publish(mqtt_topic_out_hold[btn], mqtt_payload_out_hold[btn]);
  14. }
  15. void checkButtonStates() {
  16. for (int i=0; i < BUTTONS_COUNT; i++) {
  17. checkButtonState(i);
  18. }
  19. }
  20. void checkButtonState(byte btn) {
  21. buttonHoldTime[btn] = millis() - buttonDownMillis[btn];
  22. buttonCurrentState[btn] = digitalRead(buttons_pins[btn]);
  23. if (buttonCurrentState[btn] == LOW && buttonLastState[btn] == HIGH) { // button was unpressed and is millis() pressed
  24. buttonDownMillis[btn] = millis();
  25. buttonLastState[btn] = buttonCurrentState[btn];
  26. }
  27. else if (buttonCurrentState[btn] == LOW && buttonLastState[btn] == LOW) { // button is held
  28. if ( buttonHoldTime[btn] > debounceTime ) {
  29. buttonLastState[btn] = buttonCurrentState[btn];
  30. if ( buttonHoldTime[btn] > 750 && !buttonHoldFired[btn] ) {
  31. // button is held longer
  32. Serial.print("Button ");
  33. Serial.print(btn + 1);
  34. Serial.println(" long pressed");
  35. buttonHoldAction(btn);
  36. buttonHoldFired[btn] = true;
  37. }
  38. }
  39. }
  40. else if (buttonCurrentState[btn] == HIGH && buttonLastState[btn] == LOW) { // button is released again
  41. if (buttonHoldTime[btn] > debounceTime) { // entprellung
  42. buttonLastState[btn] = buttonCurrentState[btn];
  43. if (!buttonHoldFired[btn] && !buttonFired[btn]) {
  44. Serial.print("Button ");
  45. Serial.print(btn + 1);
  46. Serial.println(" short pressed");
  47. buttonAction(btn);
  48. }
  49. buttonFired[btn] = false;
  50. buttonHoldFired[btn] = false;
  51. }
  52. }
  53. }