旋钮编码器c代码_超简单的旋转编码开关程序!

typedef struct

{

encoder_phase_state phase_state[KNOB_COUNT];

uint8_t rotate_dir[KNOB_COUNT];

uint8_t tick_count[KNOB_COUNT];

int32_t pos_old[KNOB_COUNT];

int32_t pos_new[KNOB_COUNT];

uint8_t id[KNOB_COUNT];

}knob_struct;

static int32_t knob_read_count(knob_struct *handle, uint8_t axis)

{

const int8_t phase_ab_states[] = { 0, -1, 1, 0, 1, 0, 0, -1, -1, 0, 0, 1, 0, 1, -1, 0 };

static int32_t encoder_output[KNOB_COUNT];

static int8_t phase_ab[KNOB_COUNT]; //AB key read out, Previous in the high 2 bits and current in the low two bits;

static bool first_time_run = true;

if(first_time_run == true)

{

first_time_run = false;

for(uint8_t idx = 0; idx < KNOB_COUNT; idx++)

{

encoder_output[idx] = 0x0000;

phase_ab[idx] = 0x00;

}

}

phase_ab[axis] <<= 2; //bit 2..3 now contain the previous AB key read-out;

if(handle->phase_state[axis].phase_a)

{

phase_ab[axis] |= 0x02; //set the 1st bit if A is high now;

}

if(handle->phase_state[axis].phase_b)

{

phase_ab[axis] |= 0x01; //set the 0th bit if B is high;

}

phase_ab[axis] &= 0x0f; //only retain phase_ab' last 4 bits (A_previous, B_previous, A_current, B_current)

encoder_output[axis] += phase_ab_states[phase_ab[axis]];

handle->pos_new[axis] = encoder_output[axis] >> 1;

return (encoder_output[axis] >> 1);                              //if you want to return absolute steps.

}

这个是我一直用的,主要用于控制面板旋钮操作用的。  1ms 读一次即可。不需要中断,任意一个个IO电平输入即可。

如果是电机的。这种就不合适了。

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值