const int X_pin = A0; // X轴模拟引脚
// 摇杆状态阈值
const int THRESHOLD_LOW = 400; // 低阈值
const int THRESHOLD_HIGH = 600; // 高阈值
const int CENTER_THRESHOLD = 50; // 中心位置阈值(512±50)
// 上一次的方向状态
String currentDirection = "";
void setup() {
Serial.begin(9600);
pinMode(X_pin, INPUT);
}
void loop() {
checkJoystickLR(); // 只检测左右摇杆状态
delay(50); // 小延时,避免串口数据过于密集
}
// 检测摇杆左右状态(LEFT, RIGHT)
void checkJoystickLR() {
int xValue = analogRead(X_pin); // 读取X轴值
// 判断是否在中心位置
bool isCentered = abs(xValue - 512) < CENTER_THRESHOLD;
if (isCentered) {
currentDirection = ""; // 回到中心时,重置方向为空
return;
}
// 如果不在中心,判断是左还是右
if (xValue < THRESHOLD_LOW) {
currentDirection = "RIGHT";
} else if (xValue > THRESHOLD_HIGH) {
currentDirection = "LEFT";
}
// 持续输出方向,只要方向没回到中心
if (currentDirection != "") {
Serial.println(currentDirection);
}
}