New button template
Some checks failed
CI / Test (Linux) (push) Has been cancelled
CI / Test (Windows MSVC) (push) Has been cancelled
CI / Clippy (push) Has been cancelled
CI / Format (push) Has been cancelled

This commit is contained in:
Eric Ratliff
2026-02-22 17:06:02 -06:00
parent 578b5f02c0
commit e12608370a
9 changed files with 898 additions and 5 deletions

View File

@@ -0,0 +1,77 @@
#ifndef APP_H
#define APP_H
#include <hal.h>
#include "button.h"
#include <stdio.h>
/*
* ButtonApp -- Detects button presses and reports to Serial.
*
* Uses polling with edge detection: only triggers on the transition
* from released to pressed (rising edge). Holding the button does
* not generate repeated messages.
*
* Each press prints:
* Button pressed! (count: 1)
*
* The button is injected through the Button interface, so this
* class works with real hardware, mocks, or simulations.
*
* Wiring (active-low, no external resistor needed):
* Digital pin 2 -> one leg of the button
* GND -> other leg of the button
* Set pin mode to INPUT_PULLUP in begin().
*/
class ButtonApp {
public:
static constexpr uint8_t BUTTON_PIN = 2;
ButtonApp(Hal* hal, Button* button)
: hal_(hal)
, button_(button)
, was_pressed_(false)
, press_count_(0)
{}
// Call once from setup()
void begin() {
hal_->serialBegin(115200);
hal_->pinMode(BUTTON_PIN, INPUT_PULLUP);
hal_->serialPrintln("ButtonApp ready -- press the button!");
// Read initial state so we don't false-trigger on startup
was_pressed_ = button_->isPressed();
}
// Call repeatedly from loop()
void update() {
bool pressed_now = button_->isPressed();
// Rising edge: was released, now pressed
if (pressed_now && !was_pressed_) {
press_count_++;
onPress();
}
was_pressed_ = pressed_now;
}
// -- Accessors for testing ------------------------------------------------
int pressCount() const { return press_count_; }
bool wasPressed() const { return was_pressed_; }
private:
void onPress() {
char buf[40];
snprintf(buf, sizeof(buf), "Button pressed! (count: %d)", press_count_);
hal_->serialPrintln(buf);
}
Hal* hal_;
Button* button_;
bool was_pressed_;
int press_count_;
};
#endif // APP_H