Skip to content

Instantly share code, notes, and snippets.

@betab0t
Last active May 28, 2019 19:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save betab0t/9f6b0bdc33e0a5c5054077cb5c702aa4 to your computer and use it in GitHub Desktop.
Save betab0t/9f6b0bdc33e0a5c5054077cb5c702aa4 to your computer and use it in GitHub Desktop.
Arduino test sketch for cheap 2 phase incremental rotary encoder from AliExpress
// Arduino test sketch for cheap 2 phase incremental rotary encoder from AliExpress
// https://www.aliexpress.com/item/32849332003.html
#define PIN_A_PHASE 2
#define PIN_B_PHASE 3
volatile unsigned int tick_counter, last_printed_tick_count = 0;
void setup()
{
Serial.begin(9600);
pinMode(PIN_A_PHASE, INPUT_PULLUP);
pinMode(PIN_B_PHASE, INPUT_PULLUP);
attachInterrupt(0, a_phase_interrupt_handler, RISING);
}
void loop()
{
if (tick_count_changed_since_last_print())
{
Serial.println(tick_counter);
update_last_printed_tick_count();
}
}
bool tick_count_changed_since_last_print()
{
return tick_counter != last_printed_tick_count;
}
void update_last_printed_tick_count()
{
last_printed_tick_count = tick_counter;
}
bool is_encoder_rotating_clockwise()
{
return digitalRead(PIN_B_PHASE) == LOW;
}
void a_phase_interrupt_handler()
{
tick_counter = is_encoder_rotating_clockwise() ? tick_counter + 1 : tick_counter - 1;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment