t09 - olikraus/m2tklib GitHub Wiki
Tutorial 9: Incremental Rotary Encoder
This tutorial will describe setup and use of an incremental rotary encoder.
Support for incremental rotary encoder is added for v1.09 of M2tklib.
Theory
Hardware
- The incremental rotary encoder has two outputs. These outputs must be connected to the microcontroller (Arduino board).
Setup
- Event source: The event source must support the incremental rotary encoder. The event source
m2_es_arduino_rotary_encoder
for the Arduino environment supports normal keys (one per pin) and one attached rotary encoder (see M2tk). - Pin numbers: An incremental rotary encoder has two output pins. These pins must be attached to the microcontroller. The pin numbers must be provided to the event source. Use setPin() to set the pin numbers for the event source (M2_KEY_ROT_ENC_A, M2_KEY_ROT_ENC_B).
Action
- The event source converts the signal values from the incremental rotary encoder into
M2_KEY_NEXT
andM2_KEY_PREV
messages. This is done by calling checkKey(). Ensure to call this procedure very often.
Example
The following code is taken from the RecEnc
example of the Arduino environment (U8glib variant).
This is a suitable constructor for M2tk with incremental rotary encoder:
M2tk m2(&top_menu, m2_es_arduino_rotary_encoder, m2_eh_4bd, m2_gh_u8g_bf);
The event handler m2_eh_4bd
will use M2_KEY_NEXT
and M2_KEY_DOWN
to change the data and to move between elements.
For minimum user input M2tk requires two lines for the rotary encoder and one select button:
void setup(void) {
// Connect u8glib with m2tklib
m2_SetU8g(u8g.getU8g(), m2_u8g_box_icon);
// Assign u8g font to index 0
m2.setFont(0, u8g_font_7x13r);
// define button for the select message
m2.setPin(M2_KEY_SELECT, 7); // dogm128 shield, 2nd from top
// The incremental rotary encoder is conected to these two pins
m2.setPin(M2_KEY_ROT_ENC_A, 3);
m2.setPin(M2_KEY_ROT_ENC_B, 2);
}
The checkKey() procedure must be called outside and inside of the picture loop (U8glib):
void loop() {
// check rotary encoder also inside the picture loop
m2.checkKey();
// process events and redraw menu if required
if ( m2.handleKey() != 0 ) {
// picture loop starts here
u8g.firstPage();
do {
// check rotary encoder also inside the picture loop
m2.checkKey();
// draw menu
m2.draw();
} while( u8g.nextPage() );
}
}
Conclusion
- Use event source with support for incremental rotray encoder
- Use suitable event handler (
m2_eh_4bd
) - Inform M2tk about rotary encoder pins with the setPin() procedure
- Make calls to checkKey() as often as possible
Links
- Previous Tutorial: User Forms
- Next Tutorial: Touch Screen Support
- Wiki Start Page