wobblyhead hg > arduino > TiltSwitch
comparison TiltSwitch.h @ 0:f2ccfa3f20ad default tip
more complete version from magic rattle
| author | ark |
|---|---|
| date | 2017-06-28 00:48 +0200 |
| parents | |
| children |
comparison
equal
deleted
inserted
replaced
| -1:000000000000 | 0:f2ccfa3f20ad |
|---|---|
| 1 #ifndef TiltSwitch_h | |
| 2 #define TiltSwitch_h | |
| 3 | |
| 4 #include <Arduino.h> | |
| 5 | |
| 6 | |
| 7 /** | |
| 8 utility class for interpreting tilt switch state. | |
| 9 | |
| 10 calculates intensity of movement expressed as number of state changes per | |
| 11 _secs_ seconds. | |
| 12 | |
| 13 calculates up/down state as approximated by avg. | |
| 14 | |
| 15 | |
| 16 (c) 2017 arkadiusz@wobblyhead.net | |
| 17 */ | |
| 18 class TiltSwitch { | |
| 19 public: | |
| 20 // raw switch input | |
| 21 bool isOn; | |
| 22 // movement intensity | |
| 23 float act; | |
| 24 // averaged state | |
| 25 float avg; | |
| 26 | |
| 27 | |
| 28 /** | |
| 29 create an uninitialised TiltSwitch. | |
| 30 setup() must be called after this to make it usable. | |
| 31 */ | |
| 32 TiltSwitch(); | |
| 33 | |
| 34 /** | |
| 35 setup switch instance. | |
| 36 @param {byte} pin button input pin | |
| 37 @param {bool} pu if true, button uses internal pullup | |
| 38 @param {float} secs seconds to average over | |
| 39 */ | |
| 40 void setup(byte pin, bool pu, float secs = 1.0); | |
| 41 | |
| 42 /** | |
| 43 check pin and update switch state. | |
| 44 @param {unsigned long} us current micros() value | |
| 45 */ | |
| 46 void update(unsigned long us); | |
| 47 | |
| 48 | |
| 49 /** | |
| 50 number of samples to average for _avg_. | |
| 51 */ | |
| 52 #ifdef __AVR_ATtiny85__ | |
| 53 const uint32_t MAX_SAMPLES = 5; | |
| 54 #else | |
| 55 const uint32_t MAX_SAMPLES = 20; | |
| 56 #endif | |
| 57 | |
| 58 | |
| 59 private: | |
| 60 byte pin; | |
| 61 bool isPullup; | |
| 62 | |
| 63 // act calculation | |
| 64 uint32_t dus; | |
| 65 float ref; | |
| 66 uint32_t refUs; | |
| 67 | |
| 68 // avg calculation | |
| 69 float sum; | |
| 70 int num; | |
| 71 | |
| 72 | |
| 73 /** | |
| 74 read pin state, translate to on/off state. | |
| 75 @return {bool} true if buton is pressed | |
| 76 */ | |
| 77 bool readState(); | |
| 78 | |
| 79 }; | |
| 80 | |
| 81 #endif |
