Commit 66aea158 authored by Martin Natano's avatar Martin Natano

Refactor debouncing code

parent afeac558
......@@ -6,6 +6,8 @@ static const uint8_t hidReportDescriptor[] PROGMEM = {
0xa1, 0x01, // COLLECTION (Application)
0xa1, 0x00, // COLLECTION (Physical)
0x85, 0x03, // REPORT_ID (3)
// Buttons
0x05, 0x09, // USAGE_PAGE (Button)
0x19, 0x01, // USAGE_MINIMUM (Button 1)
0x29, 0x06, // USAGE_MAXIMUM (Button 6)
......@@ -15,74 +17,55 @@ static const uint8_t hidReportDescriptor[] PROGMEM = {
0x95, 0x06, // REPORT_COUNT (6)
0x81, 0x02, // INPUT (Data, Var, Abs)
// Padding
0x75, 0x01, // REPORT_SIZE (1)
0x95, 0x02, // REPORT_COUNT (2)
0x01, 0x01, // INPUT (Constant)
0xc0, // END_COLLECTION
0xc0, // END_COLLECTION
};
#define DEBOUNCE_DELAY 2
#define NBUTTONS 6
static const int button_pins[NBUTTONS] = {7, 8, 9, 10, 11, 12};
static const int buttonPins[NBUTTONS] = {7, 8, 9, 10, 11, 12};
void setup() {
int i;
pinMode(LED_BUILTIN, OUTPUT);
for (i = 0; i < NBUTTONS; i++)
pinMode(button_pins[i], INPUT_PULLUP);
pinMode(buttonPins[i], INPUT_PULLUP);
static HIDSubDescriptor node(hidReportDescriptor, sizeof(hidReportDescriptor));
HID().AppendDescriptor(&node);
}
// the loop function runs over and over again forever
void loop() {
uint8_t reportData;
uint8_t debounceBuffer[15];
static uint8_t previousReportData;
int i, j;
reportData = 0;
for (i = 0; i < NBUTTONS; i++) {
int pressed = !digitalRead(button_pins[i]);
if (pressed)
reportData |= (1 << i);
}
static uint8_t reportData;
static uint8_t buttonStates;
static unsigned long lastButtonChange[NBUTTONS];
unsigned long now;
int sendReport, i;
for (i = 14; i > 0; i--) {
debounceBuffer[i] = debounceBuffer[i-1];
}
debounceBuffer[0] = reportData;
now = millis();
sendReport = 0;
reportData = previousReportData;
for (i = 0; i < NBUTTONS; i++) {
int n = 0;
for (j = 0; j < 15; j++) {
if (debounceBuffer[j] & (1 << i))
n ++;
int pressed = !digitalRead(buttonPins[i]);
if (pressed != bitRead(buttonStates, i)) {
bitWrite(buttonStates, i, pressed);
lastButtonChange[i] = now;
}
if (reportData & (1 << i)) {
if (n == 0)
reportData &= ~(1 << i);
} else {
if (n == 15)
reportData |= (1 << i);
if (pressed != bitRead(reportData, i) && lastButtonChange[i] + DEBOUNCE_DELAY < now) {
bitWrite(reportData, i, pressed);
sendReport = 1;
}
}
if (reportData != previousReportData) {
if (sendReport) {
HID().SendReport(0x03, &reportData, sizeof(reportData));
if (reportData)
digitalWrite(LED_BUILTIN, HIGH);
else
digitalWrite(LED_BUILTIN, LOW);
previousReportData = reportData;
digitalWrite(LED_BUILTIN, reportData ? HIGH : LOW);
}
delayMicroseconds(100);
}
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment