Home > Industry Insights >Gear Motor
TECHNICAL SUPPORT

Product Support

Let The Servo Swing Back And Forth And Achieve Free Rotation With Just A Few Lines Of Code

Published 2026-03-25

Have you ever encountered this situation - theservoyou bought can only turn in one direction, or can only stop at a few fixed angles, completely unable to achieve the smooth back-and-forth swing effect? Don't worry, this is actually not a problem with theservoitself, but the program we wrote is not "smart" enough. Today we will talk about how to use a few simple lines of code to make theservotruly rotate freely back and forth, making your little invention instantly agile.

Understand the underlying logic of steering gear rotation

The reason why the steering gear can accurately stop at a certain angle depends on the internal motor and an angle feedback system. To put it simply, it determines which position it wants to move to by receiving a PWM signal (that is, a pulse width modulation signal). Usually the signal period is 20 milliseconds, and the high level time is between 0.5 and 2.5 milliseconds, corresponding to the angle range of 0 to 180 degrees. Understand this logic, when we write a program, we have mastered the "steering wheel". If we want the servo to turn, we just need to send it the corresponding signal value.

When using this type of development board to control, you don't need to calculate those complicated pulse times yourself, just call the ready-made library functions. For example, in thewrite()function inServo.hlibrary, you only need to write.write(90), and the servo will turn to the 90-degree position. So if you want it to rotate back and forth freely, the core is to make this angle value change repeatedly within the specified range.

How to write the simplest code to rotate back and forth

If you are new to programming, you can start with the most basic "back and forth movement". We first use a variable to store the current angle, then let it start from 0 degrees, increase by 1 degree each time, until it increases to 180 degrees, and then decrease it by 1 degree each time, back to 0 degrees, thus completing a complete back-and-forth swing cycle. Pay attention to adding an appropriate delay here, otherwise the servo will turn too fast and look like it is convulsing.

In actual operation, the code structure is actually very simple. You first define the servo pins insetup()function, and then write twoforloops inloop()function. One loop increments the angle and the other loop decrements it. Each loop calls.write(angle)internally, and then cooperates withdelay(15)to control the rotation speed. The effect written like this is that the servo rotates back and forth smoothly like a pendulum.

Key parameters controlling speed and angle range

Many friends tend to overlook one detail when writing programs - speed control. If you want the servo to turn slower, you can add a longer delay, such asdelay(30), after each angle change, but this will make the overall movement appear laggy. A better way is to reduce the angle increment each time, for example, changing it from 1 degree to 0.5 degrees each time. In this way, the movement trajectory of the servo will be more delicate and it will look more mechanically beautiful.

The angle range is also entirely up to you. It doesn't necessarily have to go from 0 to 180, you can just have it rotate back and forth between 90 and 120 degrees. This is particularly useful in certain application scenarios of robotic arms or small ornaments. Just modify the start value and end value inforloop, such asfor(angle=45; angle , so that the servo will reciprocate between 45 and 135 degrees.

Make turning smarter with buttons or sensors

It's not cool enough to just let the servo turn back and forth on its own. It would be more interesting if you could add some external control. You can connect a button and press the servo to start rotating back and forth, and press it again to stop at the current angle. Or use ultrasonic sensors to detect objects in front of you, and automatically trigger a swinging action when an object approaches. This way you can create an interactive device that "says hello."

To implement this function, you only need to add a few judgment conditions to the program. First read the sensor data, and decide whether to execute the servo's round-trip cycle based on the data value. Here is a little trick. In order to avoid the program getting stuck in the loop, you can encapsulate the rotation of the servo into a function, and then useifcondition in the main loop to determine whether to call this function. In this way, the main program can handle sensor reading and servo control at the same time without interfering with each other.

Solve common stuck and jitter problems like this

In actual debugging, you may encounter situations where the servo shakes or becomes stuck at a certain angle. This is usually caused by insufficient power supply. The instantaneous current of the servo is relatively large when starting and reversing direction. If the power supply is only powered by the 5V pin on the development board, voltage instability will easily occur. The solution is also very simple. Find an external power supply, such as four 1.5V batteries or a 5V 2A power adapter. Connect the positive and negative poles to the red and brown wires of the servo respectively. At the same time, connect the GND of the development board and the GND of the power supply together to ensure that the signal reference voltage is consistent.

Another situation is that there is not enough delay added in the program. If you change the angle value immediately afterwrite(), and the servo receives a new command before it reaches the specified position, a strange twitching feeling will occur. Leave at least 15 to 20 milliseconds of waiting time between each angle change to allow the servo to have enough time to complete the action. This is why we mentioned before that we need to adddelayto the loop.

Advanced gameplay from simple swing to creative applications

Once you've mastered the basics of turning back and forth, you can try more interesting combinations. For example, let the servo cooperate with LED lights to light up lights of different colors when turning to a certain angle; or use two servos to form a simple mechanical arm to achieve synchronous or alternate swings. These ideas can be used in smart home gadgets, children's toy modifications or art installations to instantly enhance the fun and interactivity of the product.

Furthermore, you can also save the rotation modes and timings to create an "action library" and use your mobile phone's Bluetooth or infrared remote control to call different swing modes. In this way, your work is no longer a repetitive mechanical movement, but has a variable "expression" that can show different action postures according to the scene, giving users a richer experience.

What interesting small projects are you doing using servos? Have you ever encountered that kind of programming problem that makes people mad? Welcome to share your story in the comment area, or directly search for "Shenzhen Hengxing Micro Motor" to find us to get more practical steering gear control solutions and source code references, so that the next idea can be implemented more smoothly.

Update Time:2026-03-25

Powering The Future

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

Mail to Kpower
Submit Inquiry
WhatsApp Message
+86 0769 8399 3238
 
kpowerMap