Quantcast
Channel: Simulink – File Exchange Pick of the Week
Viewing all 33 articles
Browse latest View live

Synchronizing a MATLAB GUI and a Simulink Model

$
0
0

Jiro's pick this week is Simulink GUI Synchronization by our fellow MathWorker Will Campbell.

Here's a little something new. We've been mostly looking at MATLAB entries in this blog, but today we'll take a look at a Simulink example. Even though this is a simple example, I find this very useful and pedagogical. Imagine that you want to build a graphical user interface that controls your Simulink model (You know how I'm all about GUIs!). This is not uncommon and can be accomplished by using functions like set_param and get_param. But what if you want to be able to control the model directly through Simulink as well as through the MATLAB interface? In that case, you want to make sure that the interface accurately reflects the current state of the model.

In this example, Will shows how you can create a MATLAB GUI that not only drives and manipulates your Simulink model, but also stays synchronized to the current state. You too can now drive and manipulate your Simulink model from either environment!

Comments

Tell us how you use MATLAB and Simulink together.


Get the MATLAB code

Published with MATLAB® 7.9


Simscape sensing made easy

$
0
0

Jiro's pick this week is Simscape Probes by our fellow MathWorker Tom Egel.

Continuing in the spirit of my previous pick, I would like to highlight another useful Simulink utility for those of you doing physical modeling using our Simscape™ product family. These tools allow you to model physical systems at a component level, rather than from equations. It's very useful when your system starts to get very complicated, like an airplane or a car (yes, our customers use our tools to model whole aircrafts.) Those of you who have worked with physical systems can appreciate the fact that you can take measurements just by placing probes and sensors. Well, you can do that with a simulation model as well. To do that in Simscape, you place an appropriate sensor component, convert physical signals to Simulink signals, and measure.

It's pretty straight-forward once you understand the process, but with Tom's utility, sensing will now become second nature.

In addition to what you see above, he has created a slew of probes for various domains, a utility to group probe signals, and a help file.

Comments

Give this a try and tell us what you think, or leave a comment for Tom on the submission page.


Get the MATLAB code

Published with MATLAB® 7.9

Explore Your Physical Modeling Data

$
0
0
Will's pick this week is the Simscape Simulation Results Explorer by Atul Suri.

What's this, a new blogger? As Jiro and Brett continue their quest for the missing third amigo, they have graced me with the opportunity to select a few exchange contributions for this much-coveted award. I'm an aerospace engineer who has used MATLAB for over a decade. Since joining MathWorks, I have focused on Simulink, hence you will see favoritism towards Simulink contributions in my selections. Word to the wise, I am notorious as a perfectionist around the office. So get your submissions squeaky clean if you want to win the prize.

This week, I have selected a utility for our Physical Modeling tools. Simscape facilitates simulation of electrical, mechanical, hydraulic, magnetic, pneumatic, and thermal systems within Simulink. Rather than having to derive a system of equations and then implement those equations with basic Simulink blocks, I can instead schematically draft a physical network diagram. In the example below, I have created a simple Graetz bridge rectifier electrical circuit.

rectifier model

Ok, great. But how do I analyze the results of my simulation? Well, we could rely on Simulink Scope blocks to acquire time traces of data. Simscape Probes is a former Pick of the Week winner that streamlines this process. However, if you go down this path, you can't escape the limitation that you will have to attach one Scope to every parameter you're interested in. If you want the voltage and current pertaining to every element of your diagram, that's going to require a lot of extra work.

Fortunately, it is possible to log all data in a Simscape diagram in one fell swoop. Within the Configuration Parameter Simscape tab, enable Data Logging.

Rectifier Configuration Parameters

Upon running your simulation, you will get a Simscape data logging variable. The structure of this variable can be explored manually, and you can leverage all  your traditional MATLAB analysis and visualization tools.

Atul's submission is a utility that makes examination of Simscape data even easier. Simply type ssc_explore(simlog) and a new window will open. It provides a data tree to explore the different elements of your physical network. We can open different elements and view plots of our data.

Simscape Simulation Results Explorer

This is one of my most-used File Exchange contributions. And for that, it is my inaugural Pick of the Week.

Comments
Let us know what you think here or leave a comment for Atul.

Quickly Create Simulink “From” Blocks

$
0
0
Will's pick this week is the Create From Blocks by Giacomo Faggiani.

When I first began using Simulink, I was averse to the From and Goto blocks in the Signal Routing library. Years of writing Fortran (yes Fortran) had ingrained in me a deep aversion to "Goto." But I soon realized that the block had little to do with the questionable coding practice.

Under the proper circumstances, From/Goto combinations can be quite powerful in Simulink. They serve as invisible shortcuts for signals within the model. This enables the user to avoid signals crossing one another, a stylistic choice that can make a model harder to decipher. Of course you wouldn't want to exclusively use Froms/Gotos; that would also make for a cryptic diagram.

If you're looking for a good rule of thumb on when to use these blocks, the MathWorks Automotive Advisory Board (MAAB) produced a style guide that includes rules for From and Goto. Check out sections 6.1.14 and 6.3.5 for more information. Below is a screenshot of proper usage according to MAAB.

MAAB Style Guide examples of appropriate usage of From and Goto blocks

Once you get in the habit of using these blocks, you'll probably discover that management of them isn't quite as efficient as it could be. When you add a Goto block to your model, you invariably want a corresponding From block. That means you have to go to the Library Browser, find the From block, add it to the model, double-click on it to open the dialog, and associate it with the proper Goto tag. You may also want to color code the blocks to match one another.

Giacomo's contribution streamlines this entire process by adding an option to the menu when right-clicking on a Goto block. Selecting the menu option will create a corresponding From block with the appropriate tag. It will even make the aesthetics of the block (font, background color, size, etc) match its Goto partner. Now we can all be that much more productive!

Create From Blocks

Comments
Let us know what you think here or leave a comment for Giacomo.

Log and Inspect Simulink data quickly with SIMLOG

$
0
0

Doug's pick this week is SIMLOG by Robin Larsson

Hi, my name is Doug, and I'm one the guest pickers that will be contributing to the Pick of the Week blog occasionally. I started using MATLAB and Simulink while studying mechanical engineering in college. I soon found I was more interested in doing cool stuff with the software than the actual engineering, so I'm thrilled to now be working at MathWorks as an Application Engineer like Brett and Jiro. I tend to focus on the Simulink and control related tools so you may find that my picks are generally related to those topics.

When I first started using Simulink I would add lots of scope blocks to my models when something wasn't behaving the way I expected and I needed to locate the source of the problem. While this worked, it was a bit tedious and cluttered up my models significantly. Once I had resolved the issue I would delete all these debugging scopes to restore the clean look. And of course if another issue cropped up, I'd go through the whole process again.

In R14, Simulink gained the ability to log and plot signals without using any additional blocks. In R14SP3, MATLAB introduced the timeseries object and the Time Series Tool that help manage and analyze time series data such as what is produced by Simulink. However when I go out and talk to users today I find that many are not aware that these capabilities exist. What I like about Robin's SIMLOG tool is that it exposes these new capabilities to users and highlights their advantages. It also makes it easier to enable and disable the logging of many signals simultaneously.

With SIMLOG you can select whatever signals you are interested in and then log them all with one click. After running the simulation you can then plot whatever signal you select in a standard MATLAB figure:

simlogDemo

Robin has also added the ability to select all the signals in a subsystem or exclude or include signals based on block type. In addition there is a button to launch the time series tool to further analyze the logged data.

This is a great first submission from Robin.

Comments

Let us know what you think here or leave a comment for Robin.

Run on Target Hardware

$
0
0

Doug's picks this week are Simulink Support Packages for LEGO MINDSTORMS NXT [link], Beagleboard [link], Arduino Uno [link], and Arduino Mega [link] by the Classroom Resources Team.

This week, I'd like to highlight a new feature in the R2012a release of Simulink called Run on Target Hardware.

You may remember back in November 2010 Greg Wolff highlighted my Arduino Target submission that let you run a Simulink model on an Arduino Deumilanove by leveraging Simulink Coder and Embedded Coder to convert the model to C code.

So what's different about this new Run on Target Hardware capability? Well starting in R2012a you can now run your Simulink models on hardware even if you do not have Simulink Coder or Embedded Coder. That means that even those of you using the Student Version can take advantage of this capability! Run on Target Hardware currently supports the Uno and Mega varieties of the Arduino as well as the BeagleBoard-xM and LEGO MINDSTORMS NXT.

While there are File Exchange submissions for the supported hardware targets, you should install them directly from MATLAB by typing "targetinstaller" at the command prompt. This brings up a tool that automates the download and install process. Watch the video below to see it in action:

Video: Introduction to Simulink Support for Target Hardware
Introduction to Simulink Support for Target Hardware 1:57

If you do have Simulink Coder and Embedded Coder, the original target is still available and is known as the Embedded Coder Support Package for Arduino. It supports the ability to do processor-in-the-loop simulations. For more information on the different ways Arduino is supported with MATLAB and Simulink see this solution page.

Comments

We can't wait to see what kind of interesting projects you come up with by taking advantage of this capability. Please check it out and let us know what you think here.

Simulink Model for Fetal ECG Extraction

$
0
0
Will's picks this week is Simulink model for Fetal ECG extraction by Igal.

Signal processing isn't typically an area of interest for me. Half the time, all that filtering, modulation, buffering, and quantization is black magic to me. But I find Igal's File Exchange contribution is oddly approachable and understandable, most likely because of the quality design of the model.

Igal has leveraged a MATLAB example created by Dr. Scott C. Douglas to construct a Simulink model to identify the heart rate of a fetus based on sensor data from two electrodes. Effectively, you have two primary signals (mother and baby's heartbeat) with noise superimposed. The goal is to filter out everything but the baby's heartbeat and calculate the period of the signal based on our estimation of that heartbeat.

In order to accomplish this, Igal relies on blocks from the Simulink and Digital Signal Processing libraries. But he also makes use of his own custom components via the MATLAB Function block. Here is a screenshot of the primary subsystem of the Simulink model. I made some aesthetic changes so that it would fit within the blog's width restrictions.
Igal's Fetal ECG Processing Algorithm

Now this is all well and good, but one of the beautiful things about Simulink (and MATLAB for that matter) is the ability to convert your work into another computing language. In this case, Igal has ensured that his model is suitable for conversion into Verilog HDL code. This enables us to take our work and run it on an FPGA (if we happen to have one laying around). And in order to get the biggest bang for your buck on such hardware, you'll need to dabble with fixed point math. Luckily for us, Igal's signals are already set to fixed point in the model.

You can right-click on the primary subsystem and select "Generate HDL for Subsystem" if you have HDL Coder. I did as much; here's a small sample of the resultant code.
Igal's Fetal ECG Verilog Code

Comments Let us know what you think here or leave a comment for Igal.

Raspberry Pi DC Motor Driver

$
0
0
Doug's pick this week is Raspberry Pi DC Motor H-Bridge Driver Block by Joshua Hurst.

As my previous posts may suggest, I've been a long-time fan of the Arduino platform. Among other things I use it as the basis of a demonstration to showcase a variety of MathWorks' tools that includes driving a motor to rotate a camera to track an object. The Arduino works great for doing closed-loop position control of the camera, but falls short when it comes to actually processing the camera video to detect the object. So currently the video processing is relegated to my laptop which prevents me from creating a completely embedded solution.

Enter R2013a which introduced support for a number of new target platforms which Jiro pointed out earlier this year. I was drawn to Raspberry Pi in particular because it is a similar price and form factor to the Arduino, but has built-in support for USB webcams:

Raspberry Pi Block Library

Looking at the blocks that are included with the target, however, you'll notice that there is nothing included for sending voltages to a DC Motor like you can do with the Arduino PWM Output blocks. Because of that I had initially planned to use both the Raspberry Pi and Arduino for my demo until I ran across Joshua's submission the other day. His model uses S-Function Builder blocks to take advantage of the new WiringPi support in the Raspberry Pi image that is used in the support package. Here's the top-level of Joshua's model:

Motor Driver Model

After some breadboard work, I built and downloaded the model and I was controlling my motor in minutes by simply changing the Input Volts value in External Mode. Now I just need to decide on the best way to read the motor's potentiometer then the whole system can run on the Pi. Or perhaps I should bite the bullet and switch to an encoder. If anyone has any suggestions, leave a comment!

I was happy to see that Joshua was inspired by Giampiero's Device Driver guide that explains how to create custom drivers for the hardware support packages. Joshua has also recently uploaded several other related submissions. I'm looking forward to seeing what Joshua and others come up with in the future to increase the I/O options for the different hardware platforms.

One minor suggestion I would have for Joshua is to include the pin numbers that correspond to the PWM outputs for this model. I had to do a bit of hunting to track that down (it's 7 and 11 on the P1 header for those that are interested). But other than that, this submission has been a big help, thanks Joshua!

Comments
Let us know what you think here or leave a comment for Joshua.

Dynamical Systems with Applications using MATLAB

$
0
0
Will's pick this week is Dynamical Systems with Applications using MATLAB by Stephen Lynch.

Many years ago, a professor of my numerical methods class insisted that we write all our programs in C. When several students bemoaned this imposition, he explained that the reason he did this was that the exercise was "pedagogical." Well, once I looked up what pedagogical meant, I saw some merit to his position. It never hurts to flex your skills in a different programming language. In this case, however, I felt like C was the wrong tool for the job. MATLAB was a more natural environment to develop the algorithms in question, and its output still satisfied the homework deliverable requirements. In the end, the TA accepted my work from MATLAB without complaint.

So anytime I see a professor arrive at the similar conclusion that MATLAB is an ideal programming platform for engineering problems, I can't help but be delighted. Dr. Lynch has in fact built his entire dynamics textbook around MATLAB and Simulink. All the examples he uses in the book are available on MATLAB Central. Some 59 MATLAB files and 10 Simulink models are provided.

Of course if you have the book, you'll have a better appreciation for what intriguing plots like these are conveying.

Ring Passes

Lorenz System

Nevertheless, anyone with some experience in dynamics will appreciate the work that's put together here.

Comments
Let us know what you think here or leave a comment for Stephen.

Flight Route Planning Simulator

$
0
0

Sean's pick this week is International Flight Route Planning Simulator by Simulink Dude.

San Diego

At the time of this posting, I will be in San Diego, California. I fully expect to be sitting on a beach or a sailboat getting a nice sunburn instead of shoveling snow off my driveway back in Massachusetts. Alright, who am I kidding, I'll be in a business meeting...

Out of curiosity to see where the planes would fly in order to transport us to Southern California, I turned to the File Exchange and discovered Simulink Dude's Flight Route Planning Simulator.

After downloading it there was a convenient run_me_now file that seemed, well, like I should run it!

My Own Flight Path

It appeared easy to change the example to use my flight termini. All I had to do was change the latitude and longitude vectors.

My flight itinerary is:

  • Outbound: Boston -> San Diego
  • Return: San Diego -> Dallas / Fort Worth -> Boston

So I need to acquire the latitude and longitude of these cities, which could be done with an internet search. Instead, I'll do it completely within MATLAB using the Mapping Toolbox's new webmap functionality.

% Build the webmap.
h = webmap;

Now I need to zoom in on Logan, recording the airport coordinates. I did this interactively, and then extracted the center using wmcenter.

Repeating these steps for San Diego and Dallas yields latitude and longitude vectors of:

% Boston, San Diego, Dallas, Boston
latitude = [42.36532 32.73662 32.89819 42.36532].';
longitude = [-71.00800 -117.19137 -97.04380 -71.00800].';

% Add markers at the airports to check it
wmmarker(h,latitude,longitude);

Now I comment out the latitude and longitude vectors in the run_me_now script and then run it to use the ones I defined. This will pull up the Simulink Model and the Simulink 3D Animation virtual reality world viewer where we'll be able to see the flights:

The Camtasia Studio video content presented here requires JavaScript to be enabled and the latest version of the Adobe Flash Player. If you are using a browser with JavaScript disabled please enable it now. Otherwise, please update your version of the free Adobe Flash Player by downloading here.

How neat is that?

Plus, this also means I can now officially say: I've used the Aerospace Toolbox and Blockset :)

Comments

Give it a try and let us know what you think here or leave a comment for Simulink Dude.


Get the MATLAB code

Published with MATLAB® R2013b

SimRF Models of Analog Devices RF Agile Transceivers

$
0
0

Idin's pick for this week is the SimRF Models of Analog Devices RF Agile Transceivers by MathWorks RF Team.

This is probably one of the best documented submissions on the File Exchange. The Simulink models in this submission can be used to accurately simulate a commercial radio frequency (RF) chip (Analog Devices AD9361). The work was the result of collaboration between MathWorks and Analog Devices engineers, and the final result is a software model that matches the behavior of the physical device on the lab bench.

You can get a lot of details on the hardware and these software models here.

I will not go into any further technical details on this page, but I want to point out why I believe this was a useful and interesting project.

First, this is just plain cool! Seeing any software model predict (or match) hardware behavior at the level of detail that we find in these models is always interesting (having run simulations for 15+ years, I’m still amused when what I see in the lab matches what I predicted in simulation; it feels magical every time!)

Second, it helps understand and program the chip. An RF chip like the AD9361 (or most any chip for that matter) is a complex piece of hardware, and you can't see inside of it. This is an "agile" RF transceiver, which means it can be programmed to perform many different tasks for many different radio applications. Understanding the functioning of such a chip, and programming it correctly are rather difficult tasks in hardware, especially when the results of one's work can't be seen immediately (at least not without the use of expensive lab equipment such as spectrum analyzers). Having a software model that accurately mimics the hardware allows me to understand the behavior of the hardware such that I can program it better.

Third, debugging. If you have programmed anything but the simplest piece of hardware, you know that things rarely do what you want on the first try. Understanding apparent anomalies and hardware "misbehavior" is made infinitely easier when we can go to a simulation model and trace different signals to our heart"s content! With this Simulink model I can look at intermediate signals that I could never access on the physical chip. These intermediate signals often hold the key to understanding why the system’s outputs look the way they do.

Fourth (this should really be 3.5), studying the effects of an RF chip on digital baseband signals. These effects are generally something that we observe once we put everything together in the lab. Being able to simulate the digital baseband with the RF front-end will be quite useful in designing a robust communication system before we put any hardware together. Remember that as cool as physical prototypes are, they're typically quite expensive and time-consuming to build.

Finally (or fifth!), it builds trust in Simulink and SimRF. This one explains why we invested the time to do this. The fact that we could construct this model in a relatively short amount of time, and that it matches lab measurements, makes us confident that the simulation software tools are both capable and accurate.

I encourage you to take a look at the documentation and videos on this page to get more information on this package.

Comments

As always, your thoughts and comments here are greatly appreciated.


Get the MATLAB code

Published with MATLAB® R2014b

Quad-Sim: You Really Can Use Simulation for Design

$
0
0

Greg's pick this week is Quad-Sim by David.

There have been a bunch of models for multiple-rotor flying machines floating around the File Exchange, but this entry is far and above the most comprehensive entry I have seen.

It has neat, sophisticated Simulink models of the dynamic system behavior; graphical user interfaces for data analysis, data formatting, and visualization; and finally, it includes the notion of model development and verification.

To me this entry represents the power MATLAB and Simulink can provide to the design of complex dynamic systems such as flying machines.

This video summarizes it very nicely.

Contents

Organization is Everything!

Okay, maybe not everything. At some point you need to have substance in order to be useful. And documentation helps create the context in which to operate the tools. The Quad-Sim entry has all of these. The content of this entry is well organized in a way which helps detail what exactly is available within the content of the Quad-Sim tools.

In addition, the Simulink simulation models are well organized in terms of functional hierarchy. In other words, elements contained within the Simulink model are placed in well-named subsystems and libraries according to their functionality. There are clear partitions between inputs, controllers, plant dynamics, sensors, etc.

It sounds simple, but it makes all the difference. The organization of the content and the models alone made it very easy for me to understand, and start using the models.

I am definitely a proponent of Simulink as a platform for the development of dynamic systems and their control. Because I believe in Simulink as a design tool, it also means I spend a great deal of time and effort thinking about how to create and share models and supporting materials.

I have a self-imposed bias that makes it difficult for me to demonstrate or promote models that are messy, or otherwise difficult to understand. As such, I struggle to find File Exchange entries that involve Simulink, especially because Simulink is designed as a graphical tool, and therefore the form of the simulation model is at the forefront.

Documentation: The Asset Everyone Wants to Use, but No One Wants to Produce

If David and his colleagues somehow believe that the world of development and design will always be well thought-out and documented, they will soon be in for a shock.

Generally deadlines of overlapping projects loom, and we must produce functionality to meet specific needs now, and worry about documentation later (if at all).

As all of us know, being a user of a tool we want clear, well though-out documentation that not only has details of how to use a particular tool or feature, but examples of its use. Finally understanding the underlying nature of a particular feature helps us better use features appropriately. But as many of us are some sort of developer or designer, we also are aware of the effort required to produce such rigorous documentation.

The Quad-Sim not only has well written documentation on specifically how to use the included tools (e.g. Modeling GUI):

It also has detailed explanations of various experimental processes so they can be reproduced, and the tools can be understood relative to a specific design context (e.g. Motor Modeling Hardware).

Verification: Proof the Model Is Worth Building

The fact that David and his colleagues bothered to attempt and verify their system models really excited me. I know it sounds like maybe I should reconsider my priorities in life, but I couldn’t help showing some of my colleagues in my hall the Quad-Sim entry. Nor could I hide my excitement in seeing users spend the time to make sure their models are correct.

A model is an invaluable tool for design and analysis of complex systems. But what good is the use of that model for design if it is “wrong”?

Certainly “wrong” is a relative term. A model is always wrong, otherwise it’s not a model. I am specifically referring to the notion that a model must capture the important attributes of a system sufficiently with enough accuracy to be useful for the purposes of the design and analysis.

Maybe I should say: what good is using a model that is “too wrong”?

Code Generation for the Controller is an Excellent Next Step

It wasn’t clear to me that David and his colleagues used automated C-code generation from Simulink to implement the controller on the Arduino processor. Control systems like this are ideal candidates for our C-code generation technology from Simulink.

In my opinion, the Quad-Sim entry covers the more important aspects of the design process. It’s more important to get it right, without damaging people or equipment, than to implement quickly.

Seeing as that part of the process has been taken care of, it seems natural to me to automate the process of generating the control algorithm from the Simulink model to be implemented on the Arduino processor.

This enables two key design process attributes:

  1. Prevent the introduction of errors when translating designs from Simulink to C-code
  2. Permit design iterations to be tested in simulation, and then quickly implemented

Both of these help save demand on software development resources, especially as designs become more complex, and design cycle iterations become shorter. We do offer an Arduino Hardware Support Package that enables you to include connections of the model to hardware peripherals such as analog-to-digital converters (ADC), and go all the way from the Simulink model to the executable running on the hardware with a single button click.

This is fine if you can represent the entire system software in Simulink. But in most cases, engineers want to integrate the control algorithm with some existing software framework. For this, you can leverage Embedded Coder to generate the C-code and then integrate the resulting code into your software project.

Okay That’s Enough Out of Greg Already!

I have lots of other comments and notions about this entry, but I’ll save that for other discussions. Let us know what you think.

Comments

If you would like to leave any comments regarding this post, please click here.


Get the MATLAB code

Published with MATLAB® R2014b

Simulink Dual Gravity Drained Tank

$
0
0
Will's pick this week is Simulink Dual Gravity Drained Tank by John Hedengren.

How often do you find a File Exchange submission accompanied by a video tutorial? I've only explored a small fraction of all the content on the File Exchange, but in my limited sampling, I have to say that this is the first contribution with such an achievement. The model is simple enough: a prediction of the water level of two tanks as they are filled and drained. But as John notes in his video, the model doesn't jump up and scream "I'm clearly two draining tanks!" when look you at it.

Can you tell that there are two tanks modeled here?

The video explains how the problem is configured and what is being calculated in a way that even someone outside the field of chemical engineering can appreciate. He also includes a clever animation of the process. As the model simulates, a MATLAB figure displays the water level in each tank.

Water level diagram

The submission also includes an Excel file with background data used to determine initial gains for a PID controller that is added to the model in the video. He demonstrates how to create a feedback loop to control water flow into the top tank, the goal being to maintain water level in the bottom tank. This is a tricky controls problem because of the long lag time before the bottom tank fills. Presumably, this is why a valve is available that enables flow directly into the bottom tank. But including it in the control system is a task left to the user.

As I reviewed the model, other thoughts came to mind on how to improve it. The tank levels are calculated using a Level- 1 MATLAB S-Function. This technique is so old that MathWorks doesn't even provide a documentation page for it. The only thing available is a discussion on how to maintain them. I recommend avoiding the S-Function and instead rely on a MATLAB Function block for the derivative calculation combined with an Integrator block. Or better yet, the whole thing could be done with Simuink blocks without MATLAB code. I'd also suggest eliminating all the Muxes and Demuxes in favor of separate signal lines or buses. So there's room for improvement, but a solid model nevertheless.

In my mind, it's material like this that the File Exchange was meant for. John combines MATLAB, Simulink, Excel, and YouTube together into an interactive educational experience. It's a lot of fun, and I hope you check it out.

Comments
Let us know what you think here or leave a comment for John.

What’s the reaction when we touch?

$
0
0
  Contact Modeling in SimMechanics

Greg's pick this week is Rolling Ball on Plane by Janne Salomäki.
Janne put together a nice example of modeling the interaction of a ball contacting a plane, rolling on the plane, and then falling off the plane.

Janne uses SimMechanics to model the geometry and motion of the ball and the plane. And then applies C-code S-Function to model the interaction between the ball and the plane. Contact modeling isn’t something SimMechanics can do, so I’m excited to see an example that shows the basic concept. I also saw an opportunity to compare using C-code and MATLAB Code to solve this particular problem.  

Contents

What is SimMechanics?

SimMechanics enables six degree of freedom (6DOF) modeling of rigid bodies in Simulink. A nice benefit is it comes with an animation feature where you can visualize the motion of the bodies. Bodies are defined in terms of mass, inertia tensor, and location for the center of mass. Connections to other bodies are defined by coordinate systems applied to the body, and placing constraints on the type of motion permitted between two coordinate systems. For example, a revolute joint only has one degree of freedom, while a gimbal joint has three degrees of freedom. 6dofJoint
In this particular case, the joint between the ball and the plane has six degrees of freedom, which means there is no restriction on the relative motion between these two bodies. Using this joint enables measurement and actuation of the relative motions between the two bodies, which is essential for modeling the contact interaction.

What is an S-function?

An S-Function is a “system function”. It is a way to create customized blocks in Simulink that can extend its functionality. People use S-Functions to for all sorts of capabilities:
  • Interface Simulink models with other software running on your computer
  • Compile an optimized block algorithm to improve performance
  • Protect intellectual property
  • Integrate existing code into a Simulink model
While S-functions can be a little tricky, especially if you are unfamiliar with the API, they interact more or less directly with the Simulink solver engine, which enables development of a wide variety of block types and capabilities. Janne uses the C-code S-function to implement the mathematical model for the interaction between the ball and the plane.

Are there other ways to do this?

There are other ways to develop the interaction model. You could of course use basic Simulink blocks, and develop the equations using Add blocks, Gain blocks, etc. Another option is to write the interaction as MATLAB-Code in the MATLAB Function block. This would enable you to test the algorithm in the flexible MATLAB environment. The MATLAB Function block is not designed to support mathematical integration. So it is often best to pass out the derivatives of the states as outputs, route them through an integrator block, and pass the result back as inputs to the MATLAB Function block. matlabFunctionBlock

How do they compare?

C-code S-Function

MATLAB Function

MATLAB Function

(Debugging Disabled)

2.15 sec

2.67 sec

2.30 sec

~

+24%

+6.8%

I thought I would try some basic benchmarking to compare some different implementations. It’s interesting to me that the MATLAB Function block is only about 7% slower. Remember that by default, the MATLAB Function block converts the MATLAB Code to C-code and then compiles it to essentially an S-Function.

MATLAB Debugging Disabled

debugSettings Leaving the debugging on certainly provides for a much bigger performance hit, but it also means you can step through the code using the MATLAB Debugger. This is a bit more difficult to do when you need to debug the C-code S-Function. I’ll leave it to you to decide if the convenience of the MATLAB Code is worth the hit in performance.

What do I like about this entry?

First, it is a neat, clean, and clear model. Both the model and the code for the S-function are done in a nice straight forward manner. I like the use of the macros in the C-code S-function to make the code easier to read by hiding some of the weird API language. What I find so fascinating is that SimMechanics handles all of the appropriate coordinate transformations, so the algorithm for the contact model is relatively simple without a lot of math to figure out the body relationships. I realize this approach might not scale well to a more general implementation of contact modeling, but I think it’s a beautiful and creative example of investigating rigid body dynamics.

Do you need contact modeling in SimMechanics?


Let us know how you would use it. Do you create S-Functions? What’s one thing you like about them? What’s one thing you dislike about them? You can leave your comments here.

Get the MATLAB code

Published with MATLAB® 8.4

Flush Your Toilet with Simulink!

$
0
0

Sean's pick this week is Auto Flush by the Techsource Technical Team.

My pick this week is something that many of us could find useful and have likely thought about at some point during the standard workday: a simple design for the controller behind an automatically flushing toilet.

Techsource's Technical Team has put together a collection of simple Simulink models to showcase getting started with Simulink and an Arduino Board, a low cost embedded target.

This particular one caught my attention for two reasons. First, the main model is called 'UltraSonic_Pee.slx'. If you want to grab someone's attention, well, a model name like this is a good way to do it. Second, this simple model is extensible so that I can include my own sensor input and simulate different flushing scenarios. Let's see how this is done.

Here's the original model:

For my Arduino board, I only have the LEDs and a simple DC motor. However, I have a Lego NXT that has an ultrasonic distance sensor and a DC motor that I can use. I don't know if the DC motor is actually powerful enough to pull down the handle on the urinal, but I'm going to try.

The first thing I am going to do is replace the two Arduino Blocks with a Lego Motor block from the Lego Support Package. Support packages are additional functionality you can freely download to allow MATLAB and Simulink to take advantage of your hardware.

One of the beautiful things about Simulink is the ability to have Variant Subsystems. These allow you to either have different fidelity models or to substitute in different components. My second step is going to be to make the Signal Builder block into a variant subsystem so I can have my Lego distance sensor as an input instead. This is really important for the modeling aspect. I'm fortunate enough right now to have access to the hardware. But if I did not, I could still develop and test my algorithms by simulating the hardware with other signals that I could build or historical data from other tests.

Next I'm going to simulate this in External Mode. This means that the model will be running in Simulink but be grabbing data from the sensors and controlling the motor. By running in External Mode we can use the full power of the MATLAB and Simulink platforms to analyze the results of the model and see it running in semi-real-time. By doing this, I discovered that I needed a couple of gains on the signals to control how close one needs to get to trip the sensor.

Once the model has been tested, we can then embed the controller onto the Lego. One button click in Simulink generates the equivalent C-code, compiles it, and moves it onto the Lego.

Now we're ready to put this to the test!

The looks we got from fellow restroom patrons and the cleaning staff were pretty priceless.

Next I got my friend Adam, who is relocating from Massachusetts to California shortly, to test it out. The control algorithm that Techsource used is to have a preflush and a postflush - not the most environmentally friendly of algorithms but we waste no water in simulation. Since this is no longer simulation, I figured Adam should enjoy this luxury while still being on the east coast.

Unfortunately, the Lego motor was not strong enough to pull the handle down and instead lifted the whole robot up. But hey, not too shabby for an hour's worth of work.

Comments

Give it a try and let us know what you think here or leave a comment for the Techsource Technical Team.


Get the MATLAB code

Published with MATLAB® R2015a


Mission On Mars Robot Challenge 2015 – France

$
0
0
Will's pick this week is Mission On Mars Robot Challenge 2015 - France by Pascale Naillard.

Pascale works in the MathWorks Paris office and helped coordinate a student competition: the Mission on Mars Robot Challenge. The goal was to design an algorithm that would drive a rover to a points of interest as quickly as possible while avoiding obstacles. And while it would have been fun to land a fleet of rovers on the Martian surface, the finals were held in Lyon in a terrain mockup.

Of course before you test in the field, the prudent thing to do is to fine-tune your design in simulation first. MathWorks provided competitors with a starter model in Simulink. As I would expect from any of my coworkers, this model is very well organized and follows many modeling best practices. All the files are managed as a Simulink Project, which makes it easy to share and get others using it quickly. Once you load the project and open the main model, this is what you discover:

Rover seeking sites


The model is comprised on a subsystem that models the rover's control system, dynamics, and sensors. A separate subsystem scores the rover's performance. These subsystems served as a foundation that enabled competition teams to improve on the third subsystem: InputProcessing. In effect, this was the guidance algorithm to the rover's software.

The guidance algorithm for the rover is managed by a Stateflow chart, which contains a state machine that defines the pathing logic. If you're unfamiliar with state machines, we produced a tech talk series on the subject that's worth checking out (I hear the presenter is phenomenal). In a nutshell, state machines are a useful way of expressing a system with different modes of operation that you switch between. When you use Stateflow to design your state machine, you can visualize the mode switching as you simulate:
Rover Navigation state machine


While this looks pretty, the state machine employs an intentionally poor algorithm. This is a sample of a simulated three minute attempt to locate all points of interest (marked as circles). The rover doesn't know where the circles are; it has to scan for them with a camera whose range of visibility is shown with the blue trapezoid.
Rover seeking sites


As you can see in the animation, there's no strategy employed to systematically sweep through the field and find points of interest. The rover randomly spins around, moves forward on occasion, and (if it's lucky) find a circle. Even when that happens, it sometimes loses track of what it found. The animation shows a case were it identified a point but then drove right past it. The end result of the three minutes is unimpressive. The rover wastes a lot of time covering the same ground and ultimately misses one of the six points of interest.
Rover final results


Think you could design a better algorithm? Well that was the point of the competition. And even though the challenge is over, this is still a fun model to play around with.

Comments
Let us know what you think here or leave a comment for Pascale.

Design Oriented Trebuchet Model with SimMechanics

$
0
0
Will's pick this week is Design Oriented Trebuchet Model with SimMechanics by James Allison.

We've all been there: wanting the glory of owning a trebuchet but unable to fulfill our dream due to a lack of time, budget, and firing range access. Well James has given us the next best thing with a virtual trebuchet. Configure the parts, run the simulation, and watch your projectile fly.



The model is constructed of about 270 Simulink blocks.
Top level of the model

The "meat" of the model is in 46 blocks from the Physical Modeling tool SimMechanics. We can observe the blocks for the counterweight, sling, and projectile if we zoom in on a portion of the model.
Top level of the model

Some of these blocks specify the properties of the component. Double-clicking on the projectile reveals that James opted for a 0.624 inch radius sphere with a density of 3000 kilograms per cubic meter (about the density of aluminum). Other blocks specify the physical relationship between components, like the R3 revolute joint that defines a degree of freedom between the sling and projectile.

Projectile properties


If we change the properties of these blocks, we will get a different result when we run the simulation. But rather than hunting and pecking for properties of interest, James has provided a user interface for commonly adjusted properties.

App's User Interface


With this configuration, I was able to throw my projectile 123 feet. Can you do any better? One setting that helped was the addition of wheels. In an equation-based simulation, a lengthy derivation could potentially be required every time we altered the mechanical configuration like this. But with SimMechanics, you aren't burdened with deriving equations. All you have to do is add new blocks, specify their properties, and get right back to simulating.

So how does James get from the SimMechanics diagram to the animation at the top of the blog? He's tapping into SimMechanics' animation feature to pull it off. Getting animation of a sphere or cylinder is straightforward, but his counterweight, uprights, arms, and base all have unusual, custom geometries. He's able to incorporate the geometries into the animation thanks to STL files. He must have designed these pieces in a CAD tool and imported them into SimMechanics.

All in all, this is a very well assembled File Exchange contribution. Kudos to James on a job well done!

Comments
Let us know what you think here or leave a comment for James.

Device Drivers

$
0
0

Richard is a Consultant at MathWorks focused on the Embedded Coder product for code generation, primarily in the Aerospace industry.

Richard's pick this week is Device Drivers by Giampiero Campa.

Pick

My pick this week is Developing Simulink Device Driver Blocks: Step-by-Step Guide and Examples .

One of the many capabilities of Simulink is the ability to generate code for an embedded application. However, when hardware is involved, the complexity goes up exponentially. As with any embedded system, the core algorithm must interface with hardware components to be effective. These can range from simple I/O, to complex sensors such as a GPS. In addition, there are myriad communication channels that can be used such as serial, A2D/D2A, and other communication protocols (i.e. I2C). In all of these cases, there are some low-level hardware routines that provide a bridge between the hardware and the core algorithm - device drivers.

That being said, the issue then becomes how do you call these low-level routines? One way would be to write all of the code by hand. This is not very efficient and not recommended. Another would be to write the base code for the application by-hand, including the interface to the hardware, and calling the algorithmic code produced via Simulink. In reality, this is an approach adobted by many users, particularly where it is a highly complex system with many aspects, with a limited number being generated from Simulink. However, for our case, we want to be able to generate code from our Simulink model and run it directly on our hardware, especially if we are using the Run on Target Hardware feature in Simulink rather than using one of the Coder products. To do this, we need a block in Simulink that will translate into a call to the appropriate device driver.

That is where this post comes into play. This post walks you through the steps needed to create these device driver blocks. In particular, the post provides information on the various approaches that can be used such as S-Function blocks and MATLAB Function blocks, and the pros/cons of each approach. The post provides examples for creating blocks for an Arduino board, but the approach is applicable to any board. This is supported by the number of additional posts that were inspired by this post for a wide range of boards and applications.

Once a device driver block is created, the user can place it in a Simulink library for reuse. In this way, various device driver blocks can be packaged and shared for use in different applications. Many of the Target Support Packages leverage this capability.

Comments

If you need to interface with hardware, this post can provide the necessary guidance to allow you to create a set of hardware specific blocks. Give it a try and let us know what you think here or leave a comment for Giampiero.


Get the MATLAB code

Published with MATLAB® R2016a

Data Acquisition Tool

$
0
0

Sean's pick this week is Data Acquisition Tool by Isaac Noh.

Data Acquisition Hardware

Have you ever wanted to bring data directly from hardware into MATLAB or control something via a data acquisition board?

Working with data acquisition hardware was my very first project in MATLAB back in the winter of 2008. I had a miniature load frame, transparent to x-rays, for applying a load to a concrete cylinder. There were three sensor inputs: two displacements, and force, and one output: a voltage to a piezoelectric actuator that applied a force. Here's a figure from my thesis:

I built a user interface in GUIDE to allow me to apply the load while recording and plotting the signals. To complicate matters, the session based interface for the Data Acquisition Toolbox didn't exist yet, so I was also doing everything with timers on my own.

I can only imagine how much easier it would've been with this app. I no longer have access to the load frame, so instead here's an example getting data from an ADALM1000, a low cost data acquisition device.

Let's control it with the app. First, I'll just get connected and pull some data from the attached RC circuit. Note I previously had to install the hardware support package for this board.

Seems to work, great!

Now I want to output some data to it. There are two channels, the first will be a sine wave and the second a cosine wave. The board can take 0-5V so add 1 to the waves keep them positive.

t = linspace(0,8*pi,100000)';
x = [sin(t) cos(t)]+1; %

In order to get them into the output, we simply pick the variable:

And then run the session:

From here, the data can be exported or equivalent code can be generated from the file menu to automate this acquisition session.

My only point of feedback is that error messages are not all exposed via dialogs. For example, the first time I selected x with the range -1:1, it errored at the command line with a useful message that I didn't see because the app was maximized.

Going back to my use case in college, I was trying to control load, with displacement so that the loading rate would be roughly linear. To do this, I ran a bunch of experiments and fit an equation to the load v. displacement curve for many cylinders. At the time, I knew nothing about Simulink or how it could help me. If challenged with the same task today, I would likely use the data acquisition blocks in Simulink R2016b to control the actuator. This would allow me to then use the PID block and its tuning capabilities to accomplish what I was doing much more quickly.

For nostalgia's sake, I put together a quick a model of the system.

Comments

Do you work with data acquisition hardware? Give it a try and let us know what you think here or leave a comment for Isaac.


Get the MATLAB code

Published with MATLAB® R2016b

What’s the reaction when we touch?

$
0
0
  Contact Modeling in SimMechanics

Greg's pick this week is Rolling Ball on Plane by Janne Salomäki.
Janne put together a nice example of modeling the interaction of a ball contacting a plane, rolling on the plane, and then falling off the plane.

Janne uses SimMechanics to model the geometry and motion of the ball and the plane. And then applies C-code S-Function to model the interaction between the ball and the plane. Contact modeling isn’t something SimMechanics can do, so I’m excited to see an example that shows the basic concept. I also saw an opportunity to compare using C-code and MATLAB Code to solve this particular problem.  

Contents

What is SimMechanics?

SimMechanics enables six degree of freedom (6DOF) modeling of rigid bodies in Simulink. A nice benefit is it comes with an animation feature where you can visualize the motion of the bodies. Bodies are defined in terms of mass, inertia tensor, and location for the center of mass. Connections to other bodies are defined by coordinate systems applied to the body, and placing constraints on the type of motion permitted between two coordinate systems. For example, a revolute joint only has one degree of freedom, while a gimbal joint has three degrees of freedom. 6dofJoint
In this particular case, the joint between the ball and the plane has six degrees of freedom, which means there is no restriction on the relative motion between these two bodies. Using this joint enables measurement and actuation of the relative motions between the two bodies, which is essential for modeling the contact interaction.

What is an S-function?

An S-Function is a “system function”. It is a way to create customized blocks in Simulink that can extend its functionality. People use S-Functions to for all sorts of capabilities:
  • Interface Simulink models with other software running on your computer
  • Compile an optimized block algorithm to improve performance
  • Protect intellectual property
  • Integrate existing code into a Simulink model
While S-functions can be a little tricky, especially if you are unfamiliar with the API, they interact more or less directly with the Simulink solver engine, which enables development of a wide variety of block types and capabilities. Janne uses the C-code S-function to implement the mathematical model for the interaction between the ball and the plane.

Are there other ways to do this?

There are other ways to develop the interaction model. You could of course use basic Simulink blocks, and develop the equations using Add blocks, Gain blocks, etc. Another option is to write the interaction as MATLAB-Code in the MATLAB Function block. This would enable you to test the algorithm in the flexible MATLAB environment. The MATLAB Function block is not designed to support mathematical integration. So it is often best to pass out the derivatives of the states as outputs, route them through an integrator block, and pass the result back as inputs to the MATLAB Function block. matlabFunctionBlock

How do they compare?

C-code S-Function

MATLAB Function

MATLAB Function

(Debugging Disabled)

2.15 sec

2.67 sec

2.30 sec

~

+24%

+6.8%

I thought I would try some basic benchmarking to compare some different implementations. It’s interesting to me that the MATLAB Function block is only about 7% slower. Remember that by default, the MATLAB Function block converts the MATLAB Code to C-code and then compiles it to essentially an S-Function.

MATLAB Debugging Disabled

debugSettings Leaving the debugging on certainly provides for a much bigger performance hit, but it also means you can step through the code using the MATLAB Debugger. This is a bit more difficult to do when you need to debug the C-code S-Function. I’ll leave it to you to decide if the convenience of the MATLAB Code is worth the hit in performance.

What do I like about this entry?

First, it is a neat, clean, and clear model. Both the model and the code for the S-function are done in a nice straight forward manner. I like the use of the macros in the C-code S-function to make the code easier to read by hiding some of the weird API language. What I find so fascinating is that SimMechanics handles all of the appropriate coordinate transformations, so the algorithm for the contact model is relatively simple without a lot of math to figure out the body relationships. I realize this approach might not scale well to a more general implementation of contact modeling, but I think it’s a beautiful and creative example of investigating rigid body dynamics.

Do you need contact modeling in SimMechanics?


Let us know how you would use it. Do you create S-Functions? What’s one thing you like about them? What’s one thing you dislike about them? You can leave your comments here.

Get the MATLAB code

Published with MATLAB® 8.4
Viewing all 33 articles
Browse latest View live