100PPR encoder – mods to KD8CEC code to make it work better

Using a 100PPR encoder with the KD8CEC firmware may cause some issues as the firmware can’t keep up with the pulse train from the encoder.

Sascha Bonnet suggests some simple code modifications make a big difference. He replaced two commands (“millis” to “micros”) in the KD8CEC’s source code and my encoder worked.   Here’s his code for you to use as a template for editing the KD8CEC arduino sketch:

  1. int enc_read(void) {
  2.   int result = 0;
  3.   byte newState;
  4.   int enc_speed = 0;
  5.   unsigned long start_at = millis();
  6.   while (millis()  start_at < 50) { // check if the previous state was stable
  7.     newState = enc_state(); // Get current state  
  8.     if (newState != enc_prev_state)
  9.       delayMicroseconds(1);
  10.     if (enc_state() != newState || newState == enc_prev_state)
  11.       continue;
  12.     //these transitions point to the encoder being rotated anti-clockwise
  13.     if ((enc_prev_state == 0 && newState == 2) ||
  14.       (enc_prev_state == 2 && newState == 3) ||
  15.       (enc_prev_state == 3 && newState == 1) ||
  16.       (enc_prev_state == 1 && newState == 0)){
  17.         result–;
  18.       }
  19.     //these transitions point o the enccoder being rotated clockwise
  20.     if ((enc_prev_state == 0 && newState == 1) ||
  21.       (enc_prev_state == 1 && newState == 3) ||
  22.       (enc_prev_state == 3 && newState == 2) ||
  23.       (enc_prev_state == 2 && newState == 0)){
  24.         result++;
  25.       }
  26.     enc_prev_state = newState; // Record state for next pulse interpretation
  27.     enc_speed++;
  28.     delayMicroseconds(1);
  29.   }
Reference