From 32696420021d5da818ffad681a97eb427c847920 Mon Sep 17 00:00:00 2001 From: rafa Date: Sat, 24 May 2025 18:48:22 +0100 Subject: [PATCH] Add encoder controller --- code/EncoderController.cpp | 90 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 90 insertions(+) create mode 100644 code/EncoderController.cpp diff --git a/code/EncoderController.cpp b/code/EncoderController.cpp new file mode 100644 index 0000000..4ce0598 --- /dev/null +++ b/code/EncoderController.cpp @@ -0,0 +1,90 @@ +#include + +enum EncoderDirection { + COUNTERCLOCKWISE = 2, + STOPPED = 0, + CLOCKWISE = 1, +}; + +enum ButtonState { + PRESSED = 0, + RELEASED = 1, +}; + +class EncoderController { + + private: + int pin_clk; + int pin_dt; + int last_clk = HIGH; + int new_clk; + int dt_value; + EncoderDirection current_direction; + int pin_btn; + int button; + bool last_button_state = HIGH; // começa como solto + bool button_click_registered = false; + + public: + EncoderController(int pin_dt, int pin_clk, int pin_btn) { + this->pin_dt = pin_dt; + this->pin_clk = pin_clk; + this->pin_btn = pin_btn; + } + + void configure_pins() { + pinMode(this->pin_dt, INPUT_PULLUP); + pinMode(this->pin_clk, INPUT_PULLUP); + pinMode(this->pin_btn, INPUT_PULLUP); + } + + bool clk_pin_changed(){ + this->new_clk = digitalRead(this->pin_clk); + return this->new_clk != this->last_clk; + } + + void read(){ + if (this->clk_pin_changed()) { + this->last_clk = this->new_clk; + this->dt_value = digitalRead(this->pin_dt); + if (this->new_clk == LOW && this->dt_value == HIGH) { + + this->current_direction = CLOCKWISE; + } + if (this->new_clk == LOW && this->dt_value == LOW) { + + this->current_direction = COUNTERCLOCKWISE; + } + } + + int current_state = digitalRead(this->pin_btn); + if (this->last_button_state == HIGH && current_state == LOW) { + this->button_click_registered = true; + } + this->last_button_state = current_state; + } + + bool rotated_clockwise(){ + if(this->current_direction == CLOCKWISE){ + this->current_direction = STOPPED; + return true; + } + return false; + } + + bool rotated_counterclockwise(){ + if(this->current_direction == COUNTERCLOCKWISE){ + this->current_direction = STOPPED; + return true; + } + return false; + } + + bool button_pressed(){ + if (this->button_click_registered) { + this->button_click_registered = false; + return true; + } + return false; + } +}; \ No newline at end of file