增量编码器驱动程序

增量编码器驱动程序

编码器驱动

image

  • 我们可以将当A、B电平有变化时记录下来

  • 这样可以利用记录下来的数据,来判断左旋还是右旋

/**
 * @file Encoder.c
 * @brief  增量编码器驱动程序
 * @author HadyLiu email:HadyLiu@outlook.com
 * @version 0.0.1
 * @date 2026-01-21
 *
 * @copyright Apache 2.0
 */
#include "Encoder.h"

EncoderHandTypedef GetEncoderStatus(EncoderUnion *p_encoder, unsigned char ec_A_Now, unsigned char ec_B_Now)
{
    EncoderHandTypedef EncoderHand = NoHand;

    if (ec_A_Now != p_encoder->lastA || ec_B_Now != p_encoder->lastB)
    {
        p_encoder->code <<= 2;
        p_encoder->lastA = ec_A_Now; // 更新编码器上一个状态暂存变量
        p_encoder->lastB = ec_B_Now; // 更新编码器上一个状态暂存变量

        if (p_encoder->code == 0b00111000 || p_encoder->code == 0b00000111)
        {
            EncoderHand = LeftHand;
        }
        if (p_encoder->code == 0b00110100 || p_encoder->code == 0b00001011)
        {
            EncoderHand = RightHand;
        }
    }
    return EncoderHand;
}

#ifndef __ENCODER_H__
#define __ENCODER_H__

#include "SYSCFG.H"

typedef union
{
    /* data */
    struct
    {
        unsigned char lastB : 1; // 低位
        unsigned char lastA : 1;
        unsigned char : 6; // 高位
    };
    struct
    {
        unsigned char code : 6; // 低位
        unsigned char : 2;
    };
} EncoderUnion;

typedef enum
{
    NoHand,
    LeftHand,
    RightHand
} EncoderHandTypedef;

extern EncoderHandTypedef GetEncoderStatus(EncoderUnion *p_encoder, unsigned char ec_A_Now, unsigned char ec_B_Now);

#endif

posted @ 2026-02-03 22:02  HadyLiu  阅读(1)  评论(0)    收藏  举报