Сервопривод отличается от моторов постоянного тока наличием обратной связи, позволяющей реализовать заданный угол поворота или поддержку скорости. Для управления сервоприводами нужен либо управляемый контроллером мультивибратор, в таком случае набор снабжается библиотекой подпрограмм. Или мультивибратором становится сам микропроцессор, продаваемый как драйвер серв вместе с блоком настройки, включающим в себя конвертор с языка более высокого уровня, чем ассемблер.

Выходной вал мотора сервы намертво связан с валом переменного резистора обратной связи. Поэтому серва всегда знает в каком она положении в данный момент. Из минусов – невозможность сделать полный оборот. Например одна из них может крутить валом не больше, чем на 180 градусов. Серва соединяется трехжильным кабелем с микроконтроллером: темный цвет – земля GND (грунт), красный средний – питание (Vcc), желтый – управляющий сигнал (S).

Сигнал управления представляет собой повторяющуюся последовательность, в пределах периода T сигнал управления ступенчато переходит с 0 на 1, образуя подобие ГГГГГ..... От величины периода T зависит скорость вращения. А от доли верхней полочки Г – угол поворота. Тут неплохое описание с графиками сигналов СЕРВЫ. Эта сложность не касается программирования серв при помощи соответствующей библиотеки, где есть подпрограммы установки цели (target) и скорости (speed).


У фирмы pololu есть микроконтроллер только для серв, называемый Маэстро (документация). Управление через драйвер) позволяет использовать оболочку программирования с собственным языком. Микроконтроллер имеет входы и UART-интерфейс.

After the installation is finished, your start menu should have a shortcut to the Maestro Control Center (in the Pololu folder). This is a Windows application that allows you to configure, control, debug, and get real-time feedback from the Maestro. There will also be a command-line utility called UscCmd which you can run at a Command Prompt. Windows 10, Windows 8, Windows 7, and Windows Vista users: Your computer should now automatically install the necessary drivers when you connect a Maestro. No further action from you is required.





The SM-S4303R is a standard-sized servo that has been built by SpringRC specifically for continuous rotation (up to 70 RPM at 6 V), and it is the strongest continuous rotation servo we carry (4.8 kg-cm/67 oz-in at 6 V). It features two ball bearings on the output shaft for reduced friction, and it offers easy access to the rest-point adjustment potentiometer. The servo can be controlled using a direct connection to a single microcontroller I/O line without any additional electronics, which makes it a great actuator for beginner robotics projects.

The SM-S4303R continuous rotation servo converts standard RC servo position pulses into continuous rotation speed. The default rest point is 1.5 ms, but this can be adjusted by using a small slotted screwdriver to turn the middle-point positioner. Pulse widths above the rest point result in counterclockwise rotation, with speed increasing as the pulse width increases; pulse widths below the rest point result in clockwise rotation, with speed increasing as the pulse width decreases. Note that this is the reverse of what is described in the datasheet.


Getting started: blinking an LED

The following script will cause the red LED on the Maestro to blink once per second:

It is a good idea to try stepping through this script before doing anything further with scripts on the Maestro. In particular, pay attention to how the command “100” puts the number 100 on the stack, and the DELAY command consumes that number. In the Maestro scripting language, arguments to commands always need to be placed on the stack before the commands that use them, which makes the language seem backwards compared to other languages. It also means that you can arrange your code in a variety of different ways. For example, this program is equivalent to the one above:

The numbers are placed on the stack at the beginning of the loop, then consumed later on in execution. Pay attention to the order of the numbers used here: the 900 goes on the stack first, and it is used last.

A simple servo sequence

The following script shows how to direct servo 0 to five different positions in a loop.

The serial mode must not be set to detect baud rate for this script to work. In detect baud rate mode, the Maestro does not enable any of the servo outputs until the start byte has been received.
Note that the servo positions are specified in units of 0.25 μs, so a value of 4000 corresponds to 1 ms. The text after the # is a comment; it does not get programmed on to the device, but it can be useful for making notes about how the program works. Good comments are essential for complicated programs. It is important to remember the DELAY commands; without these, the script will not wait at all between servo commands, running the loop hundreds of times per second.

Compressing the sequence

The program above takes 58 bytes of program space: 11 bytes for each servo position and 3 for the loop. At this rate, we could store up to 92 servo positions in the 1024-byte memory of the Micro Maestro, or 744 servo positions in the 8192-byte memory of the Mini Maestros. To get the most out of the limited memory, there are a variety of ways to compress the program. Most important is to make use of subroutines. For example, since we repeat the instructions “0 servo 500 delay” several times, we can move them into a subroutine to save space. At the same time, this simplifies the code and makes it easier to make future modifications, such as changing the speed of the entire sequence.

Using the subroutine brings the script down to 31 bytes: 4 per position and 11 bytes of overhead for the loop and to define FRAME. We can go further: inspecting the compiled code shows that putting each number on the stack requires 3 bytes: one byte as a command, and two for the two-byte number. Numbers from 0 to 255 can be loaded onto the stack with just two bytes. Suppose in our application we do not need the full 0.25 μs resolution of the device, since all of our settings are multiples of 100. Then we can use smaller numbers to save another byte:

This program is 29 bytes long, with 3 bytes used per position and 14 bytes of overhead. Note that we could get the same efficiency if we used the SERVO_8BIT command, which takes a one-byte argument from 0 to 254. We can go even smaller by putting all of the numbers together:

If you step through this version program, you will also notice that all five numbers are placed on the stack in a single step: this is because the compiler can use a single command to put multiple numbers on the stack. Using a single command for multiple numbers saves space: we are now down to just 26 bytes. Only 12 bytes are used for the 5 frames, for an average of 2.4 bytes per frame. This is probably compact enough – by duplicating this structure we could fit 420 different positions into the 1024-byte program memory of the Micro Maestro. However, the code can get even smaller. Consider this script, which uses 31 frames to make a smooth back-and-forth motion:

In this version of the code, we have rewritten the FRAME subroutine, using the DEPTH command to automatically load frames from the stack until there are none left. This program uses 34 bytes to store 31 frames, for an average of just 1.1 bytes per frame. We could store a sequence containing 900 different positions in the memory of the Micro Maestro using this kind of script.


Rambler's Top100