#include <Wire.h>
#include <Adafruit_PWMServoDriver.h>
Adafruit_PWMServoDriver pwm = Adafruit_PWMServoDriver();
const uint8_t SERVO_CHANNEL = 0;
const int SERVO_MIN = 150;
const int SERVO_MAX = 600;
const int buttonOnPin = 2;
const int buttonOffPin = 3;
const int button0Pin = 4;
const int button90Pin = 5;
const int button180Pin = 6;
const int button270Pin = 7;
const int ledPin = 8;
// 用于保存上一次按键状态(用于状态变化检测)
bool lastButtonOnState = HIGH;
bool lastButtonOffState = HIGH;
bool lastButton0State = HIGH;
bool lastButton90State = HIGH;
bool lastButton180State = HIGH;
bool lastButton270State = HIGH;
void setup() {
Serial.begin(9600);
pinMode(ledPin, OUTPUT);
pinMode(buttonOnPin, INPUT_PULLUP);
pinMode(buttonOffPin, INPUT_PULLUP);
pinMode(button0Pin, INPUT_PULLUP);
pinMode(button90Pin, INPUT_PULLUP);
pinMode(button180Pin, INPUT_PULLUP);
pinMode(button270Pin, INPUT_PULLUP);
pwm.begin();
pwm.setPWMFreq(50);
delay(10);
Serial.println("系统启动完成");
}
int angleToPulse(int angle) {
return map(angle, 0, 270, SERVO_MIN, SERVO_MAX);
}
void loop() {
// LED 开按钮
bool currentOnState = digitalRead(buttonOnPin);
if (currentOnState == LOW && lastButtonOnState == HIGH) {
digitalWrite(ledPin, HIGH);
Serial.println("LED 已打开");
}
lastButtonOnState = currentOnState;
// LED 关按钮
bool currentOffState = digitalRead(buttonOffPin);
if (currentOffState == LOW && lastButtonOffState == HIGH) {
digitalWrite(ledPin, LOW);
Serial.println("LED 已关闭");
}
lastButtonOffState = currentOffState;
// 舵机 0 度
bool current0State = digitalRead(button0Pin);
if (current0State == LOW && lastButton0State == HIGH) {
pwm.setPWM(SERVO_CHANNEL, 0, angleToPulse(0));
Serial.println("舵机转动至 0°");
}
lastButton0State = current0State;
// 舵机 90 度
bool current90State = digitalRead(button90Pin);
if (current90State == LOW && lastButton90State == HIGH) {
pwm.setPWM(SERVO_CHANNEL, 0, angleToPulse(90));
Serial.println("舵机转动至 90°");
}
lastButton90State = current90State;
// 舵机 180 度
bool current180State = digitalRead(button180Pin);
if (current180State == LOW && lastButton180State == HIGH) {
pwm.setPWM(SERVO_CHANNEL, 0, angleToPulse(180));
Serial.println("舵机转动至 180°");
}
lastButton180State = current180State;
// 舵机 270 度
bool current270State = digitalRead(button270Pin);
if (current270State == LOW && lastButton270State == HIGH) {
pwm.setPWM(SERVO_CHANNEL, 0, angleToPulse(270));
Serial.println("舵机转动至 270°");
}
lastButton270State = current270State;
delay(10); // 防抖延迟
}