Skip to content

Commit 7865619

Browse files
authored
feat(matter): improved the button control
1 parent cb1759b commit 7865619

File tree

1 file changed

+28
-8
lines changed

1 file changed

+28
-8
lines changed

libraries/Matter/examples/MatterOnOffLight/MatterOnOffLight.ino

Lines changed: 28 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -66,8 +66,12 @@ void setup() {
6666
Matter.begin();
6767
}
6868

69-
uint32_t lastMillis = millis();
70-
const uint32_t debouceTime = 70; // button debounce time
69+
// Button control
70+
uint32_t button_time_stamp = 0; // debouncing control
71+
bool button_state = false; // false = released | true = pressed
72+
const uint32_t debouceTime = 250; // button debouncing time (ms)
73+
const uint32_t decommissioningTimeout = 10000; // keep the button pressed for 10s to decommission the light
74+
7175
void loop() {
7276
// Check Matter Light Commissioning state
7377
if (!Matter.isDeviceCommissioned()) {
@@ -92,13 +96,29 @@ void loop() {
9296
Serial.printf("Initial state: %s\r\n", OnOffLight.getOnOff() ? "ON" : "OFF");
9397
setLightOnOff(OnOffLight.getOnOff()); // configure the Light based on initial state
9498
Serial.println("Matter Node is commissioned and connected to Wi-Fi. Ready for use.");
95-
delay(10000);
9699
}
97100

98-
// Onboard User Button is used as a Light toggle switch
99-
if (digitalRead(buttonPin) == 0 && millis() - lastMillis > debouceTime) {
100-
Serial.println("User button pressed. Toggling Light!");
101-
lastMillis = millis();
101+
// A button is also used to control the light
102+
// Check if the button has been pressed
103+
if (digitalRead(buttonPin) == LOW && !button_state) {
104+
// deals with button debouncing
105+
button_time_stamp = millis(); // record the time while the button is pressed.
106+
button_state = true; // pressed.
107+
}
108+
109+
// Onboard User Button is used as a Light toggle switch or to decommission it
110+
uint32_t time_diff = millis() - button_time_stamp;
111+
if (button_state && time_diff > debouceTime && digitalRead(buttonPin) == HIGH) {
112+
button_state = false; // released
113+
// Toggle button is released - toggle the light
114+
Serial.println("User button released. Toggling Light!");
102115
OnOffLight.toggle(); // Matter Controller also can see the change
116+
117+
// Factory reset is triggered if the button is pressed longer than 10 seconds
118+
if (time_diff > decommissioningTimeout) {
119+
Serial.println("Decommissioning the Light Matter Accessory. It shall be commissioned again.");
120+
OnOffLight.setOnOff(false); // turn the light off
121+
Matter.decommission();
122+
}
103123
}
104-
}
124+
}

0 commit comments

Comments
 (0)