【问题标题】:How do you turn a servo 90 degrees when you press a button and do the same with 180 degrees and 0 degrees当您按下按钮时如何将伺服系统转动 90 度并用 180 度和 0 度做同样的事情
【发布时间】:2022-01-06 12:51:55
【问题描述】:

这可能看起来像一个愚蠢的问题,但我仍在学习过程中,我真的想在互联网上查看,但有时我并没有真正让它发挥作用。 我的代码如下:

#include <Arduino.h>
#include <Servo.h>

Servo Myservo;
int SERVO_PIN = 8;
int ServoButton_S1 = 2;

void setup() {
  Myservo.attach(SERVO_PIN);
}

void loop() {
  Myservo.write(0);
  delay(2000);
  Myservo.write(90);
  delay(2000);
  Myservo.write(180);
  delay(2000);
}

伺服器现在从 0 度(等待 2 秒)转到 90 度(等待 2 秒)再转到 180 度,如此循环。

问题是我想要一个在我按下按钮时移动的伺服系统。 所以就像当我按下按钮时伺服转到 90 度,但是当我再次按下按钮时,它转到 180 度,当我再次将它推到 0 度时,它必须继续。 所以我添加了按钮并将其命名为:

int 伺服按钮_s1 = 2;

但每当我在 void 循环中添加它时,它只能工作 1 次。

我希望有人可以帮助我。谢谢

【问题讨论】:

  • 按钮处理代码在哪里?

标签: c++ arduino


【解决方案1】:

您必须检查每次循环迭代的按钮状态。
比如:

#include <Arduino.h>
#include <Servo.h>

Servo Myservo;
int SERVO_PIN = 8;
const int ServoButton_S1 = 2;
int some_counter = 0;

void setup() {
  Myservo.attach(SERVO_PIN);
}

void loop() 
{
  //read the state of the pushbutton value:
  int buttonState = digitalRead(buttonPin);

  // check if the pushbutton is pressed. If it is, the buttonState is HIGH:
  if (buttonState == HIGH) {
    if (some_counter == 0)
    {
        Myservo.write(0);
        delay(2000);
        ++some_counter;
    }
    else if (some_counter == 1)
    {
        Myservo.write(90);
        delay(2000);
        ++some_counter;
    } 
    else if (some_counter == 2)
    {
        Myservo.write(180);
        delay(2000);
        some_counter = 0;
    }
  }
}

您也可以查看 Arduino 网站;有很多教程示例。

【讨论】:

    【解决方案2】:

    这只是另一种解决方案。

    #include <Servo.h>
    
    #define SERVO_PIN 8
    #define ANGLE_BUTTON 2
    
    Servo Myservo;
    int counter = 0;
    int angles[] = {0, 90, 180};
    int angleAmounts = sizeof(angles) / sizeof(angles[0]);
    
    void setup() {
      pinMode(ANGLE_BUTTON, INPUT_PULLUP);
      Myservo.attach(SERVO_PIN);
    }
    
    void loop()
    {
      int buttonState = digitalRead(ANGLE_BUTTON);
    
      if (buttonState == LOW) {
        counter = ++counter % angleAmounts;
        Myservo.write(angles[counter]);
        delay(2000);
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-11-04
      • 2020-05-20
      • 2014-07-11
      • 2013-07-19
      • 1970-01-01
      • 2013-04-22
      • 2019-11-12
      • 1970-01-01
      相关资源
      最近更新 更多