为什么我的伺服控制不起作用?

时间:2014-10-30 22:49:10

标签: arduino

基本上我试图用两个按钮来控制伺服(一个用于前进,一个用于向后)。但是,我的代码不起作用,我不知道为什么。基本上我使用Sweep和Button示例来制作此代码。但是,除非我的连接出现问题,否则它似乎不起作用。

#include <Servo.h>

Servo servoOne;
int servoOnePos = 0;
const int buttonUpPin = 13;
const int buttonDownPin = 12;
int buttonUpState = 0;
int buttonDownState = 0;

void setup() {
  servoOne.attach(11);
  pinMode(buttonUpPin, INPUT);
  pinMode(buttonDownPin, INPUT);
}

void loop() {
  buttonUpState = digitalRead(buttonUpPin);
  buttonDownState = digitalRead(buttonDownPin);
  if (buttonUpState == HIGH) {
    for (servoOnePos < 180; servoOnePos += 1;) {
      servoOne.write(servoOnePos);
      delay(15);
    }
  } else if (buttonDownState == HIGH) {
    for (servoOnePos <= 180; servoOnePos = servoOnePos - 1;) {
      servoOne.write(servoOnePos);
      delay(15);
    }
  }
}

1 个答案:

答案 0 :(得分:0)

#include <Servo.h>

Servo servoOne;

int pos = 90;   
const int maxDeg = 160;
const int minDeg = 5;

const int buttonUpPin = 13;
const int buttonDownPin = 12;

const int leftPin = 3;
const int rightPin = 2;

int leftPressed = 0;
int rightPressed = 0;

void setup() 
{ 
  servoOne.attach(11); 
  pinMode(buttonUpPin, INPUT);
  pinMode(buttonDownPin, INPUT);
} 

void loop() 
{ 
leftPressed = digitalRead(leftPin);
rightPressed = digitalRead(rightPin);

 if(leftPressed){
   if(pos < maxDeg) {
     pos += 3;
   }
    servoOne.write(pos);     
 }
 if(rightPressed){
   if(pos > minDeg) {
     pos -= 3;
   }
     servoOne.write(pos);  
   }
  delay(15);                     
}