97 lines
1.9 KiB
C++
97 lines
1.9 KiB
C++
|
/*
|
||
|
* File name: encoder.cpp
|
||
|
* Author: JRNitre
|
||
|
* Version: MASVersion.0.0.0b
|
||
|
* Date: 2024-05-10
|
||
|
*
|
||
|
* Description:
|
||
|
* 旋转编码器驱动程序.
|
||
|
*/
|
||
|
|
||
|
// 头文件
|
||
|
#include "encoder.h"
|
||
|
|
||
|
// 全局变量
|
||
|
|
||
|
long encoderLastToggled = 0;
|
||
|
|
||
|
ESP32Encoder encoder;
|
||
|
|
||
|
/*
|
||
|
* Function: encoder_init
|
||
|
* Description:
|
||
|
* 初始化旋转编码器.
|
||
|
*
|
||
|
* Input: void
|
||
|
* Output: void
|
||
|
* Return: BasicEncoder 返回创建的旋转编码器对象
|
||
|
*
|
||
|
* Other: nullptr
|
||
|
*/
|
||
|
void encoder_init(){
|
||
|
|
||
|
// 设置工作模式
|
||
|
ESP32Encoder::useInternalWeakPullResistors = puType::up;
|
||
|
|
||
|
// 设置编码器工作引脚
|
||
|
encoder.attachHalfQuad(ENCODER_DT, ENCODER_CLK);
|
||
|
|
||
|
// 设置计数器数值
|
||
|
encoder.setCount(0);
|
||
|
|
||
|
// 清除计数器
|
||
|
encoder.clearCount();
|
||
|
}
|
||
|
|
||
|
/*
|
||
|
* Function: encoder_getCount
|
||
|
* Description:
|
||
|
* 返回当前计数器的数值.
|
||
|
*
|
||
|
* Input: void
|
||
|
* Output: void
|
||
|
* Return: long 返回当前计数器的数值
|
||
|
*
|
||
|
* Other: nullptr
|
||
|
*/
|
||
|
long encoder_getCount(){
|
||
|
return encoder.getCount();
|
||
|
}
|
||
|
|
||
|
/*
|
||
|
* Function: encoder_getKeyNum
|
||
|
* Description:
|
||
|
* 查询当前键值.
|
||
|
*
|
||
|
* Input: void
|
||
|
* Output: void
|
||
|
* Return: uint8_t 返回当前键值
|
||
|
*
|
||
|
* Other:
|
||
|
* 该旋转编码器有三种状态
|
||
|
* 1. 顺序旋转
|
||
|
* 2. 逆序旋转
|
||
|
* 3. 无旋转
|
||
|
* 根据约定好的规则进行判断并且返回相应的键值
|
||
|
*/
|
||
|
uint8_t encoder_getKeyNum(){
|
||
|
uint8_t retKey = 0;
|
||
|
|
||
|
// 判断编码器是否有旋转
|
||
|
if (encoderLastToggled != encoder_getCount()){
|
||
|
if (encoderLastToggled > encoder_getCount()){
|
||
|
retKey = 1;
|
||
|
}
|
||
|
if (encoderLastToggled < encoder_getCount()){
|
||
|
retKey = 2;
|
||
|
}
|
||
|
} else {
|
||
|
retKey = 0;
|
||
|
}
|
||
|
|
||
|
// 同步最新的计数器数值
|
||
|
encoderLastToggled = encoder_getCount();
|
||
|
|
||
|
// 返回最终的键值
|
||
|
return retKey;
|
||
|
}
|