Skip to content

Commit 4e706ab

Browse files
committed
buttons: rewrite the button debouncer
The previous implementation actually did nothing.
1 parent 8f6ae65 commit 4e706ab

File tree

1 file changed

+22
-14
lines changed
  • src/firmware/application/io/buttons

1 file changed

+22
-14
lines changed

src/firmware/application/io/buttons/Filter.h

Lines changed: 22 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -31,12 +31,15 @@ namespace io
3131

3232
bool isFiltered(size_t index, uint8_t& numberOfReadings, uint16_t& states) override
3333
{
34-
// this is a board-optimized debouncer
35-
// by the time processing of buttons takes place, more than 5ms has already passed
36-
// 5ms is release debounce time
37-
// take into account only two latest readings
38-
// if any of those is 1 (pressed), consider the button pressed
39-
// otherwise, button is considered released
34+
/*
35+
This filter makes use of the fact that the difference between digital readings is 1ms.
36+
If the _debounceState is 0xFF or 0x00, the button is considered debounced. Since all bits
37+
are used in a byte variable, and each reading takes 1ms, the debounce time is 8ms.
38+
39+
Technically, two readings are possible since maximum number of board readings is 16, and
40+
full debounce cycle takes 8 readings. Assume the boards aren't that slow that the difference
41+
between two calls of this function for the same button index is more than 8ms.
42+
*/
4043

4144
numberOfReadings = 1;
4245

@@ -47,23 +50,28 @@ namespace io
4750
return true;
4851
}
4952

50-
states &= 0x03;
53+
_debounceState[index] <<= numberOfReadings;
54+
_debounceState[index] |= static_cast<uint8_t>(states);
5155

52-
if (numberOfReadings >= 2)
56+
if (_debounceState[index] == 0xFF)
57+
{
58+
states = 1;
59+
}
60+
else if (_debounceState[index] == 0)
5361
{
54-
if (states)
55-
{
56-
// button is pressed
57-
states = 0x01;
58-
}
62+
states = 0;
5963
}
6064
else
6165
{
62-
states &= 0x01;
66+
// not debounced yet
67+
return false;
6368
}
6469

6570
return true;
6671
}
72+
73+
private:
74+
uint8_t _debounceState[io::Buttons::Collection::SIZE(io::Buttons::GROUP_DIGITAL_INPUTS)] = {};
6775
};
6876
} // namespace io
6977

0 commit comments

Comments
 (0)