Smoothieware: understanding encoder reading readEncoderDelta()


I have a question, I’m trying to understand how readEncoderDelta() is implemented in ST7565.cpp

int ST7565::readEncoderDelta()
    static int8_t enc_states[] = {0, -1, 1, 0, 1, 0, 0, -1, -1, 0, 0, 1, 0, 1, -1, 0};
    static uint8_t old_AB = 0;

    if(this->encoder_a_pin.connected()) {
        // mviki
        old_AB <<= 2;                   //remember previous state
        old_AB |= ( this->encoder_a_pin.get() + ( this->encoder_b_pin.get() * 2 ) );  //add current state
        return  enc_states[(old_AB & 0x0f)];
    } else {
        return 0;

in the function old_AB is always initialized at every call to 0, how does the function remember the state of encA/B from the previous call to determine the direction of motion? the way it is the function will always evaluate (old_AB & 0x0f) to 0,1,2 or 3 based on the current state only

I’m also assuming this code is made to read a standard rotary encoder input, like this for example


I don’t think it’s initialized to 0 every call, wouldn’t work otherwise. This is very standard encoder reading code you can find pretty much the same thing in the arduino tutorials etc.

static local variables are static; they aren’t re-initialized dynamically each time a function/method is invoked. The local part is namespace, the static part is that they are not dynamically allocated and that the initialization is one-time (it’s actually normally implemented as a separate section that holds all the static local variables with their initial state).

Here are a few useful references selected at random from a web search:

thanks a lot @Arthur_Wolf and @mcdanlj, I appreciate it!

Today I learned

1 Like