It is based on https://developer.mbed.org/users/gregeric/code/Nucleo_Hello_Encoder/

rotary_encoder_abz_phase/rotary_encoder_abz_phase.cpp

Committer:
inst
Date:
2016-04-09
Revision:
5:fae9a340d212
Parent:
3:65021ea3fae5

File content as of revision 5:fae9a340d212:

#include "mbed.h"
#include "rotary_encoder_abz_phase.hpp"
#include "rotary_encoder_base.hpp"

namespace mbed_stl {

rotary_encoder_abz_phase::rotary_encoder_abz_phase(TIM_TypeDef* timer_type, PinName z_pin, size_t resolution) :
        rotary_encoder_base(timer_type, TIM_ENCODERMODE_TI12, resolution),
        z_phase_intr_(z_pin),
        counts_in_prev_intr_(0) {
    z_phase_intr_.fall(this, &rotary_encoder_abz_phase::intr_z_phase_first);
}

int32_t rotary_encoder_abz_phase::get_counts() const {
    int32_t counts = timer_handler_.Instance->CNT;
    
    if (counts > (max_counts_ >> 1)) {
        return counts - max_counts_;
    }
    return  counts;
}

void rotary_encoder_abz_phase::intr_z_phase_first() {
    counts_in_prev_intr_ = timer_handler_.Instance->CNT;
    z_phase_intr_.fall(this, &rotary_encoder_abz_phase::intr_z_phase);
}

void rotary_encoder_abz_phase::intr_z_phase() {
    uint32_t counts = timer_handler_.Instance->CNT;
    // Z相の割り込みが入る時は、前回とのカウントの差は分解能で割り切れるはず
    int64_t error = (counts - counts_in_prev_intr_) % resolution_;
    timer_handler_.Instance->CNT -= error;
    
    counts_in_prev_intr_ = counts;
}

void rotary_encoder_abz_phase::reset() {
    counts_in_prev_intr_ = 0;
    timer_handler_.Instance->CNT = 0;
}

} /* namespace mbed_stl */