|
| 1 | +#ifndef __DCSBIOS_ROTARYSWITCH_H |
| 2 | +#define __DCSBIOS_ROTARYSWITCH_H |
| 3 | + |
| 4 | +#include "Arduino.h" |
| 5 | +#include "PollingInput.h" |
| 6 | + |
| 7 | +namespace DcsBios { |
| 8 | + template <unsigned long pollIntervalMs = POLL_EVERY_TIME, StepsPerDetent stepsPerDetent = ONE_STEP_PER_DETENT> |
| 9 | + class RotarySwitchT : PollingInput, public ResettableInput { |
| 10 | + private: |
| 11 | + const char* msg_; |
| 12 | + char pinA_; |
| 13 | + char pinB_; |
| 14 | + signed char switchValue_; |
| 15 | + signed char maxSwichValue_; |
| 16 | + char lastState_; |
| 17 | + signed char delta_; |
| 18 | + char readState() { |
| 19 | + return (digitalRead(pinA_) << 1) | digitalRead(pinB_); |
| 20 | + } |
| 21 | + void resetState() |
| 22 | + { |
| 23 | + lastState_ = (lastState_==0)?-1:0; |
| 24 | + } |
| 25 | + void pollInput() { |
| 26 | + char state = readState(); |
| 27 | + switch(lastState_) { |
| 28 | + case 0: |
| 29 | + if (state == 2) delta_--; |
| 30 | + if (state == 1) delta_++; |
| 31 | + break; |
| 32 | + case 1: |
| 33 | + if (state == 0) delta_--; |
| 34 | + if (state == 3) delta_++; |
| 35 | + break; |
| 36 | + case 2: |
| 37 | + if (state == 3) delta_--; |
| 38 | + if (state == 0) delta_++; |
| 39 | + break; |
| 40 | + case 3: |
| 41 | + if (state == 1) delta_--; |
| 42 | + if (state == 2) delta_++; |
| 43 | + break; |
| 44 | + } |
| 45 | + lastState_ = state; |
| 46 | + |
| 47 | + if (delta_ >= stepsPerDetent) { |
| 48 | + switchValue_ = min(switchValue_+1, maxSwichValue_); |
| 49 | + char buf[7]; |
| 50 | + utoa(switchValue_, buf, 10); |
| 51 | + if (tryToSendDcsBiosMessage(msg_, buf)) |
| 52 | + delta_ -= stepsPerDetent; |
| 53 | + } |
| 54 | + if (delta_ <= -stepsPerDetent) { |
| 55 | + switchValue_ = max(switchValue_-1, 0); |
| 56 | + char buf[7]; |
| 57 | + utoa(switchValue_, buf, 10); |
| 58 | + if (tryToSendDcsBiosMessage(msg_, buf)) |
| 59 | + delta_ += stepsPerDetent; |
| 60 | + } |
| 61 | + } |
| 62 | + public: |
| 63 | + RotarySwitchT(const char* msg, char pinA, char pinB, signed char maxSwichValue) : |
| 64 | + PollingInput(pollIntervalMs) { |
| 65 | + msg_ = msg; |
| 66 | + pinA_ = pinA; |
| 67 | + pinB_ = pinB; |
| 68 | + pinMode(pinA_, INPUT_PULLUP); |
| 69 | + pinMode(pinB_, INPUT_PULLUP); |
| 70 | + delta_ = 0; |
| 71 | + switchValue_ = 0; |
| 72 | + maxSwichValue_ = maxSwichValue; |
| 73 | + lastState_ = readState(); |
| 74 | + } |
| 75 | + |
| 76 | + void SetControl( const char* msg ) |
| 77 | + { |
| 78 | + msg_ = msg; |
| 79 | + } |
| 80 | + |
| 81 | + void resetThisState() |
| 82 | + { |
| 83 | + this->resetState(); |
| 84 | + } |
| 85 | + }; |
| 86 | + typedef RotarySwitchT<> RotarySwitch; |
| 87 | +} |
| 88 | + |
| 89 | +#endif |
0 commit comments