New button template
This commit is contained in:
77
templates/button/lib/app/__name___app.h.tmpl
Normal file
77
templates/button/lib/app/__name___app.h.tmpl
Normal 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
|
||||
Reference in New Issue
Block a user