#include <Servo.h>
Servo myServo; // 创建伺服电机对象
const int servoPin = 4; // 伺服电机连接的引脚
const int Y_pin = A1; // Joystick Y轴引脚
// Joystick 阈值
const int THRESHOLD_LOW = 400;
const int THRESHOLD_HIGH = 600;
const int CENTER_THRESHOLD = 50;
int currentAngle = 90; // 初始伺服位置(90度为中间位置)
void setup() {
myServo.attach(servoPin);
myServo.write(currentAngle); // 初始化伺服电机到中间位置90度
Serial.begin(9600);
}
void loop() {
checkJoystickAndMoveServo();
delay(15);
}
void checkJoystickAndMoveServo() {
int yValue = analogRead(Y_pin);
// 向上转动
if (yValue > THRESHOLD_HIGH && currentAngle < 180) { //limit the maximum angle
currentAngle = currentAngle + 2; //change the rotation speed
myServo.write(currentAngle);
}
// 向下转动
else if (yValue < THRESHOLD_LOW && currentAngle > 0) {
currentAngle--; //change the rotation speed
myServo.write(currentAngle);
}
Serial.println(currentAngle);
}