简体   繁体   中英

Arduino servo not responding to button press

I'm pretty sure there is a stupid error here but I'm afraid I can't for the life of me work it out!

Simple test program that gets the error:

#include <Servo.h> 

Servo myservo;

int testPIN = 13;
int inputPIN = 5;

void setup() 
{ 
  myservo.attach(8);
  pinMode(testPIN, OUTPUT);
  pinMode(inputPIN, INPUT);
} 

void loop() 
{ 
  if (digitalRead(inputPIN) == HIGH) 
  {
    digitalWrite(testPIN, HIGH);
    myservo.write(90);
  }
  else
  {    
    digitalWrite(testPIN, LOW);
    myservo.write(0);
  }
}

The arduino sweep example ( http://arduino.cc/en/Tutorial/Sweep ) works, so I'm fairly confident the electronics works.

The testPIN also goes on and off as expected so the if statement is working as expected.

Any ideas/suggestions welcome!

EDIT - Sorry the error is that the servo doesn't move at all

EDIT 2 - Something a bit odd is going on here. If I copy/paste the sweep loop into the if clause, the servo reacts as expected (ie input = high makes the servo run a sweep loop, which it doesn't break out of until it reaches the end of, as expected). My immediate thought was delays were needed, but they seem to make no difference no matter how long they are or where they are added in the if/else clauses.

I don't know which arduino board you have, but on the arduino uno, i'm pretty sure that the pin 8 is not a PWM output. And you can not run a servo on a non-PWM output.

See this image of the Uno board, and notice that there is no tilde (the indication that a port supports PWM) on pin 8:

Arduino Mega2560开发板

Have you tried using SoftwareServo.h instead? This example looks like what you are trying to accomplish: http://playground.arduino.cc/ComponentLib/servo

The sweep program that you're linking to is using pin 9, which is a PWM on an uno. Your code is using pin 8, which is NOT a PWM output. Switch your servo over to pin 9 and change the attach in your code to pin 9 and, assuming that this is your only issue, your code should work.

As suggested in the comments, I've just written a function that moves the servo slowly. Not an elegant solution but servo response time isn't issue so it does the trick.

Thanks for all the help and suggestions, and to @praks411 for the wrapper function work around.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM