servo posistion for loop

is very new to this. I try to learn through a project I have where I want a servo to go slowly to a position and stay there.

Have looked at the example in (servo) and there you can set the "time" with delay but it goes back and forth as I do not want.

Have also tried to enter the position (servo.write ()) and then it goes where I want and stops but far too fast.

As I understand it, you have to use a for loop to make it go slowly but I do not manage to write so the servo stops and stands still where I want it.

The last thing I tested was

#include <Servo.h>


Myservo servo; // create servo object to control a servo
// twelve servo objects can be created on most boards


int pos; // variable to store the servo position
int pos1 = 1;
void setup () {
  myservo.attach (4); // attaches the servo on pin 9 to the servo object
  Serial.begin (9600);
}


void loop () {
Serial.print (pos);
if (pos1 == 1) {
for (pos = 0; pos <= 180; pos + = 1) {// goes from 0 degrees to 180 degrees
    // in steps of 1 degree
    myservo.write (post); // tell servo to go to position in variable 'pos'
    delay (15); // waits 15ms for the servo to reach the position
}
}
if (pos == 181) {
  pos1 = 0;
}


[/ code]


feels like there should be a better or more correct way.

If you want it to do something only once, put it in setup():

#include <Servo.h>
Servo myservo; // create servo object to control a servo

void setup ()
{
  myservo.attach (4); // attaches the servo on pin 9 to the servo object
  Serial.begin (9600);

  // Move slowly from 0 to 180
  for (int pos = 0; pos <= 180; pos += 1)  // goes from 0 degrees to 180 degrees
  {
    // in steps of 1 degree
    myservo.write (pos); // tell servo to go to position in variable 'pos'
    delay (15); // waits 15ms for the servo to reach the position
  }
}

void loop () {}

Well that doesn't compile so it definitely does nothing now.

If you change write(post) to write(pos) that will help. And if you correct 'Myservo servo;' so it looks like all the examples in the IDE it will almost work.

But you don't need the if because there's no way pos can ever be 181. Just take that line out.

Alternatively you could have just put all the code in setup() which only ever runs once instead of in loop() whose main purpose is to loop round over and over again running things many times.

And for future information it is not really necessary to write your own loop like that, though it's a useful learning exercise. If you want to use it in real life there is a library VarSpeedServo.h as an alternative to Servo.h. It is very similar but has a speed parameter to the write() command so you can control how fast it moves, all on one line.

Steve

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