how to set servomotor to an angle

Thread Starter

Farhan Sheikh Ahmad

Joined Mar 31, 2016
i was using following code to control my servomotor by atmega8. instead of stopping servo to the angle it keep on moving to random angles until the port being used stops giving pulse current

#define F_CPU 4000000UL
#include <avr/io.h>
#include <util/delay.h>
int main(void) {
DDRC = 0b00100000;

while(1) {
PORTC ^= 1 << PORTC5;
return 0;

Please any one help me and it it could be then suggest me some better way to do so i'll be very thankful.


Joined Feb 24, 2006

To set the servo to a given angle you must precisely control the ratio of on time to off time within a fixed time period. Your loop toggles the output every 100 milliseconds, producing a 50% duty cycle over a period of 200 milliseconds, which is pretty much guaranteed to not work as you might expect.


Joined Feb 19, 2010
Then why didn't the OP state an RC SERVO??
Servo control has an extremely wide technology range!.
OP has another, earlier, thread where they tell that they want to use PWM, ATmega8 to control servo motor. Like Papa said, since they are using PWM (which you would not know since you did not read earlier thread), the control is through the ratio of On and Off time.

The funny thing is how OP jumped straight into the code.

John P

Joined Oct 14, 2008
On discussion boards like this, most people who say "servo motor" are talking about a hobby servo, not an expensive motor with encoder feedback and all sorts of electronics. You can't stop them doing it, so you just have to check the context to be sure (fairly sure, at least) what kind of setup they're building.


Joined Feb 19, 2010
It is a prevalent problem, seems to point to the need for an RC forum to be included?
Not really. The problem is that people do not present information in clear and organized manner. From what I have seen of OP thus far, I don't expect them to get far or get much help.

And on top of everything, I am pretty sure OP is not a native English speaker. That might explain why their messages are so short and so devoid of detail. It is probably a struggle for them just to put together the messages that they did thus far.