drumz/src/input/encoder.cpp

95 lines
2.3 KiB
C++

#include <vector>
#include <Arduino.h>
#include <Versatile_RotaryEncoder.h>
#include <ui/display.hpp>
#include <audio/tone_generator.hpp>
#include <input/encoder.hpp>
#ifndef ENCODER_A_PIN
#define ENCODER_A_PIN 12
#endif
#ifndef ENCODER_B_PIN
#define ENCODER_B_PIN 13
#endif
#ifndef ENTER_BUTTON_PIN
#define ENTER_BUTTON_PIN 14
#endif
namespace Encoder
{
using std::vector;
void pollEncoder(void *pvParameters);
void handlePress();
void handleRelease();
void handleRotate(int8_t rotation);
Versatile_RotaryEncoder *encoder;
vector<OnButtonReleaseCallback> onButtonReleaseCallbacks;
vector<OnButtonPressCallback> onButtonPressCallbacks;
vector<OnRotateCallback> onRotateCallbacks;
void init()
{
pinMode(ENTER_BUTTON_PIN, INPUT);
pinMode(ENCODER_A_PIN, INPUT);
pinMode(ENCODER_B_PIN, INPUT);
encoder = new Versatile_RotaryEncoder(ENCODER_A_PIN, ENCODER_B_PIN, ENTER_BUTTON_PIN);
encoder->setHandlePress(handlePress);
encoder->setHandlePressRelease(handleRelease);
encoder->setHandleRotate(handleRotate);
xTaskCreate(pollEncoder, "pollEncoder", 2048, NULL, 1, NULL);
}
void pollEncoder(void *pvParameters)
{
while (true)
{
encoder->ReadEncoder();
delay(1);
}
}
void handlePress()
{
//Serial.println("Encoder pressed");
for (OnButtonPressCallback callback : onButtonPressCallbacks) {
callback();
}
}
void handleRelease()
{
//Serial.println("Encoder released");
for (OnButtonReleaseCallback callback : onButtonReleaseCallbacks) {
callback();
}
}
void handleRotate(int8_t rotation)
{
//Serial.print("Encoder rotated by ");
//Serial.println(rotation);
for (OnRotateCallback callback : onRotateCallbacks) {
callback(rotation);
}
}
void onButtonRelease(OnButtonReleaseCallback callback) {
onButtonReleaseCallbacks.push_back(callback);
}
void onButtonPress(OnButtonPressCallback callback) {
onButtonPressCallbacks.push_back(callback);
}
void onRotate(OnRotateCallback callback) {
onRotateCallbacks.push_back(callback);
}
}