Guy and Seth on Simulink
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:

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:

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:

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

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.

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

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

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:

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

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.
By
Guy Rouleau
13:51 UTC |
Posted in Modeling, Signals, Simulink Tips |
Permalink |
5 Comments »
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.

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

Record & Inspect Simulation Output
In your model, click on the Record button.

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

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.

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.
By
Guy Rouleau
10:34 UTC |
Posted in Analysis, Debugging, Model-Based Design, Signals, Simulink Tips |
Permalink |
7 Comments »
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:

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.

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.

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.

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.

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:

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.

Now it's your turn
If you have some interesting plowing or zero-crossing stories to share, leave a comment here
By
Guy Rouleau
14:11 UTC |
Posted in Debugging, Modeling, Performance, Simulink Tips |
Permalink |
No Comments »
April 21st, 2013
Implementing a PID Controller on an Arduino Board
This week my colleague Pravallika is back to continue her motor control story!

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:

For this transfer function, we designed the following controller using 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:

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

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.

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.

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:

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.
By
Guy Rouleau
16:49 UTC |
Posted in Controls, Guest Blogger, Modeling, Rapid Prototyping |
Permalink |
4 Comments »
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.

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:

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.

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.

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.
By
Guy Rouleau
03:00 UTC |
Posted in Code Generation, S-functions |
Permalink |
2 Comments »
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.

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

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:

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.

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:

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.

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:

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.
By
Guy Rouleau
09:58 UTC |
Posted in Code Generation, Debugging, Signals |
Permalink |
No Comments »
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

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:

Let's look at a few more examples
Edge Triggering
Let's create a simple sine wave and display it on the Time Scope.

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

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:

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.

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.
By
Guy Rouleau
16:07 UTC |
Posted in Signals, What's new? |
Permalink |
No Comments »
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.

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."

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.

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

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.

Now it's your turn
Are you ready to move to Variant Subsystems? Let us know by leaving a comment here
By
Guy Rouleau
12:00 UTC |
Posted in Modeling, What's new? |
Permalink |
6 Comments »
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?

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

Now it's your turn
Let us know what is your favorite R2013a feature by leaving a comment here.
By
Guy Rouleau
14:59 UTC |
Posted in What's new? |
Permalink |
1 Comment »
February 28th, 2013
MATLAB Language in Stateflow
Have you noticed a new block in the Stateflow Library since R2012b?

The MATLAB Chart block uses MATLAB as the action language for states and transitions in Stateflow.
This means that you don't have to create a separate MATLAB Function every time you want to do matrix math in a Stateflow chart. Let's look at a few examples of what can be done in a MATLAB Chart.
Matrix Operations
Let's say I define a bus object containing a 3x1 position vector and a 3x3 rotation matrix:

With MATLAB as the action language, I can multiply the bus elements directly in a transition action:

Access to all MATLAB Coder supported functions
With MATLAB as the action language, you can use any function supported by MATLAB Coder for code generation. For example, I can use the functions like ones and eig in a transition:

Manipulating Arrays of buses
Let's say I want my chart to generate an array of the bus defined previously, I could write something like:

Conclusion
Based on my experience, using MATLAB as the action language in Stateflow charts makes it a lot easier to implement the algorithms I need. Since I first tried it, I have not needed to use C as the action language.
Of course, the MATLAB Chart block is not the best choice for all applications. If your application is interfacing with legacy C functions or more naturally expressed in C language, than there is no need to switch. The C chart block that we are all used to still continues to be developed and supported.
If you need help deciding which block to use, I recommend looking at the Differences Between MATLAB and C as Action Language Syntax in the Stateflow documentation.
Now it's your turn
Have you tried using MATLAB as the action language in your Stateflow charts? Let us know what you think by leaving a comment here.
By
Guy Rouleau
11:22 UTC |
Posted in Stateflow, What's new? |
Permalink |
2 Comments »
|
Recent Comments