# The Digital Motion Control Demo

**A practical lesson in Model-Based Design.**

- Prepared by: Paul Lambrechts, October, 2007
- Copyright 2007, The MathWorks, Inc.
**Note:**This demo is originally prepared with**R2007b**

If you have the Digital Motion Control hardware available, you should refer to the user manual. This script is intended for doing the demo without the actual hardware. If required, saved data is used.

**Required Products:** MATLAB®; Simulink®; Stateflow®; Control System Toolbox™; Signal Processing Toolbox™

**Recommended Products:** Simulink® 3D Animation™; System Identification Toolbox™; Simulink® Design Optimization™; Simulink® Control Design™

**Additionally Demonstrated Products:** Simscape™; SimMechanics™; SimDriveline™; Simulink® Verification and Validation™

- Unpack zipfile in any work directory: say
`c:\demo` - Start the demo with script
`StartDemo` **Tip:**create a shortcut in the MATLAB Shortcuts bar with command:`cd('c:\demo'); StartDemo`

- A web browser will be opened showing you the steps of the demo.

**Never save an opened Simulink model**

## Contents

## 1. Problem Formulation

Suppose that you are looking at a motion system that is a part of some production machine. It is intended to move a certain load (a gripper, a tool, a nozzle or anything else that you can imagine) from one position to another and back again. Typically for a production machine, this should be done in a given ‘production cycle’ that has to be completed for each product, or number of products, to be created.

Now the question is “can we increase the production speed of the machine; and can we do that without loss in accuracy, or even increased accuracy, as this determines the quality of the product.”

Our job is to design a new controller for this particular motion system, which allows the speed to increase from 150 to 250 rad/s and the acceleration from 2000 to 5000 rad/s2; the required motion is obtained when stepping from 0 to 100 radians and back again.

To investigate this, we have a model of the motion system that we can control using MATLAB and Simulink software.

- Click
**Open Simulink Model for Problem Formulation**to open the model. The ‘Plant Model’ is the model of the device, the ‘Tunable Controller’ implements the currently used feedback controller and the ‘Reference and Feedforward’ block provides the required motion profile. - Click the
**Play**button to start the simulation: a Virtual Reality scene will be opened, as well as an interface that allows you to operate the model. You can change for instance the values of**Stepsize,****Max. Velocity,**and**Max Acceleration.** - Look at the response in the
**pos. error**scope (rescale with the binoculars:) it shows the step reference and error response. Now the error is much too big; you can change the**Max. Velocity**and**Max Acceleration**to 150 and 2000, and the settling time to 2 seconds (the ‘old’ values, you can also use the**Old Spec.**button:) the response is now ‘just acceptable.’ **Stop**the simulation and Click**Show Measured Response**to look at the response in a MATLAB figure and further analyse the data. The new design should be able to follow the faster trajectory with higher accuracy.

## 2. Black Box Modeling: Transfer Function measurement

- Click
**Transfer Function measurement**to open the model - You are going to estimate the transfer function of the
**Virtual Black Box**by applying a test signal (band limited white noise generated in**Reference and Feedforward**block) to the control loop with a preliminary controller (implemented in the**Tunable Controller**block). - Do a simulation in normal mode;
**Retrieve Data**to obtain the generated signals and**Plot Results**to get the transfer function measurement.**Add model**to compare with the actual model.

You can also do system identification on the simulated results.

- Click
**System Identification**to open the GUI. - First
**Import data**: instead of using time domain data we will now use the frequency domain data determined in the previous step: select**Freq. domain data**and**Freq.Function (Complex)**. - Enter
**Freq.Func.**`Hpm`,**Frequency**`F`,**Sampling interval**`Ts`->**Import** - Click
**Frequency function**to show data: it is the transfer function measurement done before. - This data is now put in as
**Working Data**and also as**Validation Data**. - Now we are going to estimate a parametric model: choose
**Estimate -->**, then**Linear parametric models**, then**State Space**, click**Order Selection**and**Estimate**: you can see that the first order is most important but apparently the first four are significant: click on fourth bar and**Insert**to do the fourth order estimation. - Show result in
**Model output**: the peak is well estimated. You can sometimes improve by putting focus on a passband between 10 and 500 rad/s (**Focus**->**Filter**). - Pull result to
**LTIviewer**: the step response is sometimes unstable (the open loop system has two poles at zero due to the double integral). Right click to show bode plot: the peak on the left is wrong: it is well outside the measured frequency range and therefore not estimated correctly: within the measured frequency range the result is good (zoom in if you like). - From the
**LTIviewer,**export the model to MATLAB workspace (**File**-->**Export...**) and name it`sys`: this is no longer a measurement but an estimated state space model of fourth order (you may display`sys`in command window). This is a Linear Time Invariant model, or LTI model. - This means we can simulate it to investigate its behavior: click
**Open Simulink Model to show Identified Model**. We are going to apply a simple step as reference, double click**Display Scopes**and press play button. You can also start with the black box model and use**Block Choice**to change the plant to**Identified Model**: then also change the**Reference and Feedforward**block to**Simple Step**and set the simulation time to 2 seconds.

## 3. First Principles modelling: Differential Equations

- Click
**Differential Equations**display the scopes and run. - Open the
**Plant Model**and investigate the**Block Choice**options of the**Motion System**block. - The
**Mathematical Model**is set up from the diagram. From first principles (Newton's law) the given equations can be set up and transformed into state-space form: the doc block in the motion system block gives the steps. - In the end, users of the model will only be interested in changing the parameters: change model to
**Masked Math**and double click to show parameter definition GUI. Run model again to show same response. - Another approach would be to set up the system equations as a block diagram: block choice
**Simulink Model**. Again same response. - Note that even in this fairly simple case this quickly becomes complex: to facilitate this we have physical modeling tools that allow you to set up a model without actually having to derive and implement the equations.

## 4. First Principles modelling: Physical Modeling and Visualization

You will need the Simscape and SimMechanics software for the SimMechanics option to run and the Simscape, SimDriveline and Simulink 3D Animation software for the SimDriveline option to run. There is also a 'Simscape only' option, also using the Simulink 3D Animation software for visualization.

- You may click the link or use the model from step 3
- Open
**Plant Model**and use**Block Choice**option of the**Motion System**block to switch to the**SimMechanics Model**. Look at it's response (play around with visualization). Slow speed is due to the visualization (close machine during simulation to see effect). - Open the model and investigate correspondence between diagram and blocks.
- For more complex systems it may be convenient to specify the geometry of the system by means of CAD software: for instance from the SolidWorks® software it is possible to transfer a design to a SimMechanics model. If you have SolidWorks software, you can open the part files in directory 'SolidWorks.' See help on function
`import_physmod`: you can do`import_physmod('setup.xml')`. - Another option in this case is to use SimDriveline (because the motion system is in fact a simple driveline system, only considered in one rotational degree of freedom). Block choose
**SimDriveline Model**, open it and see correspondence between the diagram and the blocks again. - Now the SimDriveline software does not have a 'built in' visualization like the SimMechanics software (The SimMechanics visualization is primarily intended to verify the geometry of 3D systems: for the 1D SimDriveline software this is not required). Therefore a Virtual Reality scene is added to animate the motion system (using Simulink 3D Animation and based on the CAD drawings in the SolidWorks software).
- Run the model: if necessary, switch to
**close**in the VR scene. - If you like, you can also look at the
**Simscape Model**. - Now this is a good point to introduce a more realistic reference signal than a simple step: by changing the
**Reference and Feedforward**block with**Block Choice**to**Rigid Body P2P**or**Fourth order P2P**you can implement a motion profile that could be found in a real application. You need the Stateflow software for this; also do not use the versions with the GUI as they do not work together with physical models. Run the model and rescale the scopes to see the complete response. - Especially if you enlarge the VR scene you can now see the resonance due to the flexible shaft at the end of the move.

## 5. Parameter Estimation: Physical parameters from measurements

- Now suppose we have a prototype of the new system: a question may be: 'what is the exact stiffness and damping of the shaft'. This brings us to parameter estimation: trying to estimate such physical parameters from measurements.
- Click
**Physical parameters from measurements**. It is again the same model. If you run it, the response will be given with an initial parameter choice: this response will be different from an actual measurement. - Just to show you how it works the 'measurement data' has been taken from an earlier simulation and perturbed with some noise. We are going to estimate the actual values of the stiffness and damping of the flexible shaft from this data to see if they are estimated correctly.
- Open
**Parameter Estimation**in the Tools menu. - Make a new data set in
**Transient Data**: Enter Input Data`Tin`and`Rin`both with sampling time`Ts`; enter output data`errm`with`Ts`. **Plot Data**(errm): this is the error response during the point-to-point motion and back; see that there is some measurement noise (zoom in)- Goto
**Variables**and**Add**`k`and`b12`. Notice the possibility to specify bounds: change minimum value to 0 (stiffness and damping are by definition positive). Note: estimation also works with`-Inf`. - Add new estimation, select
**New Data**. - In Parameters: select and highlight both, press
**Use Value as Initial Guess**and**Save as Default Settings**(to do same estimation more than once). - In Estimation: check
**Show progress views**and**Start**. - When plots appear, stop estimation, rearrange plots to make them both visible and zoom in on
**Measured vs. Simulated**.**Start**again and examine parameter trajectories, iteration steps cost function etc. - If desired: display scopes to see intermediate evaluations.
- After Estimation, show parameters:
`b12`should be close to 2e-7,`k`should be close to 0.013 - Because Parameter Estimation uses simulations to optimize the unknown parameters, it can deal with non-linear models.
- Close
**Control and Estimation Tools Manager**

## 6. Control Design

- Click
**Open Simulink model to do Control Design**under**Control Design**. - Open
**Tunable Controller**, examine structure (feedforward path, error calculation, feedback controller). - Right-click feedback controller and go to
**Requirements**; select 'Feedback Controller Structure;' A Word document opens and automatically jumps to the section about the controller structure, showing this and other requirements for the new controller. - The new controller will consist of a combination of a lead-lag filter (to stabilize the motion system) and a notch filter (to suppress the resonance peak).
- This structure is well known for motion control and can be used effectively for almost any motion control problem.
- Double-click the Simulink icon in the document: you are linked back to the model and the appropriate block is highlighted.
- Select feedback controller
**Parameterized Discrete**with**Block Choice**: this contains the desired structure and parameterization. - Examine the parameters: the gain
`k`, the lead-lag has a zero at frequency`z`and a pole at frequency`p`. the notch has a (complex conjugate) zero-pair at frequency`nz`with relative damping`bz`and a (complex conjugate) pole-pair at frequency`np`with relative damping`bp`. - The blocks Leadlag and Notch are automatically implemented in discrete time: the transformation method is indicated in the blocks.
- Close diagram and double click feedback controller to see parameters.

The control design problem is now 'simplified' to choosing the correct parameters for this structure: this can be done using the Simulink Control Design software.

- Open
**Compensator Design**: it is the same interface as used for Parameter Estimation, but now we have a**Simulink Compensator Design Task**. - First step is to
**Select Blocks**to tune: click the plus sign next to**Tunable Controller**, select**Feedback Controller**, check the box next to**Parametrized Discrete**and click**OK**. Note: it works with the custom configuration function**scdleadlagnotch**. - Next in
**Closed-Loop Signals**you can select the signals you are interested in (you may want to deselect**Feedforward**to simplify things). You can also specify**Operating Points**, but in this case it is not relevant because the system is not operating point dependent. - Click
**Tune Blocks**to start the Design Configuration Wizard; click**Next >**. - Select Plot Type
**Open-Loop Bode**and click**Next >**. **Add Responses**,**Open Loop Response**,**OK**.- Analysis plots:
**Step**and**Nyquist**. - Select
**Closed-Loop from Reference to Pos/Measured Position**for Plot 1 (Step) and**Open-Loop at outport 1 of Feedback Controller Parameterized Discrete**for Plot 2 (Nyquist). **Finish**.

- Rearrange figures, zoom in Nyquist plot on (-1,0), zoom in SISOtool on area with poles and zeros (switch of zoom tool).
- You see that the step response is unstable: usual first step is to reduce gain until stable: drag down Bode magnitude plot (slowly: let analysis plots update). When peak passes zero dB the step response is stable (also: Nyquist plot passes (-1,0) point).
- Next use notch zeros (30 Hz) to suppress peak (takes some practice: zoom in on peak for easier adjustments). Note that 'circles' in the Nyquist plot disappear.
- Next increase gain again until step response gets bad: to improve, grab leadlag pole at 40 Hz and move to 75-80 Hz.
- Finally adjust gain until magnitude passes 0dB at about 20 Hz: this is a measure for the obtained bandwidth of the control system.
- Note: Gain Margin about 8dB, Phase Margin about 45 deg: nice robust design.

- Now go to
**Compensator Editor**: examine numerical values and change such that gain, damping and frequency are nicely rounded to at most 3 or 4 digits (don't forget the gain). - Now open the dialog of the
**Feedback Controller**block in the Simulink window and press**Update Simulink Block Parameters**(to see that they are indeed updated). To be able to change the sampling time later on replace the numerical value (0.002) with`Ts`and press OK. - Display Scopes and run simulation: the step response is different from the analysis plot due to saturation in the power amplifier. This shows the importance of verifying by simulation when using a linear control design method!

- To prove: use switch to bypass saturation block in
**Power Amplifier**block and run again: remaining difference is due to discrete time implementation (while design is in continuous time). You can show this by changing`Ts`to 0.0002 (5kHz): now the response is similar to the calculated step response in the LTI viewer. - Show torques scope: big spike is due to step reference which is not realistic in practice; instead use
**Rigid Body P2P**or**Fourth Order P2P**: note that torques are limited in spite of much larger move. - Change saturation limits and sampling time back to original values: error does not significantly increase.
**Conclusion**: for realistic reference trajectories the controller has good performance.

## 7. Rapid Prototyping

Click **Open Simulink Model to do Rapid Prototyping**. If it is detected that no hardware is available, the Rapid Prototyping interface is not loaded, but the Plant Model is used instead. During simulation the VR scene will be opened: if necessary, switch to **close**. Now it is possible to test the controller and the Reference and Feedforward GUI on the model.

**Note:** a default feedback controller is automatically activated; to use the controller designed in the previous section, change the parameters of the appropriate feedback controller in the library DMC_lib.

## Notice

MATLAB and Simulink are registered trademarks of The MathWorks, Inc. See www.mathworks.com/trademarks for a list of additional trademarks. Other product or brand names may be trademarks or registered trademarks of their respective holders.