Published 2026-05-06
"Knowledge is power." - Francis Bacon.
In this embedded world, this motto has a completely new flesh and blood, that is, precise timing is also power.
Late at night, a man who was a robotic arm enthusiast was facing the screen. At this time, he discovered that his servo was trembling like a Parkinson's patient. At this time, he suddenly realized that the control code was not something magical, but actually mathematics.
I'll get it herekpower servoTake an example to analyze the underlying logic of the 51 microcontroller that generates PWM signals, and then provide a code skeleton that can be directly transplanted.。
All cases are derived from common situations in the laboratory, such as "steering gear stuck", "angle drift", and "power-on jump" and other frequently occurring faults.
core argument: The essence of servo control is the "time carving" of pulse width.
Servo is a "time paranoid".
It only recognizes one language, which is a PWM wave with a period of 20ms, and its high level time is between 0.5ms and 2.5ms.。
chain of causation:
Reason A: The crystal oscillator frequency deviates, causing the initial value of the timer to be calculated incorrectly, which in turn causes the pulse width error to accumulate, causing the steering gear positioning to deviate.
Reason B, the interrupt nesting is not processed, the main loop interrupts the PWM output, the pulse period becomes longer and shorter, and the servo emits a sharp beep.。
An enthusiast once used a 12MHz crystal oscillator to directly apply a timer value of 11.0592MHz. Then, the servo made a "nodding" action at a frequency of 15Hz, as if to mock the code for being written too hastily.
Ask yourself the answer: Why do some people fail to copy the code from the Internet?
Answered by themselves: The reason is that no one told them that the machine cycle of the 51 microcontroller is 12 times the crystal oscillator cycle, and the STC series 1T mode is 12 times the speed of the traditional 8051。
The mathematical expression of pulse width modulation is as follows (pseudocode):
High level time (ms) = 0.5 + (angle/180)2.0 timer reload value = 65536 - (pulse width_us) / (12/crystal MHz)
The key conclusion is that there is no steering gear control calibrated to an outdated time base. The situation is like using a tape measure to measure sea level. The tool itself is fine, but the reference system is a disaster.
Tip word: pulse width modulation
Open Keil, create a new project, and select AT89C52.
This is a very common basic case, and it is also the starting point for 95% of beginners to make the servo rotate quietly for the first time.

Signal line → P1.0
Red line → 5V (independent power supply! Do not take power from the development board)
Black line → GND
Code structure(Divided into four stages according to timeline):
1. Initialize timer: Mode 1 (16 bit), 12T mode.
2. Calculation parameters:
Period 20ms → 20000us
Zero degrees Celsius corresponds to 0.5 milliseconds. It can be seen that the accuracy of accumulating 0.1 microseconds after one timer interrupt is too wasteful. Based on this, software counting within a single timed interrupt should be used instead.
3. Interrupt service function:
void Timer0_ISR() interrupt 1 { static unsigned char counter = 0; TH0 = 0xFC; // Reload value: interrupt once every 1ms (12MHz crystal oscillator) TL0 = 0x66; counter++; if(counter = 20) counter = 0; }
Note that the value range of pulse_width_in_ms is 0.5 to 2.5, but in the code it is multiplied by 10 and stored as an integer.
4. Main loop modifies pulse width:
pulse_width_in_ms = 10; // 1.0ms → 0 degrees? No, it is -45 degrees! pulse_width_in_ms = 15; // 1.5ms → median pulse_width_in_ms = 20; // 2.0ms → 90 degrees
In the relevant case for verification, when pulse_width_in_ms is equal to 10, the actual measured angle pointed by the servo arm is -45°. This angle state is due to the common connection method, which causes the zero point to shift. The reason why such a result shows that the calibration operation needs to be performed in the opposite direction.
The request for help was sent by a factory automation engineer with the same code.kpower servoIt’s the same one. On his production line, the servo at station 5 always locks up.
After three hours of investigation, we found:
Q/A:Why does the servo spin crazily as soon as it is powered on?
Answer: Because the P1.0 port is high during reset, it should be set to low during initialization.
Q/A:Why is my angle correspondence reversed?
The following is: Check the installation direction of the servo arm. For many brands of servos, 0 degrees corresponds to 0.5ms. However, the definition of some aircraft model servos is the opposite.。

Q/A:What should I do if the servo shakes after the battery voltage drops?
Answer: Due to insufficient current due to voltage reduction, undervoltage lockout is set when setting up an independent power supply, and the threshold is set to 4.8V.
Q/A:Is it possible for a 51 microcontroller to control 8 servos at the same time?
Answer: This is not possible, because a separate timer interrupt will time out, so it needs to be replaced with a PCA module or time-sharing refreshed.
Fear appeals. If you ignore any of the above, your servo will smoke at the 47th minute of debugging, and this is the most frequent hardware burnout time point in laboratory statistics.
Prompt word: time base
Controlling one servo is an enumeration; controlling eight servos is an algorithm.
When you need to let the robot arm draw a sinusoidal trajectory, linear pulse width control immediately exposes its weaknesses:
The angular velocity of each single joint presents a discontinuous state, which causes a sudden change in the acceleration of the end, ultimately causing mechanical vibration to be transmitted to the base.
causal argument:
The 51 microcontroller does not have a hardware PWM array, so it has to use the "time-sharing polling + intermediate variable interpolation" method.
Solution:
1. Divide the 20ms large period into N time slots (N=number of servos).
2. Only one signal line is pulled high in each time slot, and the rest are kept low.
3. Use an array to store the pulse width of each servo, and output it sequentially within the interrupt.
It is like a kindergarten childcare worker delivering edible crispy snacks to many children one by one and alternately. Each time they are given is only a very short millisecond. Although it seems ruthless and cold, it has an effective effect.
Code transformation example (pseudocode logic):
unsigned int pwm_val[8] = {10,15,20,12,18,9,14,16}; unsigned char current_servo= 0; void Timer0_ISR() interrupt 1 { // Turn off the previous servo signal P1 &= 0xFE; // Only clear P1.0, actual mask is required // Load the current servo high level time TH0 = (65536 - pwm_val[current_servo]100) >> 8; // Assume the unit is 0.1ms TL0 = (65536 - pwm_val[current_servo]100) & 0xFF; // Turn on the current servo signal P1 |= (1
The first is a key reminder. As for this code, whenever a servo switch occurs, the timer will be restarted. As a result, the final total period no longer maintains the original value of 20ms. In view of this situation, it is necessary to add additional time logic.
Tip word: dead zone
Even if they are from the same batchkpowerServo, due to individual differences, will also cause 15% of servos to have a static difference of one to three degrees.
This isn't a glitch, it's the tolerance of physics.
Looking back at history, in the 1980s, industrial robots used a potentiometer feedback method, and the dead zone setting under this feedback method was as high as five degrees; now, magnetic encoder servos can already achieve a repetition accuracy of 0.1 degree. However, the eight-bit PWM resolution of the 51 microcontroller, which is the 256-level type, can only distinguish changes of about 0.7 degrees.
product review bodyTuning steps:
1. Use rough calibration method, set the median pulse width to 1.5ms and write it, then measure the actual angle and record the offset Δθ.
2. Linear compensation: In the formula composed of angle and pulse width, an offset correction term is added. This correction term is in the form that the pulse width is equal to the base value plus the angle step plus the offset. The specific formula is: pulse = base + anglestep + offset.
3. Avoiding dead zone: When the target angle is different from the current angle
Example: In an underwater robotic arm project, changes in seawater temperature caused the crystal oscillator frequency to drift by ±0.1%. Engineers calibrated themselves every 10 minutes: turning the servo to the mechanical limit position, recording the corresponding pulse width, and correcting the time base under dynamic conditions.
"Patience is the basis of all intelligence." - Plato.
The ultimate secret about the control of the 51 microcontroller servo does not lie in the wonderful skills displayed by the code, but in the awe of every microsecond.
Repeat key points:
PWM is not a complex theory;pulse width modulationThe mathematical constraints behind this keyword.
Time base stability > Code elegance.
When encountering jitter, howling, or drifting conditions, first check the power supply, then check the interruption, and finally question the steering gear.
Suggestions for action(The final footing of the spiral):
1. Tonight, I will use a breadboard to build a single servo test circuit.
2. Starting from ten degrees, advance in steps, and use an oscilloscope or logic analyzer to record the actual pulse width corresponding to each angle.
3. Add dead zone function and voltage monitoring warning to the code.
4. Use your 51 microcontroller as a "time engraving machine". Every time it is interrupted, it is the moment when the engraving knife falls.
On an autumn night, there is a cool breeze flowing through the laboratory window. At this time, a neatly arranged row of square waves displayed on the oscilloscope is jumping on the fluorescent screen. At this moment, you finally understand that control is not a conquest, but a reconciliation with time.
At this moment, start writing your first servo control code for the 51 microcontroller. Remember, for every precise movement, you are fulfilling your promise of microseconds.
Update Time:2026-05-06
Contact Kpower's product specialist to recommend suitable motor or gearbox for your product.