管理来自编码器的值以了解编码器本身的方向(逆时针或顺时针)

Manage values from encoder to understand the direction of the encoder itself (counterclockwise or clockwise)

我正在对编码器进行采样,该样本的值介于区间 [30, 230] 之间;我必须使用这个值来定义两个输出计数器变量(一个递增计数器和一个递减计数器)。

问题是,有时当出现翻转时,这意味着编码器从 230 变为 30,反之亦然,采样太慢,我失去了运动的方向(逆时针或顺时针),这导致错误行为。

示例:

如果编码器在 220 值上并且我沿顺时针方向非常快地移动它,我的下一个值是例如 100,这意味着该值通过 30(翻转):方向应该是 顺时针。但是软件认为我将编码器从 230 移到了 100,它给了我一个 逆时针 移动。

提醒我不能提高采样速度,它是稳定的。

在实时环境中。

如果你不能保证编码器在一个轮询周期内不会移动超过一半的范围,那么问题就无法解决。如果您假设它不会移动那么远,那么它是可以解决的 - 您只需假设两个轮询事件之间的移动是两个可能方向中的最短

您没有解释为什么您的编码器范围从非零开始,但是如果您删除该偏移量并通过减去偏移量来处理 0 到 200 的范围,则算法更容易理解(和编码)。

给定编码器读取函数 uint8_t ReadEnc() 例如:

#define ENCODER_RANGE 200
#define ENCODER_OFFSET 30  // remove offset for range 0 to 200
static unsigned ccw_counter = 0 ;
static unsigned cw_counter = 0
static uint8_t previous_enc = ReadEnc() - ENCODER_OFFSET ;

uint8_t enc = ReadEnc() - ENCODER_OFFSET ;
signed enc_diff = enc - previous_enc ;
previous_enc = enc ;

// If absolute difference is greater then half the range
// assume that it rotated the opposite way.
if( enc_diff > ENCODER_RANGE / 2)
{
    enc_diff = -(ENCODER_RANGE - enc_diff)
}
else if( enc_diff < -(ENCODER_RANGE / 2) )
{
    enc_diff = (ENCODER_RANGE + enc_diff)
}

// Update counters
if( enc_diff < 0 )
{
    // Increment CCW counter
    ccw_counter -= enc_diff ;
}
else
{
    // Increment CW counter
    cw_counter += enc_diff ;
}