Files
anvil/libraries/button/src/button_digital.h
2026-02-22 07:47:51 -06:00

58 lines
1.6 KiB
C++

#ifndef BUTTON_DIGITAL_H
#define BUTTON_DIGITAL_H
#include "button.h"
#include "hal.h"
/*
* Button -- Real hardware implementation (digital read).
*
* Reads a physical pushbutton connected to a digital pin.
* Supports both wiring configurations:
*
* Active-low (most common, use INPUT_PULLUP):
* Pin -> Button -> GND
* Reads LOW when pressed, HIGH when released.
* Set active_low = true (default).
*
* Active-high (external pull-down resistor):
* Pin -> Button -> VCC, with pull-down to GND
* Reads HIGH when pressed, LOW when released.
* Set active_low = false.
*
* Wiring (active-low, no external resistor needed):
* Digital pin -> one leg of button
* GND -> other leg of button
* Set pin mode to INPUT_PULLUP in your sketch.
*
* Note: This implementation does NOT debounce. If your application
* needs debounce (most do), implement it in your app logic -- that
* way you can test it with the mock and simulator.
*/
class ButtonDigital : public Button {
public:
/// Create a button on the given digital pin.
/// active_low: true if pressed reads LOW (default, use with INPUT_PULLUP).
ButtonDigital(Hal* hal, uint8_t pin, bool active_low = true)
: hal_(hal)
, pin_(pin)
, active_low_(active_low)
{}
bool isPressed() override {
int state = hal_->digitalRead(pin_);
return active_low_ ? (state == LOW) : (state == HIGH);
}
int readState() override {
return hal_->digitalRead(pin_);
}
private:
Hal* hal_;
uint8_t pin_;
bool active_low_;
};
#endif // BUTTON_DIGITAL_H