#include <Servo.h>
Servo myServo; // 创建舵机对象
int potPin = A0; // 电位器连接到A0引脚
int servoPin = 9; // 舵机信号线连接到9号引脚
int lastAngle = 0; // 记录上一次的有效角度
const int numReadings = 10; // 移动平均滤波的采样次数
int readings[numReadings]; // 存储采样值的数组
int readIndex = 0; // 当前采样值的索引
int total = 0; // 采样值的总和
void setup() {
myServo.attach(servoPin); // 将舵机对象连接到指定的引脚
Serial.begin(9600); // 初始化串口通信,用于调试
// 初始化滤波数组
for (int i = 0; i < numReadings; i++) {
readings[i] = 0;
}
}
void loop() {
// 读取电位器的值
int potValue = analogRead(potPin);
// 移动平均滤波处理
total = total - readings[readIndex]; // 减去最早的采样值
readings[readIndex] = potValue; // 存储当前采样值
total = total + readings[readIndex]; // 加上当前采样值
readIndex = (readIndex + 1) % numReadings; // 更新索引
// 计算平均值
int averageValue = total / numReadings;
// 将滤波后的值映射到舵机角度(0-180度)
int angle = map(averageValue, 0