Guy and Seth on Simulink

May 20th, 2013

Configuring Models for Linear Analysis

One of the benefits of Model-Based Design is the ability to perform linear analysis on your non-linear model and design controllers using classical controls techniques. In R2013a, configuring your model for linear analysis with Simulink Control Design have been greatly improved. Let's take a look at how useful Linear Analysis Points are when performing control related tasks in Simulink.

Why using Linear Analysis Points?

Those doing linear analysis with Simulink for a long time are probably familiar with the linmod function. With linmod, the inputs and outputs of the linearization are the root-level Inport and Outport blocks of your model. This means that your model needs to be built in a specific way to accommodate linear analysis.

With Simulink Control Design, you can use Linear Analysis Points to specify which portion of a model to linearize.

To see all the advantages of Simulink Control Design compared to linmod, I recommend going through this documentation page: Linearization Using Simulink Control Design Versus Simulink.

Specifying Linear Analysis Points in a model

Let's take this model as example.

Example model to be linearized

To design a controller, the first thing I am interested in is linearizing the plant. For that, I can right click on the signals entering and exiting the plant, and mark them as Open-loop Input and Open-loop Output. For those already familiar with Simulink Control Design, notice the new improved menu in R2013a.

Linear Analysis Points Menu

Once this is done, you will see markers in your model for the marked signals.

model With Linear Analysis Points

Specifying Multiple sets of Linear Analysis Points

When developing controllers for your model, you will very likely need to accomplish linear analysis multiple times for different parts of your model, open and closed loop, with different inputs and outputs. For that, you can click on Create new linearization I/Os... in the Linear Analysis Tool.

Create new linearization I/Os...

This will launch a window where you can define multiple sets of points for your different tasks.

Creating new linearization I/Os

Once you are done, you can select the set of points to be used for linearization.

Using existing linear analysis points

Now it's your turn

For those familiar with the earlier version of this menu, I recommend looking at the R2013a release notes to find a table describing the mapping between the previous and current Linear Analysis Points menu. Hopefully, this new menu will help avoid confusion when specifying linear analysis points, especially with the open and closed loop concept.

If you prefer, all the above is also available from the command line with functions like linio, getlinio, and setlinio.

Give that a try and let us know what you think by leaving a comment here.

May 10th, 2013

Sum Block: Round or Rectangular?

Working in technical support, I see a lot of Simulink models from users. I have realized that many users do not know how to, or do not take the time to configure the ports of the Sum block.

For example, when I see things like this, it makes my eyes hurt a little:

Unusual configurations of the Sum block

Here are a few tips to format the Sum block to make your models easier to understand.

Round Sum block

When you drag the Sum block from the Simulink Library Browser, its Icon Shape is set to Round, and it has one input port on the left and one on the bottom:

Default configuration of the Sum block

When the Sum block Icon Shape is set to Round, the ports are spread evenly from top to bottom and the vertical bar "|" can be used to skip one position. For example, if we want to add a port on top of the block, we can modify the list of signs:

3 ports configuration of the Sum block

Rectangular Sum block

If you change the Icon Shape property of the default Sum block to Rectangular, the block will look like the following:

Rectangular configuration of the Sum block

Personally, I can not think of a good reason for skipping a port in Rectangular shape. So I almost always remove the "|" when I change the shape to Rectangular.

Rectangular configuration of the Sum block

Sum of Elements

One way I like to use the Sum block is to sum all the elements of a vector or matrix:

Sum of elements configuration of the Sum block

For matrices, the Sum block can also be configured to Sum only over one specific dimension:

Sum of elements configuration of the Sum block

Round or Rectangular?

One question remains: When should the Sum block be Round and when should it be Rectangular?

There is no absolute rule, but personally I like to use the Rectangular shape when implementing equations that flow from left to right, without obvious feedback. For example:

When to use configuration of the Sum block

I keep the Round shape for when I want to make it obvious that there is a feedback involved:

When to use Round configuration of the Sum block

Now it's your turn

Please share with us if you have rules or guidelines on the format of your blocks by leaving a comment here.

May 3rd, 2013

Comparing Runs using Simulation Data Inspector

Do you use the Simulation Data Inspector? Here is an example where it saved me a lot of debugging time.

Simulation Accuracy

I recently had to validate system behavior and analyze numerical accuracy of a model. Making small modifications in one part of the model was leading to unexpectedly large differences at the outputs. Since the model was very large, I thought it would be painful to insert Scopes or To Workspace blocks in the model to try identifying the source of the problem.

I found out that the Simulation Data Inspector can be very useful to compare simulation results without adding blocks to your model and without writing any scripts. Let's see how this work!

Logging Signals

The first step is to configure signals for logging. I like to use the Model Explorer for that. It is significantly faster than right-clicking on the signal lines one by one. Here are a few tips to configure the Model Explorer with the goal of controlling signal logging.

Configuring signals for logging using the model explorer

Also, ensure that signal logging is enabled in the model configuration.

Enabling logging

Record & Inspect Simulation Output

In your model, click on the Record button.

Record & Inspect Simulation Output

When the simulation is completed, open the Simulation Data Inspector using the link that pops up.

Launching Simulation Data Inspector

Compare Runs

Make some changes to your model and simulate it again. In the Simulation Data Inspector, go to the Compare Runs Tab, select your 2 runs and click Compare.

Using the absolute tolerance I specified, the Simulation data Inspector helped me to quickly identify where the divergence appear in my model.

Comparing Runs in Simulation Data Inspector

Now it's your turn

Give a look and the Validate System Behavior section of the documentation to learn more about the Simulation Data Inspector and let us know if it helps your workflow by leaving a comment here.

April 26th, 2013

Zero-Crossing Detection… what are your options?

When using Simulink variable-step solvers, zero-crossing detection is very useful to capture events accurately. However for some equations, configuring zero-crossing detection can be challenging.

Last week I received the following question and example model:

In the attached model, I implemented a basic bang-bang controller for a plow. Using a Sign block, I generate a 1 for the plow to go up, -1 to go down and 0 to stop. The problem is that the plow never seems to stabilize around zero. Can you help me understand why?

Here is an image of the model:

Bang Bang Controller for a plow

Nonadaptive zero-crossing detection

With the default settings, this model errors out as soon as we try to give a non-zero command with the following error:

At time 1.0000000000236877, simulation hits (1000) consecutive zero crossings. Consecutive zero crossings will slow down the simulation or cause the simulation to hang. To continue the simulation, you may 1) Try using Adaptive zero-crossing detection algorithm or 2) Disable the zero crossing of the blocks shown in the following table.
--------------------------------------------------------------------------------
Number of consecutive zero-crossings : 1000
Zero-crossing signal name : Input
Block type : Signum
Block path : 'myPlowController/Sign'
--------------------------------------------------------------------------------
You can turn off this message by using the MATLAB command:
set_param('myPlowController','MaxConsecutiveZCsMsg','none');

This error is relatively simple to understand by looking at the ideal plant model (an Integrator block) and the switching logic. If the plow position is slightly negative, the controller makes it move upward, leading to a positive error. The controller sees this positive error, makes the plow go down, bringing us back to our original state .

With zero-crossing detection enabled for the Sign block, Simulink will detect that we crossed zero and try to reduce its step-size to capture this transition accurately. But here, reducing the step size will not help. The step size can be a small as possible, a small negative error will always lead to a jump on the positive side, and vice-versa.

Let's try the suggestions offered by the error message. What suggestions? If you didn't read the error message, go back and read it now.

Suggestion 1: Adaptive zero-crossing detection

In the solver section of the model configuration, we can try selecting adaptive zero-crossing detection. This will dynamically activate and deactivate zero-crossing bracketing, helping with models that exhibit strong chattering.

Adaptive zero-crossing detection

With this setting the simulation completes, but the variable step solver takes way too many steps when it is not needed, and the position error is too large.

Simulation results with adaptive zero-crossing detection

The reason is that the adaptive algorithm encountered multiple consecutive zero-crossings for the Sign block and decided to disable zero-crossing detection for this block. Once this is done, the solver takes larger steps and gives inaccurate results.

Let's try suggestion 2 from the error message.

Suggestion 2: Disabling zero-crossing

The second suggestion from the error message is to disable zero-crossing detection for the problematic block.

Sign block with disabled ZC

In this case, the tracking is significantly better because the solver uses the state of the integrator to limit its step size, but we see a lot of switching happening when the plow desired height is constant.

results with zero-crossing disabled

The main problem here is that it is impossible for the Simulink engine to stop exactly on the zero value of the Sign block with this system. With the equations involved, Simulink can take very small steps around zero, but will not stop exactly on it. This not what the Sign block is designed to do.

Possible solutions

If we want a system that can be simulated efficiently using a variable step solver, we have to modify the equations. If we want to keep the plant as it is, we need a controller with a logic that will stop when the error is within a certain range around zero. For example, we could use a Stateflow chart or a block with hysteresis like the Relay block:

Controller with dead zone

In this case, the plow stops moving when the command is fixed and the zero-crossing detection helps ensure that the solver takes appropriate steps when needed.

Results of the Controller with dead zone

Now it's your turn

If you have some interesting plowing or zero-crossing stories to share, leave a comment here

April 21st, 2013

Implementing a PID Controller on an Arduino Board

This week my colleague Pravallika is back to continue her motor control story!

Pravallikota Vinnakota, guest blogger

In my previous post, we saw how to estimate continuous transfer functions with System Identification Toolbox. We estimated the following transfer function for a simple DC Motor using tfest:

Transfer function identified from a DC Motor

For this transfer function, we designed the following controller using pidtune:

Controller generated by pidtune

We will now implement the controller on the Arduino Uno and see how the DC motor fares with this controller. To deploy the controller on the hardware, we will use Simulink’s capability to generate an executable and run it on selected hardware.

Deploying controller to the Arduino board

You probably noticed that the controller shown above is in a continuous form. To use it on our target, the first thing to do is to discretize it using the c2d function:

Discretizing the controller generated by pidtune

Then we grab the PID block from the Simulink Library and configure it.

PID block configuration

To keep the PID controller’s output within the limits of the hardware, we go to the PID Advanced tab and enable output saturation along with anti-windup protection.

Advanced PID block configuration

To test the controller on the hardware, we created a Simulink model using blocks from the Arduino Support Package.

As you can see, we receive the desired motor position from the serial port and compare it to the measured position from the Analog Input. The position error goes through the PID block which generates a voltage to be sent to the motor. We also send the measured position through the serial port.

Controller model to be used on the Arduino board

Hardware response

We ran the model on the target, sent it some commands and logged the data transmitted through the serial port. Here is what it looks like:

Data logged from our controller

So, it does a pretty good job of tracking the reference signal. When we compare the response from the hardware to that of the simulation, we observe that they are very close! The System Identification Toolbox model is quite good.

Now it is your turn

How are you designing controllers when a system is difficult to model? Have you tried the Run on Target Hardware capability in Simulink to run your models on the supported boards? Let us know by leaving a comment here.

April 12th, 2013

Creating Driver Blocks for Arduino, Lego, and other targets

As you may know, it is easy to run Simulink models on a set of supported target hardware. This has been possible since R2012a.

Even if we add more targets and support more features for each target with every new release, it is still possible that you will need a driver that is not included in the Simulink support package. If you desperately need a driver for your hardware, you can always build it yourself.

Let's see how this works using an example from a LEGO NXT project I worked on.

The LEGO Light Sensor

The LEGO NXT kit ships with a Light Sensor including a red LED that can be turned on or off. In the Simulink support package, you can control the light from a checkbox parameter in the block dialog.

Dialog of the LEGO Light Sensor driver block

For our project, we used this sensor to make a line following robot. To make our algorithm more robust, we thought it would be interesting to turn the light on and off while tracking the line, to actively filter out the ambient light.

Step 1: Determine the code to be generated for your driver block

In the LEGO MINDSTORMS NXT Support from Simulink, you can find many small examples showing how the robot can be programmed in C. By default, they are located in C:\MATLAB\SupportPackages\R2013a\nxtOSEK\samples_c. In one of those example, I found a function initializing the robot that looked like:

Example code used to program the NXT brick in C

The function ecrobot_set_light_sensor_active is exactly what I need to generate from my driver block. I also figured that a corresponding function ecrobot_set_light_sensor_inactive exists to turn the light off, and I found that those functions are declared in a file named ecrobot_interface.h.

Step 2 - Create an S-Function

Here you have 2 options to create the S-Function

Step 2 - Option 1: S-Function Builder Block

My colleague Giampiero Campa published a very good submission on MATLAB Central titled Device Drivers showing how to use the S-Function Builder block to include the code you found during step 1 in your model.

His submission contains detailed procedures and screen captures to guide you through the process step-by-step. If you are intimidated by writing an S-function, I recommend using his S-Function Builder technique.

Step 2 - Option 2: Writing an S-Function and a TLC file

If you are like me and want to understand the magic that is happening when you click build in the S-Function Builder block, this second option is for you.

First, we need to realize that unless you model the interaction of the sensor/actuator with the environment, in simulation, driver blocks typically do nothing. All blocks must specify the number of ports and parameters, and their dimensions, even if they do nothing. In my case, I created an s-function with 1 input port of dimension 1 to specify if the light should be on or off. Here is the entire code for my s-function.

S-Function to control the light of the LEGO light sensor

To specify the code generated for your block, you need to use the Target Language Compiler.

Concretely, this means that you need to write a TLC file for your block. For that, I recommend starting with examples from sfundemos.

For this example we need our TLC to do two things: Tell the compiler to include ecrobot_interface.h, and call ecrobot_set_light_sensor_active and ecrobot_set_light_sensor_inactive. Here is what it looks like.

TLC file to control the light of the LEGO light sensor

Note that I used BlockTypeSetup to include the header file, and Outputs to define what the block output method should be.

Now it's your turn

Download this LEGO example or a similar example for the Arduino target and begin creating your own driver blocks!

If you develop custom drivers for the Simulink Target Hardware, share them on MATLAB Central and let us know by leaving a comment here.

April 5th, 2013

To Latch or not to Latch?

Yesterday I explained to a colleague the effect of the Inport block option Latch input for feedback signals of function-call subsystem outputs . I thought it would be interesting to share here.

The Problem

In the following model, inside the calib function-call subsystem, the Count signal is connected to a Unit Delay block.

Model with a Function-Call subsystem involved in a direct feedback loop

When logging data, we can see that the input and output of the Unit Delay are identical, as if the signal was not delayed!

Input and output of the Unit Delay are equal

Even though this might seem strange, this behavior is expected. Let's see why.

The simulation loop

To understand what is happening, you first need to be familiar with the order into which the block methods are executed within the simulation loop. To really understand the simulation loop I recommend the following documentation pages:

In our case, we have a model that is fixed-step and discrete, so the simulation loop is very simple and looks like this:

Simulation loop

The important thing to understand is that Simulink executes the Outputs method of all blocks, and then the Update method of all blocks.

The execution order

The second thing we need to know is the order in which blocks are executed. For that, we display the block sorted order.

Sorted Order

When you display the sorted order, you can see red numbers displayed on the block. The first number is the number of the system, so the function-call subsystem in this model is system number 3. The second number is the order of the block in this system. In this case, the Gain is the first (3:0), Unit Delay the second (3:1), Counter the third (3:2), etc.

The effect of the latch

To see the effect of latching, I generated code for this model and added comments to highlight the fact that the feedback loop causes the input signal to change immediately as the output is written:

Generated Code without latch

Such feedback loops break the assumptions on which the Output-Update logic is built... and can make results difficult to interpret. This is why the Latch is available.

Inport block dialog

With the latch, a copy of the input signal is made at the beginning of the step and this copy is used for the computations:

Generated Code with latch

Conclusion

In conclusion, we can say that introducing the latch is safer, but costs an additional copy. If you know that your function-call subsystem might be involved in a direct feedback loop, use Inport Latching to avoid surprises.

Now it's you turn

Are you latching the inputs of your function-call subsystems? Let us know the reason why by leaving a comment here.

March 25th, 2013

New for R2013a: Time Scope with Triggering!

Today we are happy to welcome guest blogger Kirthi Devleker to talk about a new trigger functionality added to the Time Scope in R2013a.

Did you know that a Trigger functionality is now available with the Time Scope in the DSP System Toolbox (R2013a) ? The Time Scope ships both as a System object and also as a Simulink block with the DSP System Toolbox

Time Scope without trigger Time Scope with trigger

Triggers are ubiquitous on real-world hardware oscilloscopes. They are useful to analyze signals,specifically to stabilize a repetitive waveform and search for a occurrence of a particular pattern in the signal.

Trigger Modes:

The Trigger in Time Scope supports 3 different modes of operation for a given trigger type. They are:

  • Auto: In this mode, the Time Scope stabilizes the display if the trigger criteria is met or continues to display the incoming signal.
  • Normal : The time scope displays the stabilized signal only if the trigger criteria is met otherwise nothing is displayed.
  • Once: The time scope displays the signal only for the very first time the trigger event is encountered. (Simulation will still keep running)

Here is an animation showing those different modes:

Triggering modes available in the time scope

Let's look at a few more examples

Edge Triggering

Let's create a simple sine wave and display it on the Time Scope.

Fs = 44.1e3;
Span = 1e-3
hsin = dsp.SineWave('Amplitude',10,'Frequency',2.2e3,...
    'SampleRate', Fs, 'SamplesPerFrame', 10);
hts = dsp.TimeScope('SampleRate', Fs, 'TimeSpan', Span);

for ii = 1:1e5
    x = step(hsin);
    step(hts,x);
end

As soon as you click the Trigger button, the triggers panel open allowing you to configure options like level, type, polarity, etc.

Configuring the trigger

Runt Triggering

What are Runt signals? Runt signals are the signals which typically cross a voltage threshold level but fail to cross a second threshold before re-crossing the first threshold level. Runt signals are frequently encountered in digital circuits.

For example if we look at the following waveform:

Noisy PWM signal

To look for Runt signals, Let us enable the Trigger, set the Trigger Mode to Normal, set the trigger type as Runt, adjust the voltage threshold and then the Time Scope detects and displays the presence of any Runt signals in the incoming data stream.

Runt Trigger

Now it's your turn

Go through the trigger documentation, give this a try and let us know what you think by leaving a comment here.

March 18th, 2013

Time to Convert to Variant Subsystems

If you are a user of Configurable Subsystems, it is time to start thinking about making the switch to Variant Systems.

Simulink Variants provide increased functionality over Configurable Subsystems:

  • They exist in two flavors: Model Variants and Subsystem Variants.
  • They can be controlled programmatically via variables in the MATLAB workspace.
  • They are in your model instead of a Simulink Library which simplifies model development.
Once you try the Simulink Variants, I guarantee you will immediately see their advantages and understand why we recommend moving away from Configurable Subsystems.

Here are some tips to help you migrate.

Upgrade Advisor

In R2012b, the Upgrade Advisor includes a check titled Identify configurable subsystem blocks for converting to variant subsystem blocks.

Upgrade Advisor

If you run the check and a configurable subsystem is found, the result will tell you that "These blocks can be upgraded to variant subsystems as they have better programmatic control and code generation capabilities."

Upgrade Advisor

Context Menu

If you right-click on a configurable subsystem (or any subsystem), you will see a new option to convert the subsystem to a variant.

Upgrade Advisor

A window will allow you to specify some details needed for the conversion.

Converting to Variant

and a new model will pop up with your new block converted to a variant subsystem. Notice the different icon in the lower left corner of the block, it indicates that the variant subsystem is configured to override variant conditions and behaves exactly like the original configurable subsystem.

New Variant Subsystem

Now it's your turn

Are you ready to move to Variant Subsystems? Let us know by leaving a comment here

March 11th, 2013

Some of My Favorite New Features in R2013a

MATLAB R2013a is now available for download! At the end of this post, I reveal my favorite feature in R2013a... what will it be?

R2013a is live!

For an overview of the new features, you can watch this release highlight video.

If you want to go in to more details, you can consult the What's New page for individual products. Here is he link for What's New in Simulink.

Another good source of information I like to go through is the release notes.

Here is a list of cool things you will notice for Simulink related products:

Simulink

DSP System Toolbox

Simscape

SimMechanics

SimRF

Documentation

Finally, I have to admit that some of my favorite improvements in R2013a are the enhancements made to the documentation center:

  • Highlighting of search results
  • Tree view of the documentation

R2013a Documentation Center

Now it's your turn

Let us know what is your favorite R2013a feature by leaving a comment here.


MathWorks
Guy Rouleau and Seth Popinchalk are Application Engineers for MathWorks. They write here about Simulink and other MathWorks tools used in Model-Based Design.

These postings are the author's and don't necessarily represent the opinions of MathWorks.