摇杆有两个 x/y 轴的模拟信号 ,一个按钮信号
此代码使用第三方防抖库检测按钮信息
按下后检测摇杆的 x 轴调整幅度,然后调整时间
#include "buttonTest.h"
// 按钮防抖库, https://github.com/thomasfredericks/Bounce2
#include <Bounce2.h>
// 开关对应的 id
#define SWITCH_BUTTON_ID 2
// 当前是否在调整模式下
bool changeModel = false;
// 按钮事件
Bounce2::Button button = Bounce2::Button();
/** 初始化按钮 */
void initButtons()
{
pinMode(LED_BUILTIN, OUTPUT);
updateLedStatus(LOW);
button.attach(SWITCH_BUTTON_ID, INPUT_PULLUP); // 监听哪个脚,这里设置一个上接电平
button.interval(1); // 延时多少时间, 感觉没什么用,而且反应有点慢
button.setPressedState(LOW); // 什么电平时认为是按下
}
/** 更新指示灯状态 */
void updateLedStatus(unsigned int state)
{
digitalWrite(LED_BUILTIN, state);
}
/** 更新按钮 */
void updateButtons()
{
button.update(); // 检测按钮的状态
if (button.pressed()) // 判断按钮的状态
{ // 按钮被按下时
changeModel = !changeModel;
updateLedStatus(changeModel ? HIGH : LOW);
}
// 判断是不是更新时间状态
if (!changeModel)
{
return;
}
// 如果是被按下状态判断摇杆有没有推动
auto type = getChangeType();
switch (type)
{
case Up: // 向上调整
ChangeDateTime(1);
break;
case UpPlus: // 向上加速调整
ChangeDateTime(5);
break;
case Down: // 向下调整
ChangeDateTime(-1);
break;
case DownPlus: // 向下加速调整
ChangeDateTime(-5);
break;
}
}
const unsigned int changeDuration = 150; // 保存多长时间认为调整一次, 毫秒
ChangeType lastJoystickState = Normal; // 摇杆最后的状态
unsigned long lastJoystickTime = 0; // 摇杆更新时间
// 判断当前 摇杆 状态
ChangeType getChangeType()
{
auto xValue = analogRead(A0);
/* Log.infoln("x value: %d", xValue); */
// 判断摇杆当前的状态
ChangeType state = Normal;
if (xValue > (1022 - 50))
{
state = UpPlus;
}
else if (xValue > (511 + 170))
{
state = Up;
}
else if (xValue < (0 + 50))
{
state = DownPlus;
}
else if (xValue < (511 - 170))
{
state = Down;
}
auto current = millis();
// 如果摇杆状态更新,重新开始计时
if (lastJoystickState != state)
{
lastJoystickTime = current;
lastJoystickState = state;
}
// 如果摇杆状态保存一定的时间,则返回该状态
if (current - lastJoystickTime > changeDuration)
{
lastJoystickTime = current; // 重新计时
return state;
}
return Normal;
}