-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathESP32RotaryEncoder.cpp
More file actions
426 lines (334 loc) · 11.2 KB
/
ESP32RotaryEncoder.cpp
File metadata and controls
426 lines (334 loc) · 11.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
#include "ESP32RotaryEncoder.h"
#if defined( ESP32 )
#define RE_ISR_ATTR IRAM_ATTR
#ifdef ARDUINO_ISR_ATTR
#undef ARDUINO_ISR_ATTR
#define ARDUINO_ISR_ATTR IRAM_ATTR
#endif
#if defined( ESP_ARDUINO_VERSION ) && ( ESP_ARDUINO_VERSION == ESP_ARDUINO_VERSION_VAL(2,0,10) )
/**
* BUG ALERT!
*
* With Arduino-ESP32 core 2.0.10, the #include statement below fails to compile due to a bug.
* Also see `attachInterrupts()` for the note about the `attachInterrupt()` macro in 2.x cores.
*/
#error Please upgrade the Arduino-ESP32 core to use this library.
#else
#include <FunctionalInterrupt.h>
#endif
#endif
RotaryEncoder::RotaryEncoder( uint8_t encoderPinA, uint8_t encoderPinB, int8_t buttonPin, int8_t vccPin, uint8_t encoderSteps )
: encoderPinA{ encoderPinA },
encoderPinB{ encoderPinB },
buttonPin{ buttonPin },
vccPin{ vccPin },
encoderSteps{ encoderSteps == 0 ? RE_DEFAULT_STEPS : encoderSteps }
{
ESP_LOGD( LOG_TAG, "Initialized: A = %u, B = %u, Button = %i, VCC = %i, Steps = %u", encoderPinA, encoderPinB, buttonPin, vccPin, this->encoderSteps );
}
RotaryEncoder::~RotaryEncoder()
{
detachInterrupts();
esp_timer_stop( loopTimer );
esp_timer_delete( loopTimer );
}
void RotaryEncoder::setBoundaries( long minValue, long maxValue, bool circleValues )
{
ESP_LOGD( LOG_TAG, "boundary minValue = %ld, maxValue = %ld, circular = %s", minValue, maxValue, ( circleValues ? "true" : "false" ) );
if( minValue > maxValue )
ESP_LOGW( LOG_TAG, "Minimum value (%ld) is greater than maximum value (%ld); behavior is undefined.", minValue, maxValue );
portENTER_CRITICAL( &mux );
this->minEncoderValue = minValue;
this->maxEncoderValue = maxValue;
this->circleValues = circleValues;
portEXIT_CRITICAL( &mux );
}
void RotaryEncoder::setMinValue( long minValue )
{
ESP_LOGD( LOG_TAG, "minValue = %ld", minValue );
portENTER_CRITICAL( &mux );
this->minEncoderValue = minValue;
portEXIT_CRITICAL( &mux );
}
void RotaryEncoder::setMaxValue( long maxValue )
{
ESP_LOGD( LOG_TAG, "maxValue = %ld", maxValue );
portENTER_CRITICAL( &mux );
this->maxEncoderValue = maxValue;
portEXIT_CRITICAL( &mux );
}
void RotaryEncoder::setCircular( bool circleValues )
{
ESP_LOGD( LOG_TAG, "Boundaries %s circular", ( circleValues ? "are" : "are not" ) );
portENTER_CRITICAL( &mux );
this->circleValues = circleValues;
portEXIT_CRITICAL( &mux );
}
void RotaryEncoder::setStepValue( long stepValue )
{
ESP_LOGD( LOG_TAG, "stepValue = %ld", stepValue );
if( stepValue > maxEncoderValue || stepValue < minEncoderValue )
ESP_LOGW( LOG_TAG, "Step value (%ld) is outside the bounds (%ld...%ld); behavior is undefined.", stepValue, minEncoderValue, maxEncoderValue );
portENTER_CRITICAL( &mux );
this->stepValue = stepValue;
portEXIT_CRITICAL( &mux );
}
void RotaryEncoder::onTurned( EncoderCallback f )
{
callbackEncoderChanged = f;
}
void RotaryEncoder::onPressed( ButtonCallback f )
{
callbackButtonPressed = f;
}
void RotaryEncoder::beginLoopTimer()
{
/**
* We're using esp_timer.h from ESP32 SDK rather than esp32-hal-timer.h from Arduino API
* because the `timerAttachInterrupt()` won't accept std::bind like `attachInterrupt()` in
* FunctionalInterrupt will. We have a static method that `timerAttachInterrupt()` will take,
* but we'd lose instance context. But the `esp_timer_create_args_t` will let us set a callback
* argument, which we set to `this`, so that the static method maintains instance context.
*
* As of 29 September 2023, there is an open issue to allow `std::function` in esp32-hal-timer:
* https://github.com/espressif/arduino-esp32/issues/8427
*
* ...for now (and maybe forever?), we'll do it this way.
*/
esp_timer_create_args_t _timerConfig;
_timerConfig.arg = this;
_timerConfig.callback = reinterpret_cast<esp_timer_cb_t>( timerCallback );
_timerConfig.dispatch_method = ESP_TIMER_TASK;
_timerConfig.skip_unhandled_events = true;
_timerConfig.name = "RotaryEncoder::loop_ISR";
esp_timer_create( &_timerConfig, &loopTimer );
esp_timer_start_periodic( loopTimer, RE_LOOP_INTERVAL );
}
void RotaryEncoder::timerCallback( void *self )
{
RotaryEncoder *instance = (RotaryEncoder *)self;
instance->loop();
}
void RotaryEncoder::attachInterrupts()
{
#if defined( BOARD_HAS_PIN_REMAP ) && ( ESP_ARDUINO_VERSION < ESP_ARDUINO_VERSION_VAL(3,0,0) )
/**
* The io_pin_remap.h in Arduino-ESP32 cores of the 2.0.x family
* (since 2.0.10) define an `attachInterrupt()` macro that folds-in
* a call to `digitalPinToGPIONumber()`, but FunctionalInterrupt.cpp
* does this too, so we actually don't need the macro at all.
* Since 3.x the call inside the function was removed, so the wrapping
* macro is useful again.
*/
#undef attachInterrupt
#endif
attachInterrupt( encoderPinA, std::bind( &RotaryEncoder::_encoder_ISR, this ), CHANGE );
attachInterrupt( encoderPinB, std::bind( &RotaryEncoder::_encoder_ISR, this ), CHANGE );
if( buttonPin > RE_DEFAULT_PIN )
attachInterrupt( buttonPin, std::bind( &RotaryEncoder::_button_ISR, this ), CHANGE );
ESP_LOGD( LOG_TAG, "Interrupts attached" );
}
void RotaryEncoder::detachInterrupts()
{
detachInterrupt( encoderPinA );
detachInterrupt( encoderPinB );
detachInterrupt( buttonPin );
ESP_LOGD( LOG_TAG, "Interrupts detached" );
}
void RotaryEncoder::begin( bool useTimer )
{
resetEncoderValue();
_lastRotaryInterruptTime = 0;
_previousAB = 3;
_encoderPosition = 0;
encoderChangedFlag = false;
buttonPressedFlag = false;
_lastButtonInterruptTime = 0;
buttonPressedTime = 0;
buttonPressedDuration = 0;
pinMode( encoderPinA, encoderPinMode );
pinMode( encoderPinB, encoderPinMode );
if( buttonPin > RE_DEFAULT_PIN )
pinMode( buttonPin, buttonPinMode );
if( vccPin > RE_DEFAULT_PIN )
{
pinMode( vccPin, OUTPUT );
digitalWrite( vccPin, HIGH );
}
delay( 20 );
attachInterrupts();
if( useTimer )
beginLoopTimer();
ESP_LOGD( LOG_TAG, "RotaryEncoder active" );
}
bool RotaryEncoder::isEnabled()
{
return _isEnabled;
}
void RotaryEncoder::enable()
{
if( _isEnabled.exchange(true) )
return;
attachInterrupts();
ESP_LOGD( LOG_TAG, "Input enabled" );
}
void RotaryEncoder::disable()
{
if( !_isEnabled.exchange(false) )
return;
detachInterrupts();
ESP_LOGD( LOG_TAG, "Input disabled" );
}
bool RotaryEncoder::buttonPressed()
{
if( !_isEnabled ) {
return false;
}
bool wasPressed;
unsigned long duration;
portENTER_CRITICAL( &mux );
wasPressed = buttonPressedFlag;
buttonPressedFlag = false;
duration = buttonPressedDuration;
portEXIT_CRITICAL( &mux );
if( wasPressed )
ESP_LOGD( LOG_TAG, "Button pressed for %lu ms", duration );
return wasPressed;
}
bool RotaryEncoder::encoderChanged()
{
if( !_isEnabled ) {
return false;
}
bool hasChanged;
long value;
portENTER_CRITICAL( &mux );
hasChanged = encoderChangedFlag;
encoderChangedFlag = false;
value = currentValue;
portEXIT_CRITICAL( &mux );
if( hasChanged )
ESP_LOGD( LOG_TAG, "Knob turned; value: %ld", value );
return hasChanged;
}
long RotaryEncoder::getEncoderValue()
{
portENTER_CRITICAL( &mux );
long value = currentValue;
portEXIT_CRITICAL( &mux );
return value;
}
long RotaryEncoder::constrainValue( long value ) const
{
if( value < minEncoderValue )
return circleValues ? maxEncoderValue : minEncoderValue;
else if( value > maxEncoderValue )
return circleValues ? minEncoderValue : maxEncoderValue;
else
return value;
}
void RotaryEncoder::setEncoderValue( long newValue )
{
long constrainedValue = constrainValue(newValue);
if( constrainedValue != newValue )
ESP_LOGD( LOG_TAG, "Encoder value '%ld' constrained to '%ld'", constrainedValue, newValue );
long oldValue;
portENTER_CRITICAL( &mux );
oldValue = currentValue;
currentValue = constrainedValue;
portEXIT_CRITICAL( &mux );
if( constrainedValue != oldValue )
ESP_LOGD( LOG_TAG, "Overriding encoder value from '%ld' to '%ld'", oldValue, constrainedValue );
}
void ARDUINO_ISR_ATTR RotaryEncoder::loop()
{
if( callbackEncoderChanged != NULL && encoderChanged() )
callbackEncoderChanged( getEncoderValue() );
if( callbackButtonPressed != NULL && buttonPressed() )
callbackButtonPressed( buttonPressedDuration );
}
void ARDUINO_ISR_ATTR RotaryEncoder::_button_ISR()
{
if ( !_isEnabled ) {
return;
}
portENTER_CRITICAL_ISR( &mux );
// Simple software de-bounce
if( ( millis() - _lastButtonInterruptTime ) < 30 )
{
portEXIT_CRITICAL_ISR( &mux );
return;
}
// HIGH = idle, LOW = active
bool isPressed = !digitalRead( buttonPin );
if( isPressed )
{
buttonPressedTime = millis();
}
else
{
unsigned long now = millis();
buttonPressedDuration = now - buttonPressedTime;
buttonPressedFlag = true;
}
_lastButtonInterruptTime = millis();
portEXIT_CRITICAL_ISR( &mux );
}
void ARDUINO_ISR_ATTR RotaryEncoder::_encoder_ISR()
{
if ( !_isEnabled ) {
return;
}
portENTER_CRITICAL_ISR( &mux );
/**
* Almost all of this came from a blog post by Garry on GarrysBlog.com:
* https://garrysblog.com/2021/03/20/reliably-debouncing-rotary-encoders-with-arduino-and-esp32/
*
* Read more about how this works here:
* https://www.best-microcontroller-projects.com/rotary-encoder.html
*/
bool valueChanged = false;
_previousAB <<=2; // Remember previous state
if( digitalRead( encoderPinA ) ) _previousAB |= 0x02; // Add current state of pin A
if( digitalRead( encoderPinB ) ) _previousAB |= 0x01; // Add current state of pin B
_encoderPosition += encoderStates[( _previousAB & 0x0f )];
/**
* Based on how fast the encoder is being turned, we can apply an acceleration factor
*/
unsigned long speed = micros() - _lastRotaryInterruptTime;
long _stepValue;
if( speed > 40000UL ) // Greater than 40 milliseconds
_stepValue = this->stepValue; // Increase/decrease by 1 x stepValue
else if( speed > 20000UL ) // Greater than 20 milliseconds
_stepValue = ( this->stepValue <= 9 ) ? // Increase/decrease by 3 x stepValue
this->stepValue : ( this->stepValue * 3 ) // But only if stepValue > 9
;
else // Faster than 20 milliseconds
_stepValue = ( this->stepValue <= 100 ) ? // Increase/decrease by 10 x stepValue
this->stepValue : ( this->stepValue * 10 ) // But only if stepValue > 100
;
/**
* Update counter if encoder has rotated a full detent
* For the following comments, we'll assume it's 4 steps per detent
* The tripping point is >= STEPS or <= -STEPS
*/
if( _encoderPosition >= encoderSteps ) // Four steps forward
{
this->currentValue = constrainValue(this->currentValue + _stepValue);
valueChanged = true;
}
else if( _encoderPosition <= -encoderSteps ) // Four steps backwards
{
this->currentValue = constrainValue(this->currentValue - _stepValue);
valueChanged = true;
}
if( valueChanged )
{
encoderChangedFlag = true;
// Reset our "step counter"
_encoderPosition = 0;
// Remember current time so we can calculate speed
_lastRotaryInterruptTime = micros();
}
portEXIT_CRITICAL_ISR( &mux );
}