Add encoder controller
This commit is contained in:
parent
bb933c847b
commit
3269642002
90
code/EncoderController.cpp
Normal file
90
code/EncoderController.cpp
Normal file
@ -0,0 +1,90 @@
|
|||||||
|
#include <Arduino.h>
|
||||||
|
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
};
|
||||||
Loading…
x
Reference in New Issue
Block a user