• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
MKT-porter
博客园    首页    新随笔    联系   管理    订阅  订阅
arduino按键控制舵机

 

 

#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);  // 防抖延迟
}

  

posted on 2025-04-12 03:41  MKT-porter  阅读(62)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3