Servomechanism Controller

System Model

A position servomechanism consists of a DC motor, gearbox, elastic shaft, and a load.

Position Servomechanism Schematic

The differential equations representing this system are


where V is the applied voltage, T is the torque acting on the load, ωL=θ˙L is the load's angular velocity, ωM=θ˙M is the motor shaft's angular velocity, and the other symbols represent constant parameters (see Parameters Used in the Servomechanism Model for more information on these).

If you define the state variables as xp=[θLωLθMω<]T, then you can convert the above model to an LTI state-space form:


Parameters Used in the Servomechanism Model


Value (SI Units)




Torsional rigidity



Motor constant



Motor inertia



Load inertia



Gear ratio



Motor viscous friction coefficient



Load viscous friction coefficient



Armature resistance

Control Objectives and Constraints

The controller must set the load's angular position, θL, at a desired value by adjusting the applied voltage, V. The only measurement available for feedback is θL.

The elastic shaft has a finite shear strength, so the torque, T, must stay within specified limits

|T| ≤ 78.5Nm

Also, the applied voltage must stay within the range

|V| ≤ 220V

From an input/output viewpoint, the plant has a single input, V, which is manipulated by the controller. It has two outputs, one measured and fed back to the controller, θL, and one unmeasured, T.

The specifications require a fast servo response despite constraints on a plant input and a plant output.

Defining the Plant Model

The first step in a design is to define the plant model.

% DC-motor with elastic shaft
%Parameters (MKS)
Lshaft=1.0;      				%Shaft length
dshaft=0.02;     				%Shaft diameter
shaftrho=7850;   				%Shaft specific weight (Carbon steel)
G=81500*1e6;     				%Modulus of rigidity
tauam=50*1e6;    				%Shear strength
Mmotor=100;      				%Rotor mass
Rmotor=.1;       				%Rotor radius
Jmotor=.5*Mmotor*Rmotor^2; 						%Rotor axial moment of inertia                      
Bmotor=0.1;      				%Rotor viscous friction coefficient (A CASO)
R=20;            				%Resistance of armature
Kt=10;           				%Motor constant
gear=20;         				%Gear ratio
Jload=50*Jmotor; 				%Load inertia
Bload=25;        				%Load viscous friction coefficient
Ip=pi/32*dshaft^4;               					%Polar momentum of shaft (circular) section
Kth=G*Ip/Lshaft;                					%Torsional rigidity (Torque/angle)
Vshaft=pi*(dshaft^2)/4*Lshaft;   						%Shaft volume
Mshaft=shaftrho*Vshaft;          						%Shaft mass
Jshaft=Mshaft*.5*(dshaft^2/4);   						%Shaft moment of inertia
Vmax=tauam*pi*dshaft^3/16; 						%Maximum admissible torque

%Input/State/Output continuous time form
AA=[0             1             0                 0;
    -Kth/JL       -Bload/JL     Kth/(gear*JL)     0;
    0             0             0                 1;
    Kth/(JM*gear) 0             -Kth/(JM*gear^2)  -(Bmotor+Kt^2/R)/JM];
Hyd=[1 0 0 0];
Hvd=[Kth 0 -Kth/gear 0];

% Define the LTI state-space model

Controller Design Using MPCTOOL

The servomechanism model is linear, so you can use the Model Predictive Control Toolbox™ design tool (mpctool) to configure a controller and test it.

    Note   To follow this example on your own system, first create the servomechanism model as explained in Servomechanism Controller. This defines the variable sys in your MATLAB® workspace.

Opening MPCTOOL and Importing a Model

To begin, open the design tool by typing the following at the MATLAB prompt:


Once the design tool has appeared, click the Import Plant button. The Plant Model Importer dialog box appears (see the following figure).

By default, the Import from option buttons are set to import from the MATLAB workspace, and the box at the upper right lists all LTI models defined there. In the following figure, sys is the only available model, and it is selected. The Properties area lists the selected model's key attributes.

Import Dialog Box with the Servomechanism Model Selected

Make sure your servomechanism model, sys, is selected. Then click the Import button. You won't be importing more models, so close the import dialog box.

Meanwhile, the model has loaded, and tables now appear in the design tool's main window (see the figure below). Note the previous diagram enumerates the model's input and output signals.

Design Tool After Importing the Plant Model

Specifying Signal Properties

It's essential to specify signal types before going on. By default, the design tool assumes all plant inputs are manipulated, which is correct in this case. But it also assumes all outputs are measured, which is not. Specify that the second output is unmeasured by clicking on the appropriate table cell and selecting the Unmeasured option.

You also have the option to change the default signal names (In1, Out1, Out2) to something more meaningful (e.g., V, ThetaL, T), enter descriptive information in the blank Description and Units columns, and specify a nominal initial value for each signal (the default is zero).

After you've entered all your changes, the design tool resembles the following figure.

Design Tool After Specifying Signal Properties

Navigation Using the Tree View

Now consider the design tool's left-hand frame. This tree is an ordered arrangement of nodes. Selecting (clicking) a node causes the corresponding view to appear in the right-hand frame. When the design tool starts, it creates a root node named MPC Design Taskand selects it, as in Design Tool After Importing the Plant Model.

The Plant models node is next in the hierarchy. Click on it to list the plant models being used in your design. (Each model name is editable.) The middle section displays the selected model's properties. There is also a space to enter notes describing the model's special features. Buttons allow you to import a new model or delete one you no longer need.

The next node is Controllers. You might see a + sign to its left, indicating that it contains subnodes. If so, click on the + sign to expand the tree (as shown in Design Tool After Importing the Plant Model). All the controllers in your design will appear here. By default, you have one: MPC1. In general, you might opt to design and test several alternatives.

Select Controllers to see a list of all controllers, similar to the Plant models view. The table columns show important controller settings: the plant model being used, the controller sampling period, and the prediction and control horizons. All are editable. For now, leave them at their default values.

The buttons on the Controllers view allow you to:

  • Import a controller designed previously and stored either in your workspace or in a MAT-file.

  • Export the selected controller to your workspace.

  • Create a New controller, which will be initialized to the Model Predictive Control Toolbox defaults.

  • Copy the selected controller to create a duplicate that you can modify.

  • Delete the selected controller.

Specifying Controller Properties

Select the MPC1 subnode. The main pane should change to the controller design.

If the selected Prediction model is continuous-time, as in this example, the Control interval (sampling period) defaults to 1. You need to change this to an application-appropriate value. Set it to 0.1 seconds (as shown in Controller Design View, Models and Horizons Pane). Leave the other values at their defaults for now.

Controller Design View, Models and Horizons Pane

Specifying Constraints

Next, click the Constraints tab. The view shown in Controller Design View, Constraints Pane appears. Enter the appropriate constraint values. Leaving a field blank implies that there is no constraint.

Controller Design View, Constraints Pane

In general, it's good practice to include all known manipulated variable constraints, but it's unwise to enter constraints on outputs unless they are an essential aspect of your application. The limit on applied torque is such a constraint, as are the limits on applied voltage. The angular position has physical limits but the controller shouldn't attempt to enforce them, so you should leave the corresponding fields blank (see Controller Design View, Constraints Pane).

The Max down rate should be nonpositive (or blank). It limits the amount a manipulated variable can decrease in a single control interval. Similarly, the Max up rate should be nonnegative. It limits the increasing rate. Leave both unconstrained (i.e., blank).

The shaded columns can't be edited. If you want to change this descriptive information, select the root node view and edit its tables. Such changes apply to all controllers in the design.

Weight Tuning

Next, click the Weight Tuning tab.

The weights specify trade-offs in the controller design. First consider the Output weights. The controller will try to minimize the deviation of each output from its setpoint or reference value. For each sampling instant in the prediction horizon, the controller multiplies predicted deviations for each output by the output's weight, squares the result, and sums over all sampling instants and all outputs. One of the controller's objectives is to minimize this sum, i.e., to provide good setpoint tracking. (See Optimization Problem for more details.)

Here, the angular position should track its setpoint, but the applied torque can vary, provided that it stays within the specified constraints. Therefore, set the torque's weight to zero, which tells the controller that setpoint tracking is unnecessary for this output.

Similarly, it's acceptable for the applied voltage to deviate from nominal (it must in order to change the angular position!). Its weight should be zero (the default for manipulated variables). On the other hand, it's probably undesirable for the controller to make drastic changes in the applied voltage. The Rate weight penalizes such changes. Use the default, 0.1.

When setting the rates, the relative magnitudes are more important than the absolute values, and you must account for differences in the measurement scales of each variable. For example, if a deviation of 0.1 units in variable A is just as important as a deviation of 100 units in variable B, variable A's weight must be 1000 times larger than that for variable B.

Controller Design View, Weight Tuning Pane

The tables allow you to weight individual variables. The slider at the top adjusts an overall trade-off between controller aggressiveness and setpoint tracking. Moving the slider to the left places a larger overall penalty on manipulated variable changes, making them smaller. This usually increases controller robustness, but setpoint tracking becomes more sluggish.

The Estimation (Advanced) tab allows you to adjust the controller's response to unmeasured disturbances (not used in this example).

Defining a Simulation Scenario

If you haven't already done so, expand the Scenarios node to show the Scenario1 subnode (see Design Tool After Importing the Plant Model). Select Scenario1.

A scenario is a set of simulation conditions. As shown in Simulation Settings View for "Scenario1", you choose the controller to be used (from among controllers in your design), the model to act as the plant, and the simulation duration. You must also specify all setpoints and disturbance inputs.

Duplicate the settings shown in Simulation Settings View for "Scenario1", which will test the controller's servo response to a unit-step change in the angular position setpoint. All other inputs are being held constant at their nominal values.

Simulation Settings View for "Scenario1"

    Note   The ThetaL and V unmeasured disturbances allow you to simulate additive disturbances to these variables. By default, these disturbances are turned off, i.e., zero.

The Look ahead option designates that all future setpoint variations are known. In that case, the controller can adjust the manipulated variable(s) in advance to improve setpoint tracking. This would be unusual in practice, and is not being used here.

Running a Simulation

Once you're ready to run the scenario, click the Simulate button or the green arrow on the toolbar.

    Note   The green arrow tool is available from any view once you've defined at least one scenario. It runs the active scenario, i.e., the one most recently selected or modified.

We obtain the results shown in Response to Unit Step in the Angular Position Setpoint. The blue curves are the output signals, and the gray curves are the corresponding setpoints. The response is very sluggish, and hasn't settled within the 30-second simulation period.

Response to Unit Step in the Angular Position Setpoint

    Note   The window shown in Response to Unit Step in the Angular Position Setpoint provides many of the customization features available in Control System Toolbox™ ltiview and sisotool displays. Try clicking a curve to obtain the numerical characteristics of the selected point, or right-clicking in the plot area to open a customization menu.

The corresponding applied voltage adjustments appear in a separate window and are also very sluggish.

On the positive side, the applied torque stays well within bounds, as does the applied voltage.

Retuning to Achieve a Faster Servo Response

To obtain a more rapid servo response, navigate to the MPC1 Weight Tuning pane (select the MPC1 node to get the controller design view, then click the Weight Tuning tab) and move the slider all the way to the right. Then click the green arrow in the toolbar. Your results should now resemble Faster Servo Response and Manipulated Variable Adjustments.

The angular position now settles within 10 seconds following the step. The torque approaches its lower limit, but doesn't exceed it (see Faster Servo Response) and the applied voltage stays within its limits (see Manipulated Variable Adjustments).

Faster Servo Response

Manipulated Variable Adjustments

Modifying the Scenario

Finally, increase the step size to π radians (select the Scenario1 node and edit the tabular value).

As shown in Servo Response for Step Increase of π Radians and Voltage Adjustments, the servo response is essentially as good as before, and we avoid exceeding the torque constraint at –78.5 Nm, even though the applied voltage is saturated for about 2.5 seconds (see Voltage Adjustments).

Servo Response for Step Increase of π Radians

Voltage Adjustments

Saving Your Work

Once you're satisfied with a controller's performance, you can export it to the workspace, for use in a Simulink® block diagram or for analysis (or you can save it in a MAT-file).

To export a controller, right-click its node and select Export from the resulting menu (or select the Controllers node, select the controller in the list, and click the Export button). A dialog box like that shown in Exporting a Controller to the Workspace will appear.

The Controller source is the design from which you want to extract a controller. There's only one in this example, but in general you might be working on several simultaneously. The Controller to export choice defaults to the controller most recently selected. Again, there's no choice in this case, but there could be in general. The Name to assign edit box allows you to rename the exported controller. (This will not change its name in the design tool.)

Exporting a Controller to the Workspace

    Note   When you exit the design tool, you will be prompted to save the entire design in a MAT file. This allows you to reload it later using the File/Load menu option or the Load icon on the toolbar.

Using Model Predictive Control Toolbox Commands

Once you've become familiar with the toolbox, you may find it more convenient to build a controller and run a simulation using commands.

For example, suppose that you've defined the model as discussed in Defining the Plant Model. Consider the following command sequence:

ManipulatedVariables = struct('Min', -220, 'Max', 220, 'Units', 'V');
OutputVariables(1) = struct('Min', -Inf, 'Max', Inf, 'Units', 'rad');
OutputVariables(2) = struct('Min', -78.5, 'Max', 78.5, 'Units', 'Nm');
Weights = struct('Input', 0, 'InputRate', 0.05, 'Output', [10 0]);
Model.Plant = sys;
Model.Plant.OutputGroup = {[1], 'Measured' ; [2], 'Unmeasured'};  
Ts = 0.1;
PredictionHorizon = 10;
ControlHorizon = 2;

This creates several structure variables. For example, ManipulatedVariables defines the display units and constraints for the applied voltage (the manipulated plant input). Weights defines the tuning weights shown in Controller Design View, Weight Tuning Pane (but the numerical values used here provide better performance). Model designates the plant model (stored in sys, which we defined earlier). The code also sets the Model.Plant.OutputGroup property to designate the second output as unmeasured.

Constructing an MPC Object

Use the mpc command to construct an MPC object called ServoMPC:

ServoMPC = mpc(Model, Ts, PredictionHorizon, ControlHorizon);

Like the LTI objects used to define linear, time-invariant dynamic models, an MPC object contains a complete definition of a controller.

Setting, Getting, and Displaying Object Properties

Once you've constructed an MPC object, you can change its properties as you would for other objects. For example, to change the prediction horizon, you could use one of the following commands:

ServoMPC.PredictionHorizon = 12;
set(ServoMPC, 'PredictionHorizon', 12);

For a listing of all the object's properties, you could type:


To access a particular property (e.g., the control horizon), you could type either:

M = get(ServoMPC, 'ControlHorizon');
M = ServoMPC.ControlHorizon;

You can also set multiple properties simultaneously.

Set the following properties before continuing with this example:

set(ServoMPC, 'Weights', Weights, ...
	'ManipulatedVariables', ManipulatedVariables, ...
	'OutputVariables', OutputVariables);

Typing the name of an object without a terminating semicolon generates a formatted display of the object's properties. You can achieve the same effect using the display command:


Running a Simulation

The sim command performs a linear simulation. For example, the following code sequence defines constant setpoints for the two outputs, then runs a simulation:

TimeSteps = round(10/Ts);
r = [pi 0];
[y, t, u] = sim(ServoMPC, TimeSteps, r);

By default, the model used to design the controller (stored in ServoMPC) also represents the plant.

The sim command saves the output and manipulated variable sequences in variables y and u. For example,

plot(t, y(:,1), [0 t(end)], pi*[1 1])
title('Angular Position (radians)');
plot(t, y(:,2), [0 t(end)], [-78.5 -78.5])
title('Torque (nM)')
stairs(t, u)
title('Applied Voltage (volts)')
xlabel('Elapsed Time (seconds)')

produces the custom plot shown in Plotting the Output of the sim Command. The plot includes the angular position's setpoint. The servo response settles within 5 seconds with no overshoot. It also displays the torque's lower bound, which becomes active after about 0.9 seconds but isn't exceeded. The applied voltage saturates between about 0.5 and 2.8 seconds, but the controller performs well despite this.

Plotting the Output of the sim Command

Using MPC Tools in Simulink

Block Diagram for the Servomechanism Example is a Simulink block diagram for the servomechanism example. Most of the blocks are from the standard Simulink library. There are two exceptions:

  • Servomechanism Model is an LTI System block from the Control System Toolbox library. The LTI model sys (which must exist in the workspace) defines its dynamic behavior. To review how to create this model, see Defining the Plant Model.

  • MPC Controller is from the MPC Blocks library. Model Predictive Control Toolbox Simulink Block Dialog Box shows the dialog box obtained by double-clicking this block. You need to supply an MPC object, and ServoMPC is being used here. It must be in the workspace before you run a simulation. The Design button opens the design tool, which allows you to create or modify the object. To review how to use commands to create ServoMPC, see Constructing an MPC Object.

    Block Diagram for the Servomechanism Example

    Model Predictive Control Toolbox Simulink Block Dialog Box

The key features of the diagram are as follows:

  • The MPC Controller output is the plant input. The Voltage Scope block plots it (yellow curve). Minimum and maximum voltage values are shown as magenta and cyan curves.

  • The plant output is a vector signal. The first element is the measured angular position. The second is the unmeasured torque. A Demux block separates them. The angular position feeds back to the controller and plots on the Angle scope (yellow curve). The torque plots on the Torque scope (with its lower and upper bounds).

  • The position setpoint varies sinusoidally with amplitude π radians and frequency 0.4 rad/s. It also appears on the Angle scope (magenta curve).

The angular position tracks the sinusoidal setpoint variations well despite saturation of the applied voltage. The setpoint variations are more gradual than the step changes used previously, so the torque stays well within its bounds.

Was this topic helpful?