From c368a1f2093e36566be9356ceb781d482844a409 Mon Sep 17 00:00:00 2001 From: xdrm-brackets Date: Sat, 30 May 2020 19:05:35 +0200 Subject: [PATCH] add sensors classes: push button, potentiometer, pressure sensor --- twinmax/sensors.cpp | 58 +++++++++++++++++++++++++++++++++++++++++++++ twinmax/sensors.h | 44 ++++++++++++++++++++++++++++++++++ 2 files changed, 102 insertions(+) create mode 100644 twinmax/sensors.cpp create mode 100644 twinmax/sensors.h diff --git a/twinmax/sensors.cpp b/twinmax/sensors.cpp new file mode 100644 index 0000000..727f06d --- /dev/null +++ b/twinmax/sensors.cpp @@ -0,0 +1,58 @@ +#include +#include +#include "sensors.h" + +void PushButton::setup(const int pin){ + pinMode(pin, INPUT); + _pin = pin; +} + +bool PushButton::tick(){ + const bool pushed = (digitalRead(_pin) == 0); + const bool toggle = (pushed != _pushed); + _pushed = pushed; + + if( toggle && pushed ){ // button has been pressed + _pushStart = millis(); + } + + return toggle; +} + +bool PushButton::tap(){ + const bool toggle = tick(); + + // released and last less than hold threshold + return toggle && !_pushed && (millis()-_pushStart) < HOLD_MS_THRESHOLD; +} + +bool PushButton::hold(){ + const bool toggle = tick(); + + // released and last at ;east hold threshold + return toggle && !_pushed && (millis()-_pushStart) >= HOLD_MS_THRESHOLD; +} + + + + +void Potentiometer::setup(const int pin){ + pinMode(pin, INPUT); + _pin = pin; +} + +short Potentiometer::range(){ + return 1023 - analogRead(_pin); +} + + + +// pressure sensors +void Pressure::setup(const int pin){ + pinMode(pin, INPUT); + _pin = pin; +} + +short Pressure::value(){ + return analogRead(_pin); +} diff --git a/twinmax/sensors.h b/twinmax/sensors.h new file mode 100644 index 0000000..bf12f16 --- /dev/null +++ b/twinmax/sensors.h @@ -0,0 +1,44 @@ +#ifndef _SENSORS_H_DEF_ +#define _SENSORS_H_DEF_ + + #define HOLD_MS_THRESHOLD 2000 + + // push button non-blocking state + class PushButton { + public: + void setup(const int pin); + bool tap(); // button has been pushed for a short amount of time + bool hold(); // button has been pushed for at least HOLD_MS_THRESHOLD milliseconds + + private: + // returns whether the button state changed + bool tick(); + + + // value of millis() when the button is down + unsigned long _pushStart { 0 }; + bool _pushed { false }; + int _pin { 0 }; + }; + + // potentiometer value + class Potentiometer { + public: + void setup(const int pin); + short range(); + + private: + int _pin { 0 }; + }; + + // pressure sensors + class Pressure { + public: + void setup(const int pin); + short value(); + + private: + int _pin { 0 }; + }; + +#endif