0

If I code like this:

motor.write(0);
Serial.println("Before");
motor.write(180);
Serial.println("After");

Both "Before" and "After" is instantly printed, while the motor is still rotating.
I want "After" or whatever statement to be executed AFTER the motor reaches 180 degree.
How can I implement this? Is it possible to read Servo's statement?

Btw, I don't want to put delay after write(), so other than that strategy.

  • Hobby servos don't provide feedback: you can't know when they have reached their target position. – Edgar Bonet Feb 17 at 15:53
1

How can I implement this? Is it possible to read Servo's statement?

No, it is not possible. When you do a servo.write() it just changes the PWM duty cycle. It's then up to the servo to use that to set its position. The Arduino has no concept at all of the current position of the servo.

Btw, I don't want to put delay after write(), so other than that strategy.

The only other way, besides delaying or otherwise using millis() to wait for a predefined period after your write would be to implement some form of feedback between the shaft of the servo and the Arduino. Maybe a potentiometer, or rotary encoder would do the job.

| improve this answer | |
  • Well, I just ripped off rotary encoder from my old mouse – Ultim8_Clock Feb 18 at 7:04
  • That was great idea, thank you very much. Can you recommend me a good arduino library to use with rotary encoder? – Ultim8_Clock Feb 18 at 7:06
1

It's not possible with the servo alone, but you could add feedback. Some options:

  • An encoder (may be expensive or not available for your servo) will tell you the position.
  • You could also make your own encoder by connecting a potentiometer to the axis. The resistance of the pot will be related to the position of the servo.
  • if you don't need to be exact something simple like a switch at the limit you want to reach.
  • If it doesn't have to be exactly when the position is reached, you could measure the average time it takes (under load) to move from the minimum angle to the maximum angle. This will be the longest it ever takes to move. Then in your code wait 150% of that time before proceeding (to give a bit of a buffer "just in case").

As Majenko said, if you don't want to use a delay, use millis() or micros() to track the current and previous times a line in the loop executed; if the difference is larger than the required delay, the time has elapsed and you can proceed with the rest of the loop. This way you can track time without having to "block" the rest of the loop while you wait.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.