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
- S32K144EVB: S32K144 Evaluation Board
- Model-Based Design Toolbox for S32K1xx Series Version 2018.R1
- MATLAB R2018a.
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:
- Solver Selection
- Type: Fixed-step
- Solver: discrete (no continuous states)
- Fixed-step size (fundamental sample time): 0.001 (1ms)
- Tasking and sample time options
- Periodic sample time constraint: Unconstrained
- Enable the "Treat each discrete rate as a separate task" checkbox
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:
- On the "Main" tab:
- Select the "Treat as atomic unit" checkbox
- Set the appropriate Sample time for each Subsystem
- 0.001 for 1 ms
- 0.010 for 10 ms
- 0.100 for 100 ms
- On the "Code Generation" tab
- Select Function packaging as "Reusable Function" and leave all the parameters as default
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.