ELEC60013-ES-CW2/lib/knob/knob.cpp

75 lines
1.8 KiB
C++
Raw Normal View History

2022-03-23 18:23:26 +00:00
#include <knob>
2022-03-25 14:55:43 +00:00
Knob::Knob(int minimum, int maximum, int initialRotation) {
2022-03-23 18:23:26 +00:00
Knob::minimum = minimum;
Knob::maximum = maximum;
Knob::A = false;
Knob::B = false;
2022-03-25 14:55:43 +00:00
Knob::previousRotation = NONE;
Knob::rotation = initialRotation;
Knob::rotationInternal = initialRotation;
2022-03-23 18:23:26 +00:00
}
int Knob::getRotation() {
return Knob::rotation;
};
void Knob::updateRotation(bool ANew, bool BNew) {
2022-03-25 14:55:43 +00:00
if (A == ANew && B == BNew)
return; // No change, do not update values
2022-03-23 18:23:26 +00:00
2022-03-25 14:55:43 +00:00
bool fullstep = (BNew && ANew) || (!BNew && !ANew);
bool cwRot = (!B && !A && !BNew && ANew) ||
(!B && A && BNew && ANew) ||
(B && !A && !BNew && !ANew) ||
(B && A && BNew && !ANew);
bool acwRot = (!B && !A && BNew && !ANew) ||
(!B && A && !BNew && !ANew) ||
(B && !A && BNew && ANew) ||
(B && A && !BNew && ANew);
bool impossible = (!B && !A && BNew && ANew) ||
(!B && A && BNew && !ANew) ||
(B && !A && !BNew && ANew) ||
(B && A && !BNew && !ANew);
if (cwRot) {
if (previousRotation == CW && fullstep) {
rotationInternal++;
} else if (previousRotation == ACW) {
previousRotation = NONE;
} else {
previousRotation = CW;
}
} else if (acwRot) {
if (previousRotation == ACW && fullstep) {
rotationInternal--;
} else if (previousRotation == CW) {
previousRotation = NONE;
} else {
previousRotation = ACW;
}
} else if (impossible) {
if (fullstep) {
switch (previousRotation) {
case NONE: // Step skipped and no previous direction
break;
case CW:
rotationInternal++;
break;
case ACW:
rotationInternal--;
break;
}
}
}
2022-03-23 18:23:26 +00:00
A = ANew;
B = BNew;
2022-03-25 14:55:43 +00:00
if (rotationInternal < minimum)
rotationInternal = minimum;
if (rotationInternal > maximum)
rotationInternal = maximum;
rotation = rotationInternal;
2022-03-23 18:23:26 +00:00
}