ESPHome 2026.11.0-dev
Loading...
Searching...
No Matches
rotary_encoder.h
Go to the documentation of this file.
1#pragma once
2
3#include <array>
4
6#include "esphome/core/hal.h"
8
10
16
24
28
29 volatile int32_t counter{0};
31 int32_t min_value{INT32_MIN};
32 int32_t max_value{INT32_MAX};
33 int32_t last_read{0};
34 uint8_t state{0};
35 bool first_read{true};
36
37 std::array<int8_t, 8> rotation_events{};
39
40 static void gpio_intr(RotaryEncoderSensorStore *arg);
41};
42
43class RotaryEncoderSensor final : public sensor::Sensor, public Component {
44 public:
45 void set_pin_a(InternalGPIOPin *pin_a) { pin_a_ = pin_a; }
46 void set_pin_b(InternalGPIOPin *pin_b) { pin_b_ = pin_b; }
47
56
65
67 void set_value(int value) {
68 this->store_.counter = value;
69 this->loop();
70 }
71
72 void set_reset_pin(GPIOPin *pin_i) { this->pin_i_ = pin_i; }
73 void set_min_value(int32_t min_value);
74 void set_max_value(int32_t max_value);
75 void set_publish_initial_value(bool publish_initial_value) { publish_initial_value_ = publish_initial_value; }
76
77 // ========== INTERNAL METHODS ==========
78 // (In most use cases you won't need these)
79 void setup() override;
80 void dump_config() override;
81 void loop() override;
82
83 template<typename F> void add_on_clockwise_callback(F &&callback) {
84 this->on_clockwise_callback_.add(std::forward<F>(callback));
85 }
86
87 template<typename F> void add_on_anticlockwise_callback(F &&callback) {
88 this->on_anticlockwise_callback_.add(std::forward<F>(callback));
89 }
90
91 template<typename F> void register_listener(F &&listener) { this->listeners_.add(std::forward<F>(listener)); }
92
93 protected:
96 GPIOPin *pin_i_{nullptr};
100
102
105 CallbackManager<void(int32_t)> listeners_{};
106};
107
108} // namespace esphome::rotary_encoder
BedjetMode mode
BedJet operating mode.
Copy of GPIOPin that is safe to use from ISRs (with no virtual functions)
Definition gpio_pin.h:98
void set_publish_initial_value(bool publish_initial_value)
void set_value(int value)
Manually set the value of the counter.
CallbackManager< void()> on_anticlockwise_callback_
CallbackManager< void(int32_t)> listeners_
bool publish_initial_value_
Index pin, if this is not nullptr, the counter will reset to 0 once this pin is HIGH.
void set_resolution(RotaryEncoderResolution mode)
Set the resolution of the rotary encoder.
void set_restore_mode(RotaryEncoderRestoreMode restore_mode)
Set the restore mode of the rotary encoder.
Base-class for all sensors.
Definition sensor.h:47
RotaryEncoderResolution
All possible resolutions for the rotary encoder.
@ ROTARY_ENCODER_2_PULSES_PER_CYCLE
increment counter by 1 with every A-B cycle, slow response but accurate
@ ROTARY_ENCODER_4_PULSES_PER_CYCLE
increment counter by 2 with every A-B cycle
RotaryEncoderRestoreMode
All possible restore modes for the rotary encoder.
@ ROTARY_ENCODER_ALWAYS_ZERO
try to restore counter, otherwise set to zero
static void gpio_intr(RotaryEncoderSensorStore *arg)