Home > Industry Insights >Gear Motor
TECHNICAL SUPPORT

Product Support

How to write the servo drive code? Attached is detailed code and FAQs

Published 2026-05-01

Servo drive codeThe key point is to use a PWM signal of a specific frequency to control the steering angle. This article directly provides a general code template and debugging method that can be used for mainstream development boards such as Arduino and STM32.No matter which type of servo you are using, as long as you master the basic rules of PWM period 20ms and high level time 0.5ms - 2.5ms corresponding to 0 - 180 degrees, you can independently write stable and reliable driver code

01Core driver code template (general type)

The following code is constructed based on the standard PWM principle and is suitable for most analog servos and digital servos. In actual use, you only need to modify the PWM output pin and timer configuration.

// Servo drive core function (applicable to any platform that supports PWM) // Input: angle (0-180 degrees), output: corresponding high level time (0.5ms-2.5ms) voidservo_write(float angle) { // Linearly map 0-180 degrees to 0.5ms-2.5ms float pulse_width = 0.5 + (angle / 180.0)2.0; // Unit: ms // Set PWM duty cycle: pulse_width / 20ms set_pwm_duty_cycle(pulse_width / 20.0 100);
}

Description of key parameters (must be strictly consistent with steering gear specifications)

PWM period: Fixed 20ms (frequency 50Hz)

The time range of the high level presents the following situation: first it is in the state of 0 degrees for 0.5ms, then it becomes the state of 90 degrees for 1.5ms, and then it becomes the state of 180 degrees for 2.5ms.

Voltage: Common servos are 4.8V-6.0V (be sure to check the servo label)

02Quick Implementation Guide for Different Platforms

2.1 Arduino platform (the most commonly used case)

#includeservomyservo; void setup() { myservo.attach(9); // The signal line is connected to pin 9 } void loop() { myservo.write(0); // Go to 0 degrees delay(1000); myservo.write(90); // Go to 90 degrees delay(1000); myservo.write(180); // Go to 180 degrees delay(1000); }

When solving common problems, if the servo is shaking, check to see if the power supply is independent. Be careful not to take power directly from the 5V pin of the development board, because most USB ports have insufficient power supply.

舵机驱动模块_驱动代码舵机怎么接线_舵机驱动代码

2.2 STM32 platform (using HAL library)

//Configure the timer in PWM mode with a period of 20ms. The prescaler and auto-reload values ​​are calculated based on the clock.// For example, 72MHz clock, prescaler 72-1, auto-reload 20000-1, get 50Hz HAL_TIM_PWM_Start(&htim2, TIM_CHANNEL_1); // Set comparison value: 0 degrees -> 500 (0.5ms), 90 degrees -> 1500, 180 degrees -> 2500 __HAL_TIM_SET_COMPARE(&htim2, TIM_CHANNEL_1, 1500);

The calculation example shows that the clock is 72MHz, after prescaling by 72, the count value is 1us, the auto-reload is 20000, which corresponds to 20ms, and the comparison value is 500, which corresponds to 0.5ms.

2.3 Raspberry Pi (Linux GPIO + software PWM)

import RPi.GPIO as GPIO import time GPIO.setmode(GPIO.BCM) GPIO.setup(18, GPIO.OUT) pwm = GPIO.PWM(18, 50) # 50Hz frequency pwm.start(2.5) # 0 degree duty cycle (0.5/20=2.5%) time.sleep(1) pwm.ChangeDutyCycle(7.5) # 90 degrees time.sleep(1) pwm.ChangeDutyCycle(12.5) # 180 degrees

Please note that the accuracy of software PWM has a certain limit. When encountering high load scenarios, it is recommended to use hardware PWM (such as the pigpio library).

03The core three-step verification method for driver code debugging

When the code prevents the servo from responding correctly, troubleshoot in the following order (90% of the problems will be solved here):

1. To measure the power supply, use a multimeter to measure the voltage between the red and black wires of the servo. This voltage must be greater than or equal to 4.8V and in a stable state. There are common cases where using a 3.7V lithium battery pack causes the servo to not rotate.

2. Measure the signal. Use a logic analyzer or oscilloscope to determine the period of the PWM waveform. Whether it is 20ms plus or minus 0.5ms. Also measure the high-level time. Whether it is within the range of 0.5ms to 2.5ms. There must be punctuation and pauses.

3. Measure the angle and implement the mapping operation: manually set the value to output a high-level signal of 1.5 milliseconds to confirm whether the position of the servo exactly stays at the precise position of 90 degrees (if there is a deviation, this indicates that the center position of the servo is offset, in which case a calibration operation is required).

04Advanced optimization and multi-servo drive

4.1 Simultaneous control of multiple servos (to avoid signal conflicts)

舵机驱动模块_舵机驱动代码_驱动代码舵机怎么接线

For hardware PWM, each servo independently occupies a pin with PWM function, just like Arduino Uno, which has up to 6 such pins.

For the software to be refreshed one by one, within a specific 20ms cycle range, signals reaching the voltage high level in the range of 0.5 to 2.5ms are sent to each servo one by one and in sequence. The code example is as follows:

// Pseudo code: 6 servos share a timer interrupt void timer_interrupt() { static int servo_index = 0; // Turn off all servo signals // Output the corresponding high level to the current servo_index // Set the next interrupt time to the pulse width of the servo // After the interruption ends, switch to the next servo index }

The most critical aspect of multi-server drive is not the code itself, but to ensure that in each cycle, the high-level pulses of all servos do not overlap.. Using DMA or timer output comparison mode, microsecond level accuracy can be achieved.

4.2 Prevent steering gear from shaking and heating

The method for filtering the power supply is to connect an electrolytic capacitor with a capacity ranging from 100 to 470uF and a 0.1uF ceramic capacitor in parallel to the input end of the servo power supply.

code smoothing: Avoid frequent and rapid angle jumps, increaseforThe cycle moves progressively.

Fault protection, when the code is injected to detect the lack of PWM signal, the output will be automatically terminated to avoid deadlock and burnout.

05Frequently asked questions Q/A (quickly locate faults)

Q1: The servo does not turn at all, but the internal motor sound can be heard?

If the current of the power supply is insufficient, it must be replaced by an independent regulated power supply. The requirement for the independent regulated power supply is 5V/2A or above, and the development board USB must not be used for power supply.

Q2: The servo can only turn to 0 degrees and 180 degrees, and the middle angle is invalid?

If there is an error in the PWM cycle, the frequency needs to be checked to see if it is 50Hz, that is, the cycle is 20ms. A common incorrect setting is to set the frequency to 100Hz.

Q3: Code compilation error "Servo.h not found"?

The library has not been installed. In the Arduino IDE, click "Project", then click "Load Library", then click "Manage Library", and then search for "Servo" to install it.

Q4: Will multiple servos interfere with each other when they rotate at the same time?

The signal lines are connected in parallel. However, each servo must occupy its own PWM pin and cannot be directly connected in parallel.

Q5: Does the servo rotation angle deviate from the code setting value by more than 10 degrees?

When the position of the object in the control direction is in the neutral state, there is an offset. Call servo.writeMicroseconds(1500) to perform the process of adjusting the physical neutral position, and then perform the mapping angle operation.

06Action recommendations and core conclusions

The essence of the servo drive is to output a high-level pulse in the range of 0.5ms to 2.5ms within a 20ms period. All codes and hardware debugging are based on this benchmark. Please perform the following operations immediately:

1. Verify the existing code and use an oscilloscope or logic analyzer to measure whether the PWM you output meets the parameters mentioned above.

2. Independent power supply: Completely separate the servo power supply and logic power supply (the same ground is enough).

3. Carry out progressive testing, first test a single servo and let it run an angle cycle. This cycle is from 0 to 90 to 180. After it stabilizes, increase the load.

After you complete the above tests, a copy can be used for production deploymentServo drive code, should cover: timer initialization, duty cycle mapping function, fault recovery logic. Modify the template given in this article according to your platform, then save it as servo_driver.c and reuse it directly in all future projects.

Update Time:2026-05-01

Powering The Future

Contact Kpower's product specialist to recommend suitable motor or gearbox for your product.

Mail to Kpower
Submit Inquiry
+86 0769 8399 3238
 
kpowerMap