111 lines
2.0 KiB
C++
111 lines
2.0 KiB
C++
#include <Arduino.h>
|
|
#include <stdint.h>
|
|
#include "hardware.h"
|
|
#include "rotary.h"
|
|
|
|
|
|
|
|
volatile int rotaryCount = 0;
|
|
volatile bool switchState = false;
|
|
volatile unsigned long lastEvent = 0;
|
|
|
|
|
|
int myDigitalRead(int a) {
|
|
int r = 0;
|
|
for (uint32_t i = 0; i < DEBOUNCING_REPEAT; i++) {
|
|
if (digitalRead(a) == HIGH) {
|
|
r++;
|
|
} else {
|
|
r--;
|
|
}
|
|
}
|
|
int res = -1;
|
|
if (r >= (DEBOUNCING_REPEAT / 2)) {
|
|
res = 1;
|
|
} else if (r <= -1 * (DEBOUNCING_REPEAT / 2)) {
|
|
res = 0;
|
|
}
|
|
return res;
|
|
}
|
|
|
|
|
|
void rotary_a_interrupt() {
|
|
uint32_t currentEvent = millis();
|
|
|
|
if ((lastEvent == 0) || (lastEvent + DEBOUNCING_DEAD_TIME < currentEvent)) {
|
|
lastEvent = currentEvent;
|
|
|
|
int a = myDigitalRead(ROTARY_A);
|
|
int b = myDigitalRead(ROTARY_B);
|
|
|
|
if (((a != -1) && (b != -1))) {
|
|
if (a == b) {
|
|
rotaryCount++;
|
|
} else {
|
|
rotaryCount--;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
void rotary_b_interrupt() {
|
|
uint32_t currentEvent = millis();
|
|
|
|
if ((lastEvent == 0) || (lastEvent + DEBOUNCING_DEAD_TIME < currentEvent)) {
|
|
lastEvent = currentEvent;
|
|
|
|
int a = myDigitalRead(ROTARY_A);
|
|
int b = myDigitalRead(ROTARY_B);
|
|
|
|
if (((a != -1) && (b != -1))) {
|
|
if (a == b) {
|
|
rotaryCount--;
|
|
} else {
|
|
rotaryCount++;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
void switch_interrupt() {
|
|
unsigned long currentEvent = millis();
|
|
|
|
if ((lastEvent == 0) || (lastEvent + DEBOUNCING_DEAD_TIME < currentEvent)) {
|
|
lastEvent = currentEvent;
|
|
|
|
switchState = true;
|
|
}
|
|
}
|
|
|
|
void rotaryInit() {
|
|
pinMode(SWITCH, INPUT_PULLUP);
|
|
pinMode(ROTARY_A, INPUT_PULLUP);
|
|
pinMode(ROTARY_B, INPUT_PULLUP);
|
|
attachInterrupt(SWITCH, switch_interrupt, FALLING);
|
|
attachInterrupt(ROTARY_A, rotary_a_interrupt, CHANGE);
|
|
attachInterrupt(ROTARY_B, rotary_b_interrupt, CHANGE);
|
|
}
|
|
|
|
|
|
int getAndResetRotaryCount() {
|
|
int res = 0;
|
|
|
|
noInterrupts();
|
|
res = rotaryCount;
|
|
rotaryCount = 0;
|
|
interrupts();
|
|
|
|
return res;
|
|
}
|
|
|
|
bool getAndResetSwitchState() {
|
|
bool res = false;
|
|
|
|
noInterrupts();
|
|
res = switchState;
|
|
switchState = false;
|
|
interrupts();
|
|
|
|
return res;
|
|
}
|