Simulink has a mechanism to generate tasks at different rates within your model, this example shows a way to create three tasks running at 1ms, 10ms and 100ms each, this may be helpful to someone looking to implement this type of systems without having to reinvent the wheel.
Mathworks has some articles with more detail on Modeling for Multitasking Execution, you can visit their website for more details. This example is intended to be a simple tutorial on how to create a simple multitasking model and toggle three digital outputs at different rates as defined in each task.
This example uses
Starting from a blank model then you first must define the step size, go to Model Configuration Parameters on the menu as shown below, or Ctrl + E
Make sure “Solver” is selected on the left menu, and set the settings as shown below:
You can change the settings on the solver to suit your specific project, as always Mathworks help is a great resource.
Next I will create three subsystems and name each one with the rate at which they will be running.
Then, right click on each Subsystem block and select the "Block Parameters (Subsystem)", on the window change the following:
At the end you'll have your three atomic subsystems with the sampling rate defined for each task.
Inside each task subsystem, place a GPO Write to toggle an output. I used the Color LED so I could have the LED changing accordingly.
For the 1ms task (Red LED):
For the 10ms task (Blue LED):
For the 100ms task (Green LED):
Once the system is built, Simulink uses a color coded scheme to differentiate the blocks running at a different rate as you can observe below:
If you take a look under the hood into the generated code you can see that Simulink generates some functions multitasking_step0, multitasking_step1 & multitasking_step2, each function is called according the Rate Monotonic Scheduler implemented by the Simulink coder.
Below is the oscilloscope capture from the PTD15, PTD0 & PTD16 outputs:
I set up some measurement boxes to measure the positive pulse duration on each signal, as you can see the pin is toggling at the expected rates of 1ms, 10ms and 100ms respectively.
Hopefully this example is helpful to someone in this forum.
Thank you gramirezv for this insightful article ! It's a great addition for our featured content. Very detailed explanation with a hands-on example as well (+oscilloscope screenshot bonus!).
Thank you for having the initiative to write such an article and share knowledge with all the members of our community! Hopefully you've also inspired others to share their insights, too.