Skip to content

Instantly share code, notes, and snippets.

@punitsoni
Created May 2, 2014 23:21
Quad-encoder monitoring code
#define ENC_INPUT_A 0
#define ENC_INPUT_B 1
#define ENC_INPUT_I 2
typedef struct enc_state {
int8_t idx, ab;
int8_t dir;
int32_t pos_count;
int32_t isr_count;
int8_t enc_error_flag;
int32_t enc_ppr;
int32_t update_period_ms;
int32_t pulse_freq;
} enc_state_t;
volatile enc_state_t cur_state;
int8_t enc_matrix[4][4] =
{
{0, -1, 1, 2},
{1, 0, 2, -1},
{-1, 2, 0, 1},
{2, 1, -1, 0},
};
/**
* called every time the XOR signal rises, the isr
* freq is 2 times pulse freuency
*/
void enc_xor_isr()
{
int8_t prev_ab;
isr_count++;
prev_ab = cur_state.ab;
cur_state.ab = (read_input(ENC_INPUT_A) << 1) | read_input(ENC_INPUT_B);
if (enc_matrix[prev_ab][cur_state.ab] == 2) {
enc_error_flag = 1;
} else if (enc_matrix[cur_state.ab][ab] != 0) {
dir = enc_matrix[cur_state.ab][ab];
pos_count += enc_matrix[cur_state.ab][ab];
}
}
/* this function should be called at a fixed update interval
* f = isr_count / 2T;
*/
void enc_update()
{
cur_state.pulse_freq = (isr_count * 500)/ cur_state.update_period_ms;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment