Simple way to control servo

发布于 2023-07-17 19:47:46

image.png

Hello! This article will tell you how to control a servo without using external libraries. Here we use advanced functions for PWM control.
I had tested this code with SG90 servo,bought on Aliexpress.
To begin with, we are studying the datasheet for SG90.
It is written there:
image.png
So we must connect the power to the servo (GND, + 5V) and connect the control wire to pin PB0.
Then we have to adjust the period (or frequency) of the PWM signal as indicated in the datasheet. This frequency corresponds to 50 hertz.
Also from the datasheet we know the DUTY CYCLE interval from 1 to 2 milliseconds. This corresponds to a change in the servo angle from 0 to 180 degrees. Through experimentation, I found that a change in DUTY from 5 to 32 corresponds to a change from 1 to 2 milliseconds.
So the step of change in degrees will be 180 / (32-5), about 6.66. Ominous number... :) It is not possible to get a step less than 6.66 degrees due to the restrictions in 8bit PWM duty.
It may be possible to overcome this limitation using the software PWM signal generation algorithm. For linear transformations, use the map() function.
For desktop testing, this solution is suitable, but in an industrial environment this cannot be done. Need to use optic isolation from your development boardand use a separate power supply for the servo. For example:
image.png

PS. But sometimes you can break the rules described in the datasheet :)
With the new parameters, the servo works with a resolution of about 0.9 degrees! You need to change the code in two places:
1) setPWM_Freq(hpwm, 350); // In setup()
2) uint8_t duty = map(angel,0,180,40,230); // In setAngel()
It turns out that the servo works at a frequency of 350 hertz. I am surprised :). Tip for newbies... more experimentation

0 条评论

发布
问题