encoder

nkrkv/encoder/encoder

Detects rotation pulses on a hardware encoder
encoder
@/encoder
Detects rotation pulses on a hardware encoder
PAport
A board port to which the channel A signal is connected.
PBport
A board port to which the channel B signal is connected.
UPDpulse
Triggers an update. You should fire pulses as quick as possible to avoid rotation misses or wrong direction interpretation.
encoder
PA
PB
UPD
INC
DEC
DECpulse
Pulses when a decrement rotation is detected. Usually corresponds to counter-clockwise rotation.
INCpulse
Pulses when an increment rotation is detected. Usually corresponds to clockwise rotation.
To use the node in your project you should have the nkrkv/encoder library installed. Use the “File → Add Library” menu item in XOD IDE if you don’t have it yet. See Using libraries for more info.

C++ implementation

using State = bool;

{{ GENERATED_CODE }}

void evaluate(Context ctx) {
    bool* stateOld = getState(ctx);
    auto portA = getValue<input_PA>(ctx);
    auto portB = getValue<input_PB>(ctx);
    auto stateA = digitalRead(portA);

    if (isSettingUp()) {
        // Remember the initial (on boot) encoder state
        *stateOld = stateA;
    }

    if (!isInputDirty<input_UPD>(ctx)) {
        // Update on explicit pulses only
        return;
    }

    if (*stateOld == false && stateA == true) {
        // We only emit rotation pulses when A channel raises.
        // Use channel B to get the direction.
        if (digitalRead(portB))
            emitValue<output_DEC>(ctx, 1);
        else
            emitValue<output_INC>(ctx, 1);
    }

    *stateOld = stateA;
}