How to make servo rotate completely?

I wrote some code that makes my Servo motor rotate whenever the photoresistor gets dark. I held my photoresistor up to a white computer screen and periodically made the screen black. When it sensed black, the servo would move, but when I flash the black color very quickly, (for less than a second) The servo would rotate, but just barely. How do I make it so that the servo rotates completely to how much it should and then go back when it sees white? I am including my current code below.

[code]
#include <Servo.h>
Servo myservo;
int sensorPin = A0;
int sensorValue = 0;
int val;
void setup() {
  // put your setup code here, to run once:
  myservo.attach(2);
  Serial.begin(9600);
  myservo.write(80);
}
void loop() {
  // put your main code here, to run repeatedly:
  sensorValue = (analogRead(sensorPin));
  if (sensorValue < 650) {
    // cactus 
    val = 130;
  }
  else {
    //no cactus
    val =  80;
    myservo.write(val);
    delay(0);
  }
  Serial.println(sensorValue); //debug
  myservo.write(val);
  delay(15);
}
[/code]

Servos take time to move. A typical servo is specified at 300ms to move 60 degrees (unloaded). Is the servo loaded?

Give the servo enough time to move. Introduce a bit of delay when it senses the cactus. Use millis() for the timing, not delay().

Non-blocking timing tutorials:
Several things at a time.
Beginner's guide to millis().
Blink without delay().

Or you could try VarSpeedServo.h instead of Servo.h. That has a 'wait' parameter on the write() that should allow the servo complete the move before continuing. I've used that library a few times but not for that purpose so you'll have to try it yourself to see if it does what you need.

Steve

This topic was automatically closed 120 days after the last reply. New replies are no longer allowed.