77 lines
1.5 KiB
C++
77 lines
1.5 KiB
C++
/*
|
|
* peripherals_button.hpp
|
|
*
|
|
* Created on: Apr 17, 2021
|
|
* Author: erki
|
|
*/
|
|
|
|
#ifndef PERIPHERALS_BUTTON_HPP_
|
|
#define PERIPHERALS_BUTTON_HPP_
|
|
|
|
#include <cstdint>
|
|
|
|
namespace Peripherals
|
|
{
|
|
|
|
enum class ButtonPress : std::uint32_t
|
|
{
|
|
NOT_PRESSED,
|
|
SHORT_PRESS,
|
|
LONG_PRESS
|
|
};
|
|
|
|
template<typename G, typename H>
|
|
class Button
|
|
{
|
|
public:
|
|
using gpio = G;
|
|
using hal = H;
|
|
|
|
static constexpr std::uint32_t TIMEOUT_SHORT_PRESS = 50;
|
|
static constexpr std::uint32_t TIMEOUT_LONG_PRESS = 500;
|
|
|
|
Button() = delete;
|
|
explicit Button(const gpio& sw)
|
|
: _sw(sw)
|
|
{}
|
|
|
|
void update()
|
|
{
|
|
const bool is_pressed = _sw.Read();
|
|
ButtonPress new_state = ButtonPress::NOT_PRESSED;
|
|
|
|
if (is_pressed && !_was_pressed)
|
|
{
|
|
_time_pressed_down = hal::GetMillis();
|
|
} else if (!is_pressed && _was_pressed)
|
|
{
|
|
const std::uint32_t time_held = hal::GetMillis() - _time_pressed_down;
|
|
if (time_held > TIMEOUT_LONG_PRESS)
|
|
new_state = ButtonPress::LONG_PRESS;
|
|
else if (time_held > TIMEOUT_SHORT_PRESS)
|
|
new_state = ButtonPress::SHORT_PRESS;
|
|
|
|
_time_pressed_down = 0;
|
|
}
|
|
|
|
_was_pressed = is_pressed;
|
|
_current_state = new_state;
|
|
}
|
|
|
|
[[nodiscard]] ButtonPress getState() const
|
|
{
|
|
return _current_state;
|
|
}
|
|
|
|
private:
|
|
gpio _sw;
|
|
|
|
bool _was_pressed = false;
|
|
std::uint32_t _time_pressed_down = 0;
|
|
ButtonPress _current_state = ButtonPress::NOT_PRESSED;
|
|
};
|
|
|
|
}// namespace Peripherals
|
|
|
|
#endif /* PERIPHERALS_BUTTON_HPP_ */
|