Guy and Seth on Simulink

February 28th, 2012

Sous-vide Cooking with Simulink Part 2

Here is the continuation of my sous-vide cooking story I began to tell in the last post.

Hardware Implementation

As described last week, I finally received everything I ordered:

I dusted off my soldering iron and soldered a cable to the LM35. Then I dipped the extremity into silicone to make it waterproof. With everything connected to the Arduino, my circuit looks like this:

Schematic of my sous-vide setup

Yeah... I know, a Tupperware is not the best container for a micro-controller. But I thought it would help avoiding to drop water on the Arduino.

Software Implementation

With everything connected to the Arduino, all that remained was to program a controller. I installed the Simulink Support Package for Arduino.

Within just a few minutes, I created the following model and uploaded it on the Arduino:

Simulink model of the Arduino controller

While this is running on the target, I can monitor the process on my PC using another model:

Simulink model of the Arduino controller

Cooking Time

I mixed a nice rub and vacuum-sealed a bunch of pork ribs.

Vacuum sealed pork ribs

I left them to cook for 24 hours at 140 degrees Fahrenheit.

My ribs cooking

I was so excited when it was time to take them out that I forgot to take pictures. I put them in the oven at broil for 2 minutes, just to give a little crunch on the top.

Believe me... that was totally worth the effort. Next time I'll try the 72 hours brisket!

Now it's your turn

Do you use Simulink on the weekend? What is your most unexpected usage of Simulink? Leave a comment here.

February 21st, 2012

Sous-Vide Cooking with Simulink Part 1

This week I am sharing the first part of a story about what I do with Simulink during weekends!

Introduction

Last Christmas, I received the book Modernist Cuisine - The Art of Science of Cooking.

Modernist Cuisine

Throughout the book, the author Nathan Myhrvold puts a lot of emphasis on a cooking technique called sous-vide.

In you are not familiar, sous-vide is a method of cooking food sealed in airtight plastic bags in a water bath for a long time at an accurately determined temperature much lower than normally used for cooking. This results in tender and juicier meats.

I have to try...

The Research

I did some research to figure out how I could try this at home and found this amazing flowchart about how to choose a Sous Vide Machine. Give a look, and post a comment below if you are also an electrical genius.

After studying all my options, I decided that, even if I could afford a nice expensive machine like the SousVide Supreme, I am going to build my own... and this will involve Simulink.

The Plan

So I began thinking about the details.

To keep my water bath at a fixed temperature, I will use a cheap, easy to use, micro-controller called an Arduino Board. I have never used one before, but I found the Simulink Support for Arduino Boards under Hardware for Project-Based Learning in the Academia page.

Arduino board and the Simulink support package library

To measure the temperature of the water bath, I will use a cheap temperature sensor chip, (like the LM35), solder a cable to it and isolate the extremity with silicone so I can drop it in the water bath.

Now... the water bath. For this part I hesitated a bit. After some reflection, I decided that will use a crockpot I already own and will switch it On and Off using a relay. If found on the web a device called PowerSwitch Tail that will be perfect for that.

The following schematics gives an overview of my project:

Schematic of my sous-vide setup

What's Next?

I ordered all the stuff needed online and now I am waiting. If everything goes fine, next week I will follow up with the implementation and testing of my Simulink sous-side cooking system.

I can't wait to try the 24 hours pork ribs!

Update: Click here to see part 2

Now it's your turn

Please share any tips and suggestions to help with my sous-vide system. Leave a comment here.

February 9th, 2012

Using Discrete Data as an input to your Simulink model

Today I want to look at a problem that often frustrates Simulink users who have discrete inputs to their model.

The Problem

I create a simple model with just an Inport block connected directly to an Outport block, both configured to execute at a sample time of 0.001 second.

Simplest Possible Model

I configure the model to import data from the workspace:

Configuring a model to Imprt data from workspace

I simulate the model and compare the input with the output using this code:

ts = 0.001;
t = (0:ts:10)';
u = (1:length(t))';
simOut = sim('exampleModel');
stem(abs(u-simOut.get('y').signals.values))

For some samples, the output does not match the input.

Comparing input and Output

The explanation

To understand what is happening here, it is important to compare the time vector of the input data and the time vector used by Simulink.

Comparing time vectors

As we can see in this image, the steps taken by the Simulink solver are different from the ones specified in the input time vector. As explained in technical solution 1-1ITHX9, Simulink computes time using the following equation:

time = stepSize * [0:N]'

While these two methods look similar, they can give different results due to floating point round-off. As you can image, if the input data is slightly behind or before the step taken by the solver, a data point can be skipped or repeated.

The Solution

To avoid such problem, it is recommended to NOT provide the time vector when inputting discrete data into a simulation. For example, modifying the code to use a structure without time will allow the Inport to take the next sample from the vector at each step. Here is some code to create a signal structure without time, update the model to use this structure, and verify that the input and output are equal.

inputStruct.time = [];
inputStruct.signals.dimensions = 1;
inputStruct.signals.values = u;
set_param('exampleModel','ExternalInput','inputStruct')
simOut = sim('exampleModel');
norm(u-simOut.get('y').signals.values)

ans =

0

Now it's your turn

Look at the doc section Guidelines for Specifying Time and Signal Values for Imported Data for more details more this topic.

Let us know how you import data into your models by leaving a comment here.

February 1st, 2012

Applying Motion to SimMechanics Models

One of the features I like about SimMechanics is the ability to specify the motion of a system without having to think about the forces involved. This can simplify testing a model so you don't have to design a controller if all you are doing is testing the plant model for correctness. Today I want to talk about a common problem people run into.

The Problem

I have the following SimMechanics model. This model is supposed to simulate a big crane... you know the ones with a big ball at the end of a cable used to destroy buildings.

SimMechanics model of a crane

When applying a sine wave trajectory (position) to the base, I expect the ball to swing, however it does not!

SimMechanics animation of a crane

The Explanation

As you probably noticed, the base is actuated with a Joint Actuator, setup to Actuate with motion. In this configuration, three components must be fed to the block: Position, Velocity and Acceleration.

Obviously, the velocity and acceleration corresponding to a sine wave trajectory are not 0!

The Solution: First Try

To get valid results with SimMechanics, it is important to provide valid inputs.

To do that, the first thing that probably goes through your mind is to use Derivative blocks, like this:

Using Derivative blocks

This works if the position signal is smooth, however in many cases this can cause problems.

Why? If you have a discontinuity in the position signal, this will cause a sudden change in the velocity signal and an infinite acceleration. Infinite accelerations are not realistic and cause derivative errors in the solver.

A Better Solution

What I recommend is to implement a filtered derivative using a Transfer Function block.

Using Derivative blocks

Now we can see that our crane behaves as expected.

SimMechanics animation of a crane

Now it's your turn

If you are interested, you can find the model here.

Look at the documentation section titled Stabilizing Numerical Derivatives in Actuation Signals for more details and let us know what you think by leaving a comment here.

January 22nd, 2012

Advanced S-function Techniques: Scheduling Future Events

Today I will describe how to use a variable sample time s-function to schedule events in the future. This topic is fairly advanced, so hold on tight... or as we say where I come from: Attachez vos tuques avec d'la broche

The question

The question I received is:

I have a model with a variable sample time solver. In this model, I have a signal with a continuous sample time, but discontinuous amplitude. Every time the signal changes amplitude, I need to trigger a subsystem. But I do not want to trigger the subsystem immediately. I need to trigger after fixed delay.

Original Model

First attempt

The first thing the user tried is delaying the signal using the Transport Delay block and detecting the changes in the delayed signals.

As I explained in a previous post, the Transport Delay expects a smoothly changing continuous signal. When fed a signal with discontinuities, the output of the Transport Delay is not exactly the input offset by a delay. This is the situation we encounter as shown in this image below.

Delaying the input signal

Variable Sample Time

One way for a block to tell the Simulink solver to take steps at a specific moment in the future is to specify variable sample time. For example, the Pulse Generator block uses this technique to run only when needed.

If I make a model with the Pulse Generator block configured to have a period of 5s and a pulse width of 40%, the block will tell the variable step solver to take steps at times 0s, 2s, 5s, 7s, 10s,...

Pulse Generator, a Variable Sample Time block

Variable Sample Time S-function

With an s-function, you can do the same!

For a basic example, look at the demo model sfcndemo_vsfunc.mdl. This model shows how to use mdlGetTimeOfNextVarHit to specify the next time your block should run.

The solution

Based on that, we want to write an s-function that will look at its input every major step of the simulation. When a change will be detected, we will store the time value in a buffer. Every time an event will be generated, we will look into this buffer and schedule the next event.

In S-function specific terms, this means:

  • In mdlInitializeSizes, we specify the size of the buffer using ssSetNumRWork . We also define an integer work vector using ssSetNumIWork to keep the index of events coming in and out of the buffer.
  • In mdlInitializeSampleTimes, we declare 2 sample times: Fixed in Minor and Variable. The fixed in minor sample time will allow us to monitor each sample of the input signal for detected changes and the variable sample time will be used to generate the events.
  • In mdlUpdate, we monitor the input. If a change is detected, we store the time in the work vector.
  • Every time a variable sample time is hit, the solver calls mdlGetTimeOfNextVarHit to obtain the time of the next variable sample time hit. When this happens, we look into the work vector to get the time of the next event and use ssSetTNext to register it.
  • In mdlOutputs, we use ssIsSampleHit to know if the current step is a hit of the variable sample time. If this is the case, we generate a function call using ssCallSystemWithTid.

When this is all implemented, I have a block that can schedule events in the future

Final Model

For those interested to see the final results, here are links to the model and the s-function source code.

Now it's your turn

Do you use variable sample times in your model? Leave us a comment here.

January 11th, 2012

Model-Based Design of a Dicycle

The other day I found this video:

If you watch carefully, you will see around 1:50 that they used Simulink to design their controller.

So for this week's post, I thought it would be interesting to see how we can design a simple planar version of a dicycle in Simulink.

Modeling the plant in SimMechanics

Since this system is not very complex, I could have derived the equations of motion by hands. But even if the equations are simple, it is simpler (and more fun) to model it with SimMechanics.

To model this planar dicycle, we need 3 bodies: the ground, a wheel and a center body. The important trick here is the Velocity Driver block constraining the motion of the wheel relative to the ground. Note that, to make the SimMechanics visualization look nicer, I added 2 posts acting as starting and stopping references.

Modeling a Diwheel using SimMechanics
Click on the image to download the model.

Our system has 2 sensors, a gyroscope returning the angle of the body relative to gravity, and an encoder giving the angle of the body relative to the wheel. On the actuator side, the system has 1 motor applying a torque between the wheel and the body.

Testing the plant motion

When developing a plant model, it is important to validate it. To validate the plant, I apply a torque to the actuator and observe if the resulting motion is as expected.

Uncontrolled motion

This behaves as expected... but if I don't find a better controller, the passenger will quickly get sick. Let's see how we can design a controller.

Linearizing the plant

Most control techniques I know are based on a linear representation of the system. To obtain this representation, I use Simulink Control Design. I can use the graphical interface or the command-line API. For my model, the command-line version looks like:

mdl = 'Diwheel';
% Set the controller to zero during linearization
K = [0 0 0 0];
% Construct linearization input/output
io(1) = linio([ mdl '/Ctrl'],1,'in','on')
io(2) = linio([ mdl '/Sensors'],1,'out','on')
% Linearization
sys = linearize(mdl,io);

Designing a controller

Now I will use the Control System Toolbox function lqr to design a state-feedback controller. The code looks like this:

% Get minimal realization
[sys U] = minreal(sys);
% Design state feedback controller
Q = diag([ 100 1 100 1],0);
R = 1;
[K,S,e] = lqr(sys,Q,R);
% Transformation from y to x
K = K/sys.C;

All I had to tune are the values on the diagonal of matrix Q to give a priority to each state. You can download the complete initialization script here.

Now if I try to command the vehicle an aggressive trajectory of 1m/s for 10 meters and sudden breaking, I get the following:

Controlled motion

Next steps

I will stop here for this post. If I had to implement this controller on a real system, I would have a lot more steps to go through. This would involve adding to the model actuators limits, sensors resolution, discretizing the controller, maybe converting it to fixed-point, etc.

Now it's your turn

Let us know what you think of this control design process by leaving a comment here.

January 4th, 2012

Frames… from signals to blocks

Today I want to talk about an important topic for DSP System Toolbox and Communication System Toolbox users: Frame-Based Processing

Beginning in R2010b, MathWorks started to significantly change the handling of frame- and sample-based processing. Currently, we are in a transition phase and it's time to update your models to the new paradigm.

Sample-based processing vs. frame-based processing

Let's begin by a quick explanation of the difference between frame-based and sample-based processing.

Let's say I have a signal of dimensions 3x2. If I process this signal in a sample-based manner, every simulation step I will process the 6 elements individually as 6 independent channels:

One sample

In frame-based processing, blocks process signals multiple sequential samples per time step. For example, a 3x2 matrix like in the previous example could contain only 2 independent channels. For each channel, this matrix contains a frame of 3 samples:

One frame

As you can guess, frame-based processing can lead to significant performance improvements because each block operates on frames of data rather than on individual samples, and interblock communication is reduced.

Changes to Frame-Based Processing

Historically, in Simulink the frame status has always been an attribute of the signals, like data type and dimensions.

This can be seen by looking at the CompiledPortFrameData property of an Output port with a code like the following:

modelname([],[],[],'compile')
ph = get_param('modelname/White Noise','PortHandles')
get_param(ph.Outport,'CompiledPortFrameData')
modelname([],[],[],'term')

Beginning in R2010b, we started to significantly change the handling of frame- and sampled-based processing. In the future, frame status will no longer be a signal attribute. Instead, individual blocks will control whether they treat inputs as frames of data or as samples of data.

This means that many blocks in the DSP System Toolbox and Communications System Toolbox now have an Input Processing option where they can decide to process columns as channels (frame-based) or elements as channels (sample-based). You can notice in the following image that the block dialog clearly mentions that the option to inherit the processing type from the input signal will be removed in the future.

One frame

To open a demo model highlighting the effects of this setting, type ex_inputprocessing at the MATLAB prompt.

What should I do to update my model?

One word: slupdate

During the transition phase, the frame information is still propagated through the signals in your model. Based on this information, slupdate can automatically configure the blocks for the new paradigm.

In the future, the frame information will be removed from signals and you will no longer be able to upgrade your models using the slupdate function. Therefore, you should upgrade your existing models using slupdate as soon as possible.

Now it's your turn

Give a look at the R2011a and 2011b release notes of the DSP System Toolbox and let us know what you think by leaving a comment here.

December 27th, 2011

Model-Based Design Dilemma

I am currently working on a model and I have a dilemma. There are two ways I could model my system. I need you to tell me which approach is best and why.

I need your help!

The Goal

I am building a model to drive a small robot made of Lego blocks. The system is similar to the NXTWay-GS submission on the MATLAB Central.

NXTWay-GS

Following a Model-Based Design approach, I want to setup my files so that I can easily develop my controller in simulation and generate code to test my algorithm on the real hardware. This means that in simulation I need to send my actuator commands to an LTI system approximating the system dynamics; and for code generation I need to send and receive signals from hardware drivers.

Hardware drivers and simulation model

My question now is: What is the best way to include these 2 sets of blocks in my model architecture?

Option 1: Two Top Models

My first option is to create 2 top models that will both refer to the same controller using model referencing.

I would have one top model for simulation:

Model for simulation

and one top model for code generation:

model for code generation

Option 2: Subsystem Variants

My second option is to create one top model. In this top model, use Subsystem Variants to switch between the simulation and the hardware drivers:

One top model with 2 variant

Now it's your turn

What architecture do you prefer? For which reasons? Do you see other options? I am very interested to hear your comments and ideas. Please leave a comment here.

December 20th, 2011

Mixed-signal modeling with Simulink

If you’re a mixed-signal engineer, we have a Christmas present for you – a new library of mixed-signal blocks and demos available for free. My colleague Mike Woodward explains all.

Designing mixed-signal systems with the free mixed-signal library

For years now, MathWorks engineers have been building mixed-signal examples for customers. We’ve built ADCs, PLLs, digital pre-distortion, and switch-mode power supply demos, often including documentation. It occurred to us that we could help our customers if we bundled demos and blocks into a library. Better still, this library could offer full help and full integration with Simulink. Best of all, we could offer the library for free. This is the new mixed-signal library.

The library has 20+ demos covering ADCs, PLLs, digital pre-distortion, switched-mode power supplies, signal integrity, and RF. Each demo has full help, accessible from the demo or from Simulink’s help system. Here’s a screenshot of one of my favorite demos:

Mixed-signal demo

There are 40+ blocks ranging from OpAmp to Clock Divider to Triggered Eye Display. Every block has help and we’ve made sure every block appears in a demo. Here’s a screenshot showing some of the blocks:

Mixed-signal Library

We’ve also supplied three detailed tutorials that take you step-by-step through the process of building an ADC, a PLL, and a digital pre-distortion system. We’ve included all the files, including the data files and the model files for each step of the process. This way, if you make a mistake, you can correct it very quickly.

The library depends on MATLAB and Simulink, plus some other products. As you might expect, the dependencies vary from demo to demo – for example, the circuit demos require products the behavioral demos don’t. We’ve listed the dependencies in the help for each block and demo.

To make it all easier to use, we’ve fully integrated the library with Simulink – the library appears in the library browser and in the help browser. The installation process is easy and you can do it in under 5 minutes.

Now it's your turn

Download the mixed-signal library here and let us know what you think by leaving a comment here.

December 14th, 2011

Welcome to the Linear Analysis Tool!

Today I am happy to welcome back guest blogger Erman Korkut to talk about the new Linear Analysis Tool.

Guest blogger, Erman Korkut

Linear Analysis Tool

Have you ever trimmed your model? Have you ever linearized it? Have you ever estimated its frequency response? Simulink Control Design has been offering all these capabilities for some time. In R2011b, we introduced the Linear Analysis Tool streamlining all these capabilities into a single interface.

Trimming a model

Before linearizing a model or estimating its frequency response, it is important to specify an operating point. It can be by taking a snapshot at a specific instant, or by finding a steady state (equilibrium) operating point, commonly referred to as trimming.

To get started, go to Tools -> Control Design -> Linear Analysis, select the Linear Analysis tab and click the Trim Model or the Operating Point Snapshot button:

Linear Analysis tab

Linearizing a model

The linearization of your model provides you with a lot of insight about its dynamics. You can inspect the frequency response, evaluate stability margins, and design controllers using the linearization result. You can linearize a model around different operating points to analyze and compare its behavior at different operating conditions.

Once you are ready to start, select the Exact Linearization tab:

Exact Linearization tab

Estimating the frequency response of a model

Another way to compute the frequency response of your nonlinear model is to simulate it with appropriate input signals, measure the output signals of interest, and inspect the frequency content of those output signals. The frequency response data obtained this way can be used to identify a parametric model or to design a controller. It also serves as an independent test for the exact linearization; thus, it can be used to validate exact linearization results.

Select the Frequency Response Estimation tab and define your input signal:

Frequency Response Estimation Tab

Analyze your Results

Once you completed a linearization or a frequency response estimation, the Linear Analysis Tool allows to visualize your systems in multiple ways and to easily transfer data to the MATLAB workspace:

Frequency Response Estimation Tab

Videos

You want to see more? I highly recommend watching the following short videos to see the linear analysis tool in action:

Trim Batch Mode Trimming and Linearization Frequency Response Estimation
Trim, Linearization and Control Design for an Aircraft Batch Mode Trimming and Linearization Frequency Response Estimation


Now it is your turn

Do you trim, linearize and estimate the frequency response of your Simulink models? What tools are you using to do so? Try using the Linear Analysis Tool with your model and share how it goes 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 The MathWorks.