Rework the joystick code to use the Bounce2 library.

This commit is contained in:
2015-11-13 00:45:38 -05:00
parent 9ae0777c6b
commit f0cfcdc90d
3 changed files with 19 additions and 31 deletions

View File

@ -15,11 +15,6 @@ bool operator !=(JoyReport a, JoyReport b){
return !(a == b);
}
uint8_t _InvertSignal(uint8_t signal) {
if (signal == HIGH) return LOW;
else return HIGH;
}
Joystick::Joystick(bool debug) {
_debug = debug;
_num_buttons = 0;
@ -42,15 +37,13 @@ void Joystick::Init() {
}
void Joystick::AddButton(uint8_t pin, ButtonType type, bool pullup) {
if (pullup) pinMode(pin, INPUT_PULLUP);
else pinMode(pin, INPUT);
uint8_t mode;
if (pullup) mode = INPUT_PULLUP;
else mode = INPUT;
Button button;
button.pin = pin;
button.type = type;
if (pullup) button.last_state = _InvertSignal(digitalRead(pin));
else button.last_state = digitalRead(pin);
button.pullup = pullup;
button.bouncer.attach(pin, mode);
_buttons[_num_buttons] = button;
_num_buttons++;
@ -79,7 +72,7 @@ void Joystick::Update() {
JoyReport oldReport = _joyReport;
for (int i = 0; i < _num_buttons; i++) {
_UpdateButton(_buttons[i], i);
_UpdateButton(i);
}
for (int i = 0; i < _num_axes; i++) {
@ -155,21 +148,20 @@ void Joystick::Write() {
delay(250);
}
void Joystick::_UpdateButton(Button& button, uint8_t index) {
uint8_t value = digitalRead(button.pin);
// Treat pullup-resistor inputs as basically backwards.
if (button.pullup) value = _InvertSignal(value);
void Joystick::_UpdateButton(uint8_t index) {
Button button = _buttons[index];
bool changed = button.debouncer.update();
switch (button.type) {
case BUTTON_LATCHED:
if (value == HIGH && button.last_state != HIGH) PressButton(index);
else if (value == LOW && button.last_state != LOW) ReleaseButton(index);
if (button.debouncer.rose()) PressButton(index);
else if (button.debouncer.fell()) ReleaseButton(index);
break;
case BUTTON_PULSED:
if (value == HIGH && button.last_state == LOW) PressButton(index);
if button.debouncer.rose() PressButton(index);
break;
case BUTTON_PULSED_DOUBLE_ACTION:
if (value != button.last_state) PressButton(index);
if (changed) PressButton(index);
break;
default:
if (_debug) {
@ -177,8 +169,6 @@ void Joystick::_UpdateButton(Button& button, uint8_t index) {
Serial.println(button.type);
}
}
button.last_state = value;
}
void Joystick::_UpdateAxis(uint8_t index) {