wobblyhead hg > arduino > TiltSwitch
diff TiltSwitch.h @ 0:f2ccfa3f20ad default tip
more complete version from magic rattle
| author | ark |
|---|---|
| date | 2017-06-28 00:48 +0200 |
| parents | |
| children |
line wrap: on
line diff
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/TiltSwitch.h Wed Jun 28 00:48:53 2017 +0200 @@ -0,0 +1,81 @@ +#ifndef TiltSwitch_h +#define TiltSwitch_h + +#include <Arduino.h> + + +/** + utility class for interpreting tilt switch state. + + calculates intensity of movement expressed as number of state changes per + _secs_ seconds. + + calculates up/down state as approximated by avg. + + + (c) 2017 arkadiusz@wobblyhead.net +*/ +class TiltSwitch { + public: + // raw switch input + bool isOn; + // movement intensity + float act; + // averaged state + float avg; + + + /** + create an uninitialised TiltSwitch. + setup() must be called after this to make it usable. + */ + TiltSwitch(); + + /** + setup switch instance. + @param {byte} pin button input pin + @param {bool} pu if true, button uses internal pullup + @param {float} secs seconds to average over + */ + void setup(byte pin, bool pu, float secs = 1.0); + + /** + check pin and update switch state. + @param {unsigned long} us current micros() value + */ + void update(unsigned long us); + + + /** + number of samples to average for _avg_. + */ + #ifdef __AVR_ATtiny85__ + const uint32_t MAX_SAMPLES = 5; + #else + const uint32_t MAX_SAMPLES = 20; + #endif + + + private: + byte pin; + bool isPullup; + + // act calculation + uint32_t dus; + float ref; + uint32_t refUs; + + // avg calculation + float sum; + int num; + + + /** + read pin state, translate to on/off state. + @return {bool} true if buton is pressed + */ + bool readState(); + +}; + +#endif
