STM 32 Manual
STM 32 Manual
Contents iii
1 Quick Start 3
Requirements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
1
Contents
2
1
Quick Start
Requirements
The PLECS STM32 Target Support Package currently supports the
STM32G431 and STM32G474 microprocessors from the STM32G4x tar-
get family, and the STM32F334 and STM32F303 microprocessors from the
STM32F3x family.
In order to use the PLECS STM32 Target Support Package you will
need:
• a host computer (with Microsoft Windows or Mac OS X)
• PLECS Blockset or Standalone 4.6.1 or newer
• PLECS Coder
If you have not done so yet, please download and install the latest PLECS re-
lease on your host computer.
targets. You will also see these targets available in the Coder + Coder op-
tions... window in the drop-down menu on the Target tab.
Another folder labeled projects is included in the ZIP archive. The contents
of this folder is required only when the PLECS Coder is configured to generate
code into STM32CubeIDE projects. The projects/stm32xx.zip files contain
Cube IDE projects that are used in conjunction with the embedded code gener-
ated from PLECS.
A set of basic demos is also included with the STM32 Target Support Package.
4
Build and Deploy Generated Code
1 Open OCD The STM32 Target Support Package includes the Open On-Chip
Debugger package and GDB server, supporting the ST-LINK debug link out
of the box (no external tools needed).
2 Segger J-Link Segger debug probes offer superior throughput and are also
supported by the STM32 Target Support Package – see below on how to in-
stall the Segger tools.
Note that the debug link can also be used in PLECS External Mode to com-
municate with the target while it is executing the generated code. It is in Ex-
ternal Mode that the high throughput of J-Link is most noticeable.
To deploy code to a STM32 target from PLECS, navigate to the PLECS Coder
Options + Target window, select the target MCU. Uncheck the Generate
code only parameter, then choose the desired Programming interface from
the dropdown menu. The default programming interface is Open OCD.
Download and install the latest version of STM32CubeIDE from the STM
website. This is available at the following location:
https://www.st.com/en/development-tools/stm32cubeide.html
5
1 Quick Start
Figure 1.1: Configuring the target support package and external tool paths
Projects into Workspace, choose the zip archive in the projects folder that
corresponds to the desired target. You will notice a new project created in your
workspace.
6
Start the External Mode
into the STM32CubeIDE project directory field and click Build. Note
that {workspace_loc} refers to the location of the imported project in the
STM32CubeIDE workspace. You will notice several new files created in the
${workspace_loc}/cube_g4xx/cg or ${workspace_loc}/cube_f3xx/cg direc-
tory. Then, proceed to build and debug your project as you would a normal
STM32CubeIDE project. The project will not compile without first generating
code from PLECS.
Note that it is necessary to manually delete the contents of the
${workspace_loc}/cube_g4xx/cg or ${workspace_loc}/cube_f3xx/cg
folder when generating code for a new subsystem of a different name, as the
STM32CubeIDE builder will build all files in this folder, including old files.
7
1 Quick Start
show a small square indicating the trigger level and delay. If the level or de-
lay are outside the current axes limits, a small triangle will be shown instead.
Drag the trigger icon to change the trigger level; drag it with the left mouse-
button pressed to change the trigger delay. Both parameters can also be set in
the External Mode dialog.
Note While a trigger channel is active, the Scope signals are only updated
when a trigger event is detected.
While the PLECS model is connected via the External Mode, the model is
locked against modifications. To disconnect from the MCU and other External
Mode connections, click on the Disconnect button or close the Coder Options
dialog.
Parameter Inlining
Certain values on the target device can be changed in real-time, when con-
nected to the target device via the External Mode, if the component is added
to the "Exceptions" list found in the Parameter Inlining tab of the Coder
options... window, prior to building the model. Changes in the parameters
will be reflected in the Scope traces once they take effect.
8
2
Overview
As a separately licensed feature, the PLECS Coder can generate C code from
a simulation model to facilitate embedded code generation. Plexim provides
and maintains target support packages (TSPs) for specific processor families.
A TSP enables the PLECS Coder to generate code that is specific to a partic-
ular hardware target such as the STM32 family of MCUs or the PLECS RT
Box. With the PLECS Coder and a TSP, embedded control code can be gen-
erated, compiled, and uploaded to the target device directly from the PLECS
environment with minimal effort. Furthermore, the embedded control logic
can be tested extensively inside the PLECS simulation environment prior to
real-time deployment.
10
Control Task Execution
Task triggers are generated at the end of injected conversions, PWM counter
underflow and overflow events, or the Timer block events. The task trigger
that connects to the Control Task Trigger component will trigger one execu-
tion of the digital control loop at the nominal base sample rate.
Additionally, the PLECS Coder and the STM32 TSP allow the user to gen-
erate multi-tasking code for the STM32 family of MCUs. For further infor-
mation, refer to the "Code Generation" section in the PLECS User Manual.
Multi-tasking code unlocks processing power for controls regulating multi-
ple system outputs with dynamics on a range of time-scales. Using the Task
library component, 15 additional tasks that execute at different rates (not
including the base task) can be specified, preserving processor time for the
fastest, highest priority control task (base task) in the application.
Multi-tasking code generation is configured in the Scheduling tab of the
Coder + Coder options... dialog. By changing the Tasking mode to multi-
tasking and the Task configuration to specify, the sample time for each
task can be configured. The base sample time is always equal to the Dis-
cretization step size. The Sample time setting for lower priority tasks
must be an integer multiple of the base sample time.
In a multi-tasking mode, the Control Task Trigger component triggers the
base task associated with the nominal base sample time.
Note In the following sections, unless specified otherwise, control task and
base task can be considered synonymous.
11
2 Target Support Architecture
In cases where the PWM carrier frequency or ADC and task trigger periods
cannot be achieved exactly, the default behavior is to generate an error mes-
sage displaying the desired frequency or step size and the closest achievable
value. Adjusting the Frequency tolerance parameter overrides this behavior
and configures the PLECS Coder to automatically select the closest achievable
frequency. The Frequency tolerance can be configured in the mask param-
eters of the Timer, PWM, and Peak Current Controller (PCC) target support
library blocks.
The discretization step size configured in the General tab of the Coder +
Coder Options will also generate an error if the exact step size cannot be
achieved. This impacts the nominal period of the task trigger and introduces
a numerical inaccuracy since C code derived from the model executes at a dif-
ferent rate than was assumed during model discretization. The Frequency
tolerance parameter relating to model and control task discretization can be
adjusted in the General tab of the Coder + Coder Options + Target win-
dow.
Note Explicitly defined trigger systems require that the Control Task Trig-
ger’s nominal base sample time parameter agrees with period of the task trig-
ger input signal.
12
Control Task Execution
In a basic project without an ADC or PWM component from the target support
library, the task trigger must be generated by a generic Timer. The schematic
below shows a simple application where a digital output is toggled at a fixed
rate.
The explicit representation of the control task execution includes a Timer
component that generates the input signal for the Control Task Trigger. The
nominal base sample time of the Control Task Trigger must agree with the
Timer task frequency. In the implicit representation the PLECS Coder will
configure the Timer and Control Task Trigger automatically based on the Dis-
cretization step size parameter set in the Coder + Coder Options + Gen-
eral menu.
NOT ST NOT ST
Digital Digital
-1
Out -1
Out
z z
LED LED
Port: B Port: B
Pin: [7] Pin: [7]
ST
ADC
Timer
Task
Explicit Implicit
Control task execution can be synchronized with the PWM carrier, and the
repetition counter period determines how many events need to occur before
a trigger is generated. When the carrier type is symmetrical, for even values
of repetition counter period, the interrupts will occur at the carrier underflow
or overflow events. Underflow and overflow events correspond to PWM car-
rier reaching the respective carrier minimum or carrier maximum values. The
task trigger is configured in the Trigger tab of the PWM component.
In the explicit representation, the PWM task trigger output is connected to
the Control Task Trigger component, such that execution of the digital control
loop is synchronized with the PWM carrier. If the schematic does not include
13
2 Target Support Architecture
a Control Task Trigger or an ADC component, then the PLECS Coder will im-
plicitly select the most appropriate source for the task trigger. First, the PWM
generator that can achieve the control task frequency with the highest preci-
sion is chosen, starting from the lowest PWM number. If the control task fre-
quency cannot be achieved exactly using a PWM carrier, then the implicit trig-
ger logic will determine if more accurate task execution can be achieved with
the Timer. The most accurate source for the control task interrupt is then se-
lected.
The task trigger will default to triggering on underflow and overflow when the
task trigger is set to disabled in the PWM Trigger tab and the trigger is im-
plicitly defined.
NOT ST NOT ST
Digital Digital
-1
Out -1
Out
z z
LED LED
Port: B Port: B
Pin: [7] Pin: [7]
ST ST
14
Control Task Execution
If the schematic includes an ADC but no PWM generators, then the ADC
start-of-conversion must be triggered by the Timer. In this case, the control
task can be triggered by the ADC end-of-conversion or the Timer. When the
ADC end-of-conversion is the source of the Control Task Trigger input, as
shown in Figure 2.3, then the control loop interrupt will occur after all ADC
results registers are updated with the latest measurement values.
The implicit implementation automatically configures the Timer to periodi-
cally trigger the ADC start-of-conversion. The ADC trigger period is set by the
Discretization step size parameter found in the Coder + Coder Options +
General menu. The ADC unit with the greatest number of channels will trig-
ger the control task.
NOT ST NOT ST
Digital Digital
-1
Out -1
Out
z z
LED LED
ST Port: B Port: B
ADC
Pin: [7] Pin: [7]
Timer ST
Task ST
ADC 0.0000
Timer ADC 0.0000 Task
Freq: Fdisc Task
Analog In
Analog In (Triggered)
(Triggered) Control Task
Trigger
Explicit Implicit
Figure 2.4 shows the explicit and implicit implementations of the control task
being triggered by the ADC via the PWM. The sequence of events begins when
the PWM carrier reaches an underflow or overflow triggering the start-of-
conversion signal for the first ADC channel. The ADC channels are sampled
and updated sequentially until the result register of the final ADC channel is
updated. Once all ADC results are available, the ADC end-of-conversion inter-
rupt triggers the control task. This arrangement synchronizes the ADC start-
of-conversion with the PWM actuation and ensures the ADC results registers
are updated prior to executing the control loop.
15
2 Target Support Architecture
When both ADC and PWM components are included in any schematic, the
PLECS Coder will implicitly select the the PWM generator with the highest
control task accuracy as the ADC trigger. If the PWM generators cannot trig-
ger the ADC at the exact target frequency, then the Timer will be used if it is
more accurate. The control task will always be triggered by the ADC end-of-
conversion signal.
NOT ST NOT ST
Digital Digital
-1
Out -1
Out
z z
LED LED
Port: B Port: B
Pin: [7] Pin: [7]
0.0000 0.0000
ST ST ST ST
ADC
ADC PWM ADC PWM
Task Task
Controller Controller
Analog In PWM Analog In PWM
(Triggered) CarrierFreq:Fdisc (Triggered) CarrierFreq:Fdisc
Control Task RepCtrPeriod:2
Trigger RepCtrEvent:Underflow
Explicit Implicit
Figure 2.4: Basic model with control task triggered by PWM via ADC
16
Control Task Execution
The control task interrupt can execute at integer multiples of the PWM car-
rier frequency, and for a symmetric carrier the control task can be triggered at
twice the PWM carrier frequency.
Figure 2.5 shows a case where the discretization frequency is Fdisc , the sym-
metric PWM carrier period is Tsw = 2/Fdisc Hz, and the Control Task Trigger
interrupt period is TCtrlT ask = 1/Fdisc . The control task is triggered twice per
PWM period. Figure 2.6 shows the corresponding PWM carrier, task trigger,
and PWM outputs.
ST
NOT ST
Digital 0.5 PWM
Out Task
z-1
LED PWM Control Task
Port: B CarrierFreq: Fdisc/2 Trigger
Pin: [7] RepCtrPeriod: 1
Figure 2.5: PWM frequency set to half the control task frequency
Overflow
TSW
TCtrlTask
m
Underflow
PWM output
Complementary PWM
Task Trigger
(Rep. period = 1)
Figure 2.6: PWM carrier and task interrupts for PWM frequency set to half the
control task frequency
Figure 2.7 shows a case where the discretization frequency is Fdisc , the sym-
metric PWM carrier period is Tsw = 1/(2 · Fdisc ) Hz, and the Control Task
Trigger interrupt is generated at TCtrlT ask = 1/Fdisc . Figure 2.8 shows the
corresponding PWM carrier, task trigger, and PWM outputs.
The STM32 TSP by default will only update the PWM duty cycle register on
PWM underflow and overflow events to prevent data corruption. In Figure 2.8
17
2 Target Support Architecture
note the delay between the task trigger and the instant when the duty cycle,
m, is updated in the PWM module. The task trigger initiates the control task
computation, but the modulation index is updated on the next overflow or un-
derflow event after the entire control task has been completed. When the con-
trol task is triggered by the ADC end-of-conversion, then the modulation index
will update on the next overflow or underflow event after all ADC channels
are converted and the control task is completed.
ST
NOT ST
Digital 0.5 PWM
Out Task
z-1
LED PWM Control Task
Port: B CarrierFreq: Fdisc*2 Trigger
Pin: [7] RepCtrPeriod: 4
RepCtrEvent: Underflow
Figure 2.7: Schematic of PWM frequency set to twice the control task fre-
quency
Overflow
TSW
TCtrlTask
m
Underflow
PWM output
Complementary PWM
Task Trigger
(Rep. period = 4)
Figure 2.8: PWM carrier and task interrupts for PWM frequency set to twice
the control task frequency
18
Control Task Execution
NOT ST
Digital
Out
z-1
LED
Port: B 0.0000
Pin: [7] ST ST
ADC
ADC PWM
0.0000 Task
ST ST
ADC Controller2
Analog In2 PWM2
ADC PWM
(Triggered) RepCtrPeriod: 2
Task
Controller1 RepCtrEvent: Underflow
Analog In1 PWM1
(Triggered) RepCtrPeriod: 2 Control Task
RepCtrEvent: Overflow Trigger
Overflow
TSW
m
Underflow
PWM output
Complementary PWM
ADC1 Trigger
ADC2 Trigger
Task Trigger
(Rep. period = 2)
Figure 2.10: PWM carrier and interrupts for phase-shifted ADC sampling
19
2 Target Support Architecture
The embedded code generation project consists of dynamic and static code. Dy-
namic code is generated by the PLECS Coder and is overwritten each time the
Build button is clicked in the Coder + Coder options... window. Static code
is provided with the TSP and should not be modified. The PLECS Coder also
generates additional dynamic configuration files that are used by the embed-
ded application.
When the Generate code only parameter checkbox is checked, then all gener-
ated dynamic code must be placed into the ${workspace_loc}/cube_g4xx/cg
or ${workspace_loc}/cube_f3xx/cg folder of the imported STM32CubeIDE
project depending on the configured target. Otherwise, by default all gener-
ated code is included in a new output directory in the same folder as the saved
PLECS model.
20
The Code Generation Project
Base task
Additional task 1
Background task
1 2 3 4 5 6
LED_task
NOT ST
ST
Digital
0.5 PWM
Out
z-1 Task
LED PWM Control Task
Port: B Trigger
Pin: [7]
Figure 2.12: Example of an additional LED task along with a base PWM task
If the base task is still executing when a second control task interrupt is
received, then the processor will halt and an assertion will be generated.
Similar behavior occurs if a low priority task does not complete by the
time it is scheduled to execute again. Assertions can be monitored using
STM32CubeIDE debug tools.
21
2 Target Support Architecture
Figure 2.13 shows the architecture of the embedded project included with the
STM32 TSP. At the top of the software stack is an application layer consist-
ing of the main application and the base and additional tasks. Next, there
is FreeRTOS™, a real-time operating system that provides a rate mono-
tonic scheduler for the nested control tasks, as previously described, and a
processor-in-the-loop (PIL) framework that acts as middleware for External
Mode communication with the PLECS application on the user PC. The hard-
ware abstraction layer (HAL) provides a hardware agnostic interface between
the application and chip specific configuration settings. This ensures code
portability between different processor platforms. The hardware specific func-
tion calls utilize the STM32 drivers to configure the MCU and key peripher-
als. At the bottom of the stack is the embedded hardware which includes the
MCU, peripheral devices, and other onboard accessories.
Embedded Hardware
22
3
The Target page contains code generation options which are specific to the
STM32 Target Support Package.
General
Use internal oscillator Selects the on-chip oscillator as the clock source.
The clock frequency is automatically specified based on the target device.
External ADC reference Specifies the external reference for VREF+ in volts
(V). VREF+ is the positive reference voltage for an analog input (ADC) or out-
put (DAC) signal. VREF+ range is 1.62 V ≤ VREF+ ≤ VDDA,
where VDDA is analog power supply (1.62 V ≤ VDDA ≤ 3.6 V).
Step size tolerance The desired control task frequency may not be achiev-
able based on the system clock frequency and the nominal discretization time
step. This setting configures the Coder to either Enforce exact value by gen-
erating an error when the exact control task frequency is unachievable or to
automatically Round to closest achievable value.
Generate code only Selects the option to generate code into the speci-
fied STM32CubeIDE project. STM32CubeIDE must then be used to build the
project and flash the MCU.
3 STM32 Coder Options
STM32CubeIDE project directory Specifies the target folder for code gen-
eration. The code must be generated into a pre-configured STM32CubeIDE
project. When using the STM32CubeIDE project templates provided
with the STM32 target support package, code must be generated into the
{workspace_loc}/cube_g4xx/cg or {workspace_loc}/cube_f3xx/cg folder
where {workspace_loc} refers to the location of the imported project in the
STM32CubeIDE workspace.
Programming interface Provides an option to automatically program the
target MCU from PLECS after it finishes generating and building code. Pro-
gramming occurs over the GNU debug protocol and requires a GDB server.
There are two options available:
• Open OCD Supports the Open On-Chip Debugger package and GDB server,
supporting the ST-LINK debug link out of the box (no external tools
needed).
• Segger J-Link Supports Segger debug probes, which offer superior
throughput. The Segger J-Link tools must be downloaded and installed sep-
arately.
External Mode
These options are used to configure the External Mode communication with
the target device. This choice must be configured prior to building the project.
External Mode This setting adds code to the target device that enables the
External Mode. Code size and memory consumption are increased when the
External Mode is enabled. There are two communication options available,
Serial or JTAG.
Target buffer size Specifies how much target memory (16-bit words of
RAM) should be allocated to buffering signals for the external mode. The
number of words Nw required by the external mode can be calculated as fol-
lows: Nw = Nsignals · 2 · (Nsamples + 1). If more samples are requested than
what is supported by the memory allocation, PLECS will automatically trun-
cate the scope traces to the maximal possible Nsamples value. Note, however,
that requesting more memory than what is available on the target will result
in a build error. Recommended values for this setting are in the range of [500
. . . 2000]for STM32F3xxRE or STM32G4xxRx chips. For chips that can be iden-
tified with STM32F3xxR8 the target buffer size should be in the range of [100
. . . 500].
USART Rx Port Specifies the Rx port used for the External Mode USART
connection.
24
USART Rx Pin Specifies the Rx pin used for the External Mode USART con-
nection. This pin cannot be used by other peripherals.
USART Tx Port Specifies the Tx port used for the External Mode USART
connection.
USART Tx Pin Specifies the Tx pin used for the External Mode USART con-
nection. This pin cannot be used by other peripherals.
Debug interface Provides an option to communicate with the target MCU
from PLECS after building code from STM32CubeIDE. Communication occurs
over the GNU debug protocol and requires a GDB server. There are two op-
tions available:
• Open OCD Supports the Open On-Chip Debugger package and GDB server,
supporting the ST-LINK debug link out of the box (no external tools
needed).
• Segger J-Link Supports Segger debug probes, which offer superior
throughput. The Segger J-Link tools must be downloaded and installed sep-
arately.
25
3 STM32 Coder Options
26
4
This chapter lists the contents of the STM32 Target Support library in alpha-
betical order.
4 STM32 Target Support Library Component Reference
Analog In
Purpose Output the measured voltage at an analog input channel, in continuous mode
Library STM32
Description This block configures the continuous conversion mode of the ADC peripheral.
In continuous mode, Analog In block converts the selected inputs continuously
ST without CPU intervention. The Analog In block output signal represents the
measured voltage at the ADC pin. The output is scalable and can be used
ADC
with an offset, where the output signal is calculated as input*Scale+Offset.
When the Analog input channel(s) parameter is vectorized, each input
channel is measured sequentially in the order of the input channel vector.
To convert selected inputs once per trigger, use the Analog In (Triggered)
block instead. Signal update of the Analog In (triggered) block is prioritized
over the regular Analog In block.
Parameters
Main
ADC unit
Selects the peripheral index for the ADC input when there are multiple
ADC submodules.
Cont. conversion input channel(s)
Index of the analog input channel for a specific ADC submodule. For vec-
torized input signals a vector of input channel indices must be specified.
Cont. conversion scale(s)
A scale factor for the input signal.
Cont. conversion offset(s)
An offset for the scaled input signal.
Cont. conversion acquisition time
Selects between a minimal or user specified ADC acquisition time.
Cont. conversion acquisition time value(s)
Sets the ADC acquisition time window in seconds.
28
Analog In
Offline only
Resolution
The resolution of the offline ADC model in bits. The resolution is applied
over the voltage reference range. If the parameter is left blank ADC quan-
tization is not modeled.
Voltage reference
The voltage range of the offline ADC model used to determine the ADC
resolution.
29
4 STM32 Target Support Library Component Reference
Analog In (Triggered)
Purpose Output the measured voltage at an analog input channel, in single or trig-
gered mode
Library STM32
Description This block configures the single conversion mode of the ADC peripheral. In
single mode, Analog In (Triggered) block converts the selected inputs once per
trigger. The Analog In (Triggered) block output signal represents the mea-
ST sured voltage at the ADC pin. The output is scalable and can be used with
an offset, where the output signal is calculated as input*Scale+Offset. When
ADC
the Analog input channel(s) parameter is vectorized, each input channel is
Task
measured sequentially in the order of the input channel vector.
The Trigger source parameter selects between an automatic or external
ADC start-of-conversion signal, where the external start-of-conversion signal
is connected to the ADC trigger port. If the ADC task output is the source of
a Control Task Trigger, then the control task will execute once the last ADC
channel is converted.
Although up to four injected measurements are supported by the STM32 ADC,
only up to three channels are allowed in PLECS. This is due to an ADC silicon
bug (revision Y) that can result in invalid measurements for the first channel.
As a consequence, the first measurement is always discarded and the block is
limited to a maximum of three conversions.
Parameters
Main
Trigger source
Selects an automatic or external start-of-conversion trigger.
ADC unit
Selects the peripheral index for the ADC input when there are multiple
ADC submodules.
Analog input channel(s)
Index of the analog input channel for a specific ADC submodule. For vec-
torized input signals a vector of input channel indices must be specified.
Scale(s)
A scale factor for the input signal.
30
Analog In (Triggered)
Offset(s)
An offset for the scaled input signal.
Acquisition time
Selects between a minimal or user specified ADC acquisition time.
Acquisition time value(s)
Sets the ADC acquisition time window in seconds.
Offline only
Resolution
The resolution of the offline ADC model in bits. The resolution is applied
over the voltage reference range. If the parameter is left blank ADC quan-
tization is not modeled.
Voltage reference
The voltage range of the offline ADC model used to determine the ADC
resolution.
31
4 STM32 Target Support Library Component Reference
Purpose Provide the CPU load generated by the base task as a percentage of the base
task period
Library STM32
Description This block outputs the percentage of time that is used by the base control task
with one interrupt period. In case of multi-tasking, the output corresponds to
ST the Base task load only, and does not include the load created by additional
Base Task lower-priority tasks.
1
Load
32
CAN Port
CAN Port
Library STM32
Description The block sets up a CAN (Controller Area Network) communication port.
ST The input en determines the CAN port state. Setting en to zero will force the
on
en CAN
CAN port to the bus-off state, while setting the port to 1 allows the CAN port
1
ea to transition to bus-on. A bus-off condition has to be cleared by setting the
enable signal to 0, and then back to 1.
CAN Port
The output on is 1 to signal bus-on status, 0 otherwise. The output ea is 1 to
signal error active status, 0 otherwise.
Parameters
Main
CAN interface
Selects the CAN interface to use.
CAN protocol
Selects the CAN protocol to use. CAN FD supports bit rates higher than 1
Mbit/s and payloads larger than 8 bytes.
GPIO
Tx port
Selects the port used to transmit data.
Tx pin
Selects the pin used to transmit data.
Rx port
Selects the port used to receive data.
Rx pin
Selects the pin used to receive data.
33
4 STM32 Target Support Library Component Reference
Advanced
Advanced configuration
If set to Enabled, advanced bit timing settings can be configured. When
set to Disable the bit timing will be automatically deduced from the con-
figured bit rate and sampling point. The following default configuration
will be used in this case:
• Nominal/Data rate bit length is maximized to have as much as possi-
ble time quanta to construct a bit time. This will result in a low bit rate
prescaler (BRP).
34
CAN Port
35
4 STM32 Target Support Library Component Reference
CAN Receive
Library STM32
Description The block initiates the reception of CAN messages with a given identifier (ID)
on the given CAN interface. Up to three CAN messages can be configured. On
ST reception of a CAN message the data is made available on the block output dx
as a vectorized signal of the provided frame length. The output v is 1 for one
CAN 1 id1 simulation step when new data is received, 0 otherwise. The output v has a
RX d1 width equal to the configured number of messages. The f output is only rele-
vant when CAN FD is used and configured in the CAN Port (see page 33) block.
v The output f is a vectorized signal containing the following information for
each configured message:
CAN Receive
• The first signal specifies the error state indicator. If the signal is 0 the
transmitting node is error passive, 1 when the node is error active.
• The second signal specifies whether the Rx frame is received in classic (0)
or FD (1) format.
• The third signal specifies whether the Rx frame is received without (0) or
with (1) bit rate switching.
36
CAN Receive
• Standard CAN for CAN 2.0A messages with an 11-bit ID. The standard
11-bit ID provides for 211 , or 2048 different message identifiers.
• Extended CAN for CAN 2.0B messages with an 29-bit ID. The extended
29-bit ID provides for 229 , or 537 million identifiers.
• Auto uses the Standard format if the specified CAN ID is smaller than
2047. Otherwise, the Extended format is used.
Frame length
Specifies the frame length of the CAN message in bytes. This parameter
must be specified as a vector whose length corresponds to the number of
messages.
Offline simulation
Enables or disables data inspection in an offline simulation. If set to en-
able, terminals are added to the subsystem in the top-level schematic. If
set to disable, no such terminals are added to the subsystem.
37
4 STM32 Target Support Library Component Reference
CAN Transmit
Purpose Transmit CAN messages
Library STM32
Description The CAN Transmit block sends out data on a CAN bus. The data to send
must be provided on the block input dx as a vectorized signal with data type
uint8. The length of the transmitted CAN message is determined by the
ST width of the input signal (1 to 8 bytes for CAN2.0 and 1 to 64 bytes for CAN
FD).
id1 CAN 1 Messages are either sent regularly with a fixed sample time or on demand
d1 TX when the trigger input changes. When configured for triggered execution, mes-
sages are sent when the trigger signal changes in the manner specified by the
Trigger type parameter:
rising
CAN Transmit
Data is sent when the trigger signal changes from 0 to a non-zero value.
falling
Data is sent when the trigger signal changes from a non-zero value to 0.
either
Data is sent when the trigger signal changes from 0 to a non-zero value or
vice versa.
Parameters CAN interface
Selects the CAN interface to use. The selected CAN interface must be con-
figured using a CAN Port (see page 33) block.
Number of messages
Selects the number of messages to be received.
CAN ID source
Selects whether the CAN identifier (ID) is specified as a parameter or is
supplied as an input signal.
CAN ID(s)
The ID(s) for which the block receives CAN messages. The CAN ID(s) can
be supplied as either 11-bit value(s) (for CAN 2.0A) or a 29-bit value(s) (for
CAN 2.0B). When the CAN ID source is set to Parameter, the length of
the CAN ID(s) vector has to match the number of messages.
Frame format
Specifies the frame format of the CAN messages to be transmitted. Possi-
ble values are:
38
CAN Transmit
• Standard CAN for CAN 2.0A messages with an 11-bit ID. The standard
11-bit ID provides for 211 , or 2048 different message identifiers.
• Extended CAN for CAN 2.0B messages with an 29-bit ID. The extended
29-bit ID provides for 229 , or 537 million identifiers.
• Auto uses the Standard format if the specified CAN ID is smaller than
2047. Otherwise, the Extended format is used.
Execution
Selects between regular and triggered execution.
Trigger type
The direction of the edges of the trigger signal upon which the data is
sent, as described above (for triggered execution only).
Offline simulation
Enables or disables data inspection in an offline simulation. If set to en-
able, terminals are added to the subsystem in the top-level schematic. If
set to disable, no such terminals are added to the subsystem.
39
4 STM32 Target Support Library Component Reference
Purpose Specify the base sample time and trigger for the main control tasks
Library STM32
Description The digital control loop executes at a nominal base sample time. The input to
the Control Task Trigger specifies the interrupt that triggers a control loop ex-
ecution. The source of the interrupt can be from the ADC end-of-conversion
signal, PWM counter underflow and overflow events, or the Timer block.
When a Control Task Trigger is not included in the subsystem an appropriate
trigger source is automatically determined.
In a multi-tasking mode (defined in the Scheduling tab of the Coder Options
dialog), the Control Task Trigger block triggers the Base task associated with
the base sample time.
The offline simulation will model the impact of controller discretization when
the Control Task Trigger is included. For offline simulations the Forward Eu-
ler method with the nominal base sample time is used to integrate continuous
states within the subsystem containing the Control Task Trigger. Offline sim-
ulations will use the default subsystem execution settings when the Control
Task Trigger block is not included in the subsystem.
40
DAC
DAC
Purpose Generate an output voltage from the input signal; the output voltage is calcu-
lated as input*Scale+Offset
Library STM32
Description This block generates a voltage on the DAC pin in the range of 0 V to 3.3 V. The
output is scalable and can be used with an offset, where the output signal is
ST calculated as input*Scale+Offset. Output voltage limitations can also be set.
1 DAC
41
4 STM32 Target Support Library Component Reference
Digital In
Library STM32
Description The output signal is 1 if the input voltage is higher than the high level input
voltage threshold, VIH , and 0 if it is lower than the low-level input voltage,
ST VIL . For other input voltages the output signal is undefined. Refer to the de-
Digital vice data sheet for the electrical characteristics of a specific target. During an
In offline simulation the block behaves like a simple feedthrough.
Digital In
Parameters Port
Selects the port name of the digital input channel.
Pin number(s)
Defines the pin number of the digital input channel. For vectorized input
signals a vector of input channel indices must be specified.
Input characteristic
Specifies whether an internal pull-up or pull-down resistor is connected to
the digital input.
42
Digital Out
Digital Out
Library STM32
Description The output is set low if the input signal is zero and is set high for all
other values. During an offline simulation the block behaves like a simple
ST feedthrough.
Digital
Out
Parameters Port
Selects the port name of the digital output channel.
Pin number(s)
Defines the pin number of the digital output channel. For vectorized out-
put signals a vector of output channel indices must be specified.
Output characteristic
Specifies whether an internal pull-pull or open drain resistor is connected
to the digital output.
43
4 STM32 Target Support Library Component Reference
Edge Counter
Library STM32
Description The Edge Counter block counts edges of an external signal. It can be config-
ured to count rising or falling edges only or both. The output of this block
then shows the counter value at the time it was read. The counter value can
ST be reset by an optional block input to the configured Initial condition value.
Edge
Counter In the Single channel + Direction counting Mode the counter counts up or
down depending on the signal level on the direction input pin. The counter is
incremented if the signal level is logic 1, and decremented if the level is logic 0
at the direction pin.
An example is shown in the figure below. The counter is configured as Single
channel + Direction, and reacts to the rising edge only. Every time a rising
edge is detected, the counter value is incremented or decremented according
to the direction pin signal level. Each task period the actual counter value is
read and output at the block output terminal.
tStep
Model Step
Pulse Input
Direction input
Counter value
Block output 4 7 6
Parameters
Main
TIM unit
Selects the timer unit used. All timer units are 16-bit counters, except
TIM unit 5 is a 32-bit counter.
44
Edge Counter
Mode
Selects whether the counter should count in positive direction only (Single
channel) or should change the counting direction based on an additional
Direction signal (Single channel + Direction). The counter increments
its value when the Direction signal is logic 1, and decrements when the
direction signal is logic 0.
External reset
The external reset selects the behaviour of the external reset input. The
values rising, falling and either cause a reset of the counter to its Initial
condition on the rising, falling or both edges of the reset signal. A ris-
ing edge is detected when the signal changes from 0 to a positive value, a
falling edge is detected when the signal changes from a positive value to 0.
If set to none the counter value cannot be reset by software.
Initial condition
The initial condition allows to choose the start value of the counter. The
initial condition is loaded at the beginning of a simulation or after a reset.
Channel
Edge
The edge detection trigger can be set on Rising, Falling or Either.
Port
Selects the port name.
Pin number(s)
Defines the pin number.
Input characteristic
Specifies whether an internal pull-up or pull-down resistor is connected
to the input pin. If high impedance is selected no internal pull resistor is
connected.
45
4 STM32 Target Support Library Component Reference
Direction
Port
Selects the port name of the direction signal.
Pin
Defines the pin number of the direction signal.
Input characteristic
Specifies whether an internal pull-up or pull-down resistor is connected
to the input pin. If high impedance is selected no internal pull resistor is
connected.
Offline only
46
HRTIM Master
HRTIM Master
Purpose Synchronize multiple high resolution timer (HRTIM) timing units to generate
frequency and/or phase variable PWM signals
Library STM32
Description The HRTIM Master block allows the synchronization of multiple HRTIM tim-
ing units (see page 50). This synchronization enables the generation of fre-
ST
1 en
ADC quency variable and/or phase shifted PWM output signals.
HRTIM 1
1 f'
1 Bd Master
Task All synchronized HRTIM timing units will inherit the configured carrier fre-
HRTIM Master quency. The carrier frequency can be controlled by using the scalar input sig-
nal f 0 . The resulting carrier frequency fc is calculated as the product of the
nominal carrier frequency specified in the block parameter Carrier fre-
quency [Hz] and the input signal f 0 .
The HRTIM Master block can also be used as burst mode controller. Burst
mode operation is commonly used during light load conditions to increase
the converter efficiency. It allows to have the output channels of synchronized
HRTIM timing units alternatively in idle and run state, by hardware. Due to
this, some switching periods can be skipped with configurable periodicity and
variable duty cycle. The burst mode duty cycle can be set by the Bd input ter-
minal and has to be a value between 0 and 1, as shown in the figure below.
ST
HRTIM 1
0.4 Bd Master
HRTIM Master
CarrierFreq: 10e3
BurstFreq: 1000
ST BM
HRTIM 1
0.5
Timer A
47
4 STM32 Target Support Library Component Reference
Note Keep in mind that the HRTIM prescaler is set during the initializa-
tion process of the MCU, and cannot be changed during operation. Therefore,
in case of variable frequency operation, the Carrier frequency [Hz] parame-
ter should be selected as the lowest frequency required during operation.
The HRTIM master block can configure interrupts to trigger the ADC start-of-
conversion and the Control Task Trigger. Interrupts are synchronized with the
PWM carrier, and the repetition counter period determines how many events
need to occur before a trigger is generated. Trigger events will always occur at
the period event (overflow) of the sawtooth carrier.
Parameters
Main
HRTIM unit
Selects the HRTIM timer unit to use.
Carrier frequency [Hz]
Defines the frequency of the carrier in Hertz (Hz). The HRTIM master car-
rier is always of type sawtooth.
Frequency tolerance
Specifies the behavior when the desired carrier frequency is not achievable
based on the system clock frequency.
Frequency variation
Enables or disables the frequency input port f 0 . The resulting output fre-
quency of all synchronized HRTIM timing units is given by f 0 multiplied
by the Carrier frequency parameter.
Enable port
An additional component port is created if Enable port is set to Show. Ap-
plying a signal = 0 to this port sets all synchronized HRTIM timing unit
output channels to their idle state.
Trigger
ADC trigger
Enables or disables the ADC start-of-conversion trigger. The trigger event
always occurs at the period event of the carrier.
48
HRTIM Master
Task trigger
Enables or disables the Control Task Trigger. The trigger event always
occurs at the period event of the carrier.
Repetition counter period
Determines how many period events need to occur before the actual trig-
ger is propagated.
Burst Mode
Burst mode
Enables or disabled the burst mode controller.
Burst mode frequency [Hz]
Defines the burst mode periodicity. This parameter is only visible if Burst
mode is Enabled.
49
4 STM32 Target Support Library Component Reference
Description The high resolution timer (HRTIM) timing unit block generates up to two in-
dependent PWM signals or a complementary PWM pair with a configurable
blanking time. The modulation index must be provided via the input signal,
ST
en
ADC which is a vectorized signal if the block uses two independent output chan-
HRTIM 1
nels. The carrier starts at 0 and varies between 0 and 1. The PWM output is
1 ph Timer A
Task active when the input is greater than the carrier.
HRTIM Timing Unit
The following figure illustrates the difference between the two available out-
put modes: complementary outputs (a) and independent outputs (b). Indepen-
dent outputs share the same PWM carrier, but have different compare values.
In complementary mode the second output channel is always complementary
to the first channel and a blanking time for the rising and falling edge can be
defined.
a)
ST
HRTIM 1
0.1
Timer A
b)
ST
HRTIM 1
[0.1 0.5]
Timer A
HRTIM timing unit output modes: a) complementary PWM pair, b) two inde-
pendent PWM outputs
The figure below shows two HRTIM timing units (A and B) that are Self syn-
chronized. Each HRTIM timing unit has its own carrier frequency and com-
pare value. There is no synchronization signal between the two timing units
and the relative position between the carriers is not deterministic.
50
HRTIM Timing Unit
ST
HRTIM 1
0.1
Timer A
ST
HRTIM 1
0.5
Timer B
The following figure shows two HRTIM timing units (A and B) that are syn-
chronized to a common HRTIM Master (see page 47) block. The HRTIM tim-
ing units A and B inherit the carrier frequency from the master timer. The
master timer generates a synchronization signal for each of the two timing
units and the relative position between the carriers of the timing units and
the master timer is given by the ph input terminal. At each synchronization
edge from the master the synchronized timing units are reset and the counter
restarts at zero. Up to 4 timing units can be arbitrarily phase-shifted in re-
spect to the master carrier. It is possible to synchronize additional timing
units with zero phase shift to the same master timer.
ST
HRTIM 1
Master
HRTIM Master
ST
HRTIM 1
0.1
ph Timer A
0.25
HRTIM Timing Unit
ST
HRTIM 1
0.5
ph Timer B
0.75
HRTIM Timing Unit1
51
4 STM32 Target Support Library Component Reference
The HRTIM timing unit block can configure interrupts to trigger the ADC
start-of-conversion and the Control Task Trigger. Interrupts are synchro-
nized with the PWM carrier, and the repetition counter period determines how
many events need to occur before a trigger is generated, as shown in the fig-
ure below. When the carrier type is symmetrical, for even values of repetition
counter period, the interrupts will occur at the carrier underflow or overflow
events. Underflow and overflow events correspond to PWM carrier reaching
the respective carrier minimum or carrier maximum values. When the carrier
type is sawtooth, the ADC trigger can occur at the period event or in the mid-
dle of the relative on-time of the PWM output. This allows to have ripple free
ADC conversions. The Control Task trigger for a sawtooth carrier will always
occur at the period event of the carrier.
Symmetrical Sawtooth
Rep. period = 1
Rep. period = 2
Underflow
Rep. period = 2
Overflow
Rep. period = 3
Rep. period = 4
Underflow
Rep. period = 4
Overflow
The figure below shows an example of a symmetric PWM carrier with the rep-
etition counter period set to 2, the trigger event set to overflow, and the polar-
ity configured with an active state logic of ‘1’.
52
HRTIM Timing Unit
Overflow
TSW
m
Underflow
PWM output
Complementary PWM
ADC Trigger
Task Trigger
the relative on-time. This can lead to a varying base task period if the timing
unit generates the Control Task trigger, especially during transient operation.
PRD TSW
CMP
CMP/2
ZERO
PWM output
Complementary PWM
ADC Trigger
Parameters
Main
HRTIM unit
Selects the HRTIM unit to use. There are two HRTIM units available.
Timing unit
Selects the HRTIM timing unit of the output channel. Each timing unit
can independently generate up to two independent PWM outputs or a com-
53
4 STM32 Target Support Library Component Reference
Channel
Mode
Configures the output PWM channels to operate independently from each
other or act as complementary signals. Each HRTIM unit can generate up
to two independent PWM outputs or one complementary PWM pair.
Output signals
Defines which output channel should generate PWM signals. If Channel 1
+ Channel 2 is selected, two duty cycle values and enable signals (if the
Enable port is set to Show) are expected at the respective input terminals.
The two independent PWM signals share the same carrier frequency and
54
HRTIM Timing Unit
Trigger
ADC trigger
Enables or disables the ADC start-of-conversion trigger.
ADC trigger event
Selects the ADC trigger event. This parameter is only visible for a carrier
of type sawtooth. When Midpoint is selected the ADC start-of-conversion
is started in the middle of the relative on-time of the PWM signal. If set
to Period the ADC trigger event occurs at the overflow event of the saw-
tooth carrier. Please note the the Timing unit E cannot generate a period
trigger event.
Task trigger
Enables or disables the Control Task Trigger. For a sawtooth carrier the
task trigger is generated at the period event of the counter.
Repetition counter period
Determines how many events need to occur before a trigger is generated.
Trigger event
Selects the trigger event. This parameter is only visible for a carrier of
type symmetrical. When the carrier type is symmetrical, for even values
of repetition counter period, the interrupts will occur at the carrier un-
derflow or overflow events. Underflow and overflow events correspond to
PWM carrier reaching the respective carrier minimum or carrier maxi-
mum values.
55
4 STM32 Target Support Library Component Reference
Burst Mode
Burst mode
If set to Enabled the HRTIM timing unit output channels will react to the
burst mode control signal emitted by the HRTIM master block. If set to
Disabled the timing unit will ignore the burst mode controller. This option
is only selectable if Synchronization is set to Master.
56
Override Probe
Override Probe
Library STM32
57
4 STM32 Target Support Library Component Reference
Library STM32
Description The Peak Current Controller (PCC) block implements peak current control
with slope compensation.
ST
In a peak current-mode controller, at the beginning of each switching cycle the
Ipk
Ipk output is set (gate signal is turned ON) without a pre-determined duty cycle.
Controller
Then, when the sensed inductor current exceeds the peak current reference
value, the output is reset (gate signal is turned OFF). The duty cycle is there-
fore determined by the rise of the inductor current during the on-time.
One of the drawbacks of the peak current-mode controller is that it suffers
from an inherent instability if the applied PWM duty cycle is greater than
50%. This is explained in the figure titled “Slope compensation”. If a small
disturbance is introduced into the system and if the applied duty cycle is less
than 50%, the disturbance eventually decays to zero. However, if the applied
duty cycle is greater than 50%, the inductor current will start to diverge and
will no longer be stable. The resulting duty cycle values will vary from small
to large, on an alternating cycle basis, called sub-harmonic oscillations. To
limit these sub-harmonic oscillations, instead of providing a constant peak cur-
rent reference, additional slope compensation is applied, which then ensures
the stability of the inductor current.
Internally, the PCC block makes use of multiple MCU peripherals. The first
component is a DAC that provides a peak current set-point including ramp,
for controlling the inductor current. The second is a comparator (COMP);
the sensed current is fed to the comparator, which is then compared to the
peak current set-point provided by the DAC. The output of the COMP block
is fed to the third component, which is the high-resolution timer (HRTIM).
The HRTIM generates the PWM waveforms and synchronizes the DAC at the
specified frequency.
The peak current reference (Ipk ) is provided as an input to the PCC block.
Logic is included in the PCC block such that when Ipk = 0, all associated
PWM outputs are driven into the passive state.
The Peak Current Controller block can also be used as burst mode controller.
Burst mode operation is commonly used during light load conditions to in-
crease the converter efficiency. It allows to have the output channels alter-
natively in idle and run state, by hardware. Due to this, some switching pe-
58
Peak Current Controller
Slope compensation
riods can be skipped with configurable periodicity and variable duty cycle. The
burst mode duty cycle can be set by the Bd input terminal and has to be a
value between 0 and 1.
59
4 STM32 Target Support Library Component Reference
Parameters
Main
Channel
Mode
Configures the output PWM channel. Each HRTIM unit can independently
generate a single PWM output or a complementary PWM pair on up to
three PWM channels.
60
Peak Current Controller
Sense port
Selects the port of the sensed current.
Sense pin
Configures the pin of the sensed current.
Timing unit
Selects the HRTIM unit of the output channel. HRTIM timing unit F is
not available on chips of the F3 target family.
Output Polarity
Defines the logical output of the PWM output when an active state is de-
tected. The active state occurs when the sensed current exceeds the peak
reference current set-point.
Switching blanking time
Specifies the delay between the rising and falling edges of a complemen-
tary PWM output pair in seconds (s).
Burst mode
Burst mode
Enables or disabled the burst mode controller.
Burst mode frequency [Hz]
Defines the burst mode periodicity. This parameter is only visible if Burst
mode is Enabled.
61
4 STM32 Target Support Library Component Reference
Powerstage Protection
Library STM32
Parameters
Main
62
Powerstage Protection
Offline only
Interlock
For convenience, the interlock can be enabled or disabled for offline simu-
lations.
• Select Simulate to enable the simulation of the interlock safety mecha-
nism. The output of the the Powerstage Protection block in the top-level
schematic is disabled unless there is a logical low to high transition on the
input en.
• Select Do not Simulate to disable the simulation of the interlock mech-
anism. The output of the the Powerstage Protection block can then be en-
abled at the start of the simulation by tying en to 1.
63
4 STM32 Target Support Library Component Reference
Pulse Capture
Library STM32
Description The capture blocks allows timestamping signal transitions (events) on input
pins, e.g. for period and/or duty cycle measurements. The timestamps are
ST
c made available on the block output c.
CAP v
o The output v is 1 for one simulation step after an event has been triggered, 0
otherwise. The output o is set to 1 if more than one capture event happened
during the last model step. This indicates an overcapture state. It is not pos-
sible to deduce how many times the event was capture in the last model step.
Overcapture events should therefore be avoided to ensure a reliable pulse de-
tection. The output o is automatically cleared after it has been read.
The pulse capture block can be used in either PWM capture Mode or as Indi-
vidual channels.
In PWM capture mode, one channel of the selected TIM unit can be used to
get information about the period and duty cycle of the captured PWM signal.
The first signal of the c output reflects the measured period, the second signal
of the c output can be used to calculate the duty cycle.
The figure below illustrates with an example how the different output signals
behave if Mode is set to Individual channels. The channels 1 and 2 are con-
figured as described in the following table:
64
Pulse Capture
tStep
Model Step tPulse
Pulse Input
CAP Output
Valid Output
Overcapture
Output
An illustrative example for different capture settings when the Pulse Capture
block is used with individual channels (channel 1 in red, channel 2 in blue).
If multiple capture events happen inside a model step the overcapture output
will output a 1 at the end of the respective model step. The counter is oper-
ated in free-running mode and therefore not reset by a capture event. To cal-
culate the period of the pulse inpunt signal one has to calculate the difference
between two consecutive capture events.
Parameters
Main
TIM unit
Selects the timer unit to use.
Mode
Specifies the desired capture mode. If set to Individual channels the
channels of the selected TIM unit can be used to capture up to three in-
dividual signals. The PWM capture mode facilitates the measurement of
frequency and duty cycle. In PWM capture mode exactly one Channel has
to be enabled.
Clock prescale
Specifies the desired prescale value.
65
4 STM32 Target Support Library Component Reference
Channel 1/2/3
Capture
Provides an option to disable or enable an input channel.
Edge
The edge detection trigger can be set on Rising, Falling or Either.
Prescale
Specifies the desired prescale value for an individual channel.
Port
Selects the port name of the capture channel.
Pin
Defines the pin number of the capture channel.
Offline only
66
PWM
PWM
Library STM32
Description The PWM block generates a single or complementary PWM pair on one or
more PWM resources. The modulation index for each channel must be pro-
ST vided via the input signal, which is a vectorized signal if the block uses mul-
ADC
tiple channels. The carrier starts at 0 and varies between 0 and 1. The PWM
PWM output is active when the input is greater than the carrier. The carrier fre-
Task quency can be controlled by using the optional scalar input signal f 0 . The re-
sulting carrier frequency fc is calculated as the product of the nominal carrier
frequency specified in the block parameter Carrier frequency [Hz] and the
input signal f 0 . Note that all PWMs channels within one PWM block share
the same frequency input.
The PWM block can configure interrupts to trigger the ADC start-of-
conversion and the Control Task Trigger. Interrupts are synchronized with the
PWM carrier, and the repetition counter period determines how many events
need to occur before a trigger is generated, as shown in the figure below.
When the carrier type is symmetrical, for even values of repetition counter
period, the interrupts will occur at the carrier underflow or overflow events.
Underflow and overflow events correspond to PWM carrier reaching the re-
spective carrier minimum or carrier maximum values.
The figure below shows an example of a symmetric PWM carrier with the rep-
etition counter period set to 2, the trigger event set to underflow, and the po-
larity configured with an active state logic of ‘1’.
The PWM block protection parameters configure the break input settings for
all PWM resources associated with the block. When a break input event is
detected, all the PWM outputs are shutdown and are forced into the passive
state.
Parameters
Main
TIM unit
Selects the advanced-control timer unit to use. There are two TIM units
available, TIM1, TIM8 or TIM20. Each TIM unit can independently generate
a single PWM output or a complementary PWM pair on up to three PWM
channels.
67
4 STM32 Target Support Library Component Reference
Symmetrical Sawtooth
Rep. period = 1
Rep. period = 2
Underflow
Rep. period = 2
Overflow
Rep. period = 3
Rep. period = 4
Underflow
Rep. period = 4
Overflow
Overflow
TSW
m
Underflow
PWM output
Complementary PWM
ADC Trigger
Task Trigger
Carrier type
Selects the carrier waveform, either sawtooth or symmetrical.
Carrier frequency
Defines the frequency of the carrier in Hertz (Hz).
Frequency tolerance
Specifies the behavior when the desired carrier frequency is not achievable
68
PWM
Channel
Mode
Configures the output PWM channel. Each TIM unit can independently
generate a single PWM output or a complementary PWM pair on up to
three PWM channels.
Polarity
Defines the logical output of the PWM output when an active state is de-
tected. The active state occurs when the modulation index exceeds the car-
rier.
Port
Selects the port of the PWM output.
Pin
Configures the pin of the PWM output.
Complementary Port
Selects the port of the complementary PWM output.
Complementary Pin
Configures the pin of the complementary PWM output.
Events
ADC trigger
Enables or disables the ADC start-of-conversion trigger.
Task trigger
Enables or disables the Control Task Trigger.
69
4 STM32 Target Support Library Component Reference
Protection
Break input
Provides an option to configure a digital input to force shutdown all the
PWM outputs associated with the block and drive them into passive
state.
• Disabled: Break input is not configured.
• Active low: a logical high to low transition on the input signal will force
the PWM outputs into passive state.
• Active high: a logical low to high transition on the input signal will force
the PWM outputs into passive state.
Break input port
Selects the digital input port to be configured as the break input.
Break input pin
Configures the digital input pin to be configured as the break input.
70
Quadrature Encoder Counter (QEP)
Library STM32
Description The Quadrature Encoder Counter counts edges which are generated from a
quadrature encoder. The A, B, and I outputs of the encoder are connected to
ST the input GPIOs of the microcontroller.
c
QEP i The block output c represents the current counter value, port i represents the
ic
index pulse, and port ic outputs the latched counter value from the previous
Counter index pulse.
The counter counts up or down depending on the sequence of input pulses.
The counter value will increase when the direction of rotation results in the
rising edge of B following the rising edge of A and will decrease in the oppo-
site direction of rotation. For each rising and falling edge of the A and B en-
coder output signals the counter will increment or decrement. Therefore the
Maximum counter value must match the number of line pairs of the en-
coder multiplied by the number of counted edges per line pair minus 1. As
an example, an encoder with 1024 line pairs would have a maximum count
of 4095 since the QEP module counts all edges of A and B (4 edges per line
pair).
Once the counter reaches the value specified in parameter Maximum
counter value it is reset to zero on the next detected edge in the positive di-
rection. Vice versa, the counter is set to Maximum counter value when it is
zero and detects an edge in the negative direction. If connected and configured
by the Mode parameter, the counter is also reset when the rising edge of the
index input is detected.
Parameters
Main
TIM unit
Selects the timer unit used.
Maximum counter value
The counter is reset to zero when it has reached the Maximum counter
value and detects an input edge in the positive direction. The counter is
set to the Maximum counter value when it is zero and detects an input
edge in the negative direction.
71
4 STM32 Target Support Library Component Reference
Mode
Selects whether the counter should be reset by a positive pulse on the in-
dex input or on overflow only. Three different modes are available:
• Free running: The counter is reset on overflow only. Output ports i and ic
are not available, and the output I of the encoder is not required.
• Free running with index capture: The counter is reset on overflow only.
In addition, the index pulse is captured and the latched counter value from
the previous index pulse is made available at the output port ic.
• Reset by index pulse: The counter is reset by a positive pulse on the in-
dex input.
Channel A
Port
Selects the port of the channel A input.
Pin
Configures the pin of the channel A input.
Input characteristic
Specifies whether an internal pull-up or pull-down resistor is connected to
the digital input. If high impedance is selected no internal pull resistor is
connected.
Channel B
Port
Selects the port of the channel B input.
Pin
Configures the pin of the channel B input.
Input characteristic
Specifies whether an internal pull-up or pull-down resistor is connected to
the digital input. If high impedance is selected no internal pull resistor is
connected.
Index
Port
Selects the port of the index pulse input.
72
Quadrature Encoder Counter (QEP)
Pin
Configures the pin of the index pulse input.
Input characteristic
Specifies whether an internal pull-up or pull-down resistor is connected to
the digital input. If high impedance is selected no internal pull resistor is
connected.
73
4 STM32 Target Support Library Component Reference
Read Probe
Library STM32
74
SinCos
SinCos
Library STM32
Description Utilizes the CORDIC co-processor for fast calculation of sine and cosine for
chips from the G4 target family. For the F3 target family a look-up table
ST based implementation is used to calculate sine and cosine efficiently.
sin
cos
75
4 STM32 Target Support Library Component Reference
SPI Master
Library STM32
Description The Serial Peripheral Interface (SPI) is a high-speed synchronous serial in-
ST put/output device that allows a serial bit stream of programmable length (4 to
v
SPI 1 o 16 bits) to be shifted into and out of the device at a configurable bit-transfer
Master rate. The SPI is usually used for communications between the MCU controller
and external peripherals, or another controller.
TX RX
SPI Master The SPI is a master-slave based interface with a single master and one or
more slave devices.
The SPI Master block provides a clock signal (SCK) which generates a config-
urable number of clock pulses during each simulation step. For both the slave
and the master, data is shifted out of the shift registers on one edge (rising
or falling) of the CLK and latched into the shift register on the opposite clock
edge. If the clock phase (CPHA) bit is configured to 1, data is transmitted and
received a half-cycle before the SCK transition.
76
SPI Master
SCK SCK
[Data-out 1, Data-out 2]
MOSI [TX] MOSI [RX]
[Data-in 1]
MISO [RX] MISO [TX]
/CS1 /CS1
SPI Slave 1
SCK
MOSI [RX]
[Data-in 2]
MISO [TX]
/CS2 /CS2
tDiscretization Step
Model Step
1: Slave 1 inactive
An example of signal exchange between one SPI Master and two SPI Slaves
The SPI Master block exchanges data with only one SPI Slave per block exe-
cution step. If there are multiple slaves, then data is exchanged over multiple
steps. For example, as illustrated in the figure above, during the first step,
77
4 STM32 Target Support Library Component Reference
the master enables SPI Slave 1 using the chip-select signal and transmits
Data-out 1; at the same time the master also receives Data-in 1 from the first
slave. During the second step, after enabling SPI Slave 2, the master trans-
mits Data-out 2 and receives Data-in 2 from the second slave simultaneously.
This process then repeats.
An output value of 1 at the v port indicates that valid data is sent to all the
slaves.
The data to be transmitted is provided at the input TX and the data received
is available at the output RX.
• TX: For transmitting data to multiple slaves, provide a vector with a length
equal to the sum of the number of words per transmission per each slave.
For example, in the figures above, if Data-out 1 is a packet of 4 words
[1,2,3,4] and Data-out 2 is a packet of 3 words [16,17,18], then the input
to the TX block is provided as a vector of 7 words [1,2,3,4,16,17,18].
• RX: Similarly, data from multiple slaves is received as a vector with a
length equal to the sum of the number of words per transmission per each
slave. For example, in the figures above, if Data-in 1 is a packet of 4 words
[21,22,23,24] and Data-in 2 is a packet of 3 words [36,37,38], then the out-
put of the RX block is read as a vector of 7 words [21,22,23,24,36,37,38].
If the SPI Master does not have enough time to complete the transmission be-
fore the block is executed again, the output o turns 1 to indicate an overrun
error.
If an overrun error is being signaled at the o port of the SPI Master, it is pos-
sible that the task with which the SPI Master is associated executes too fast.
In this case, either reduce the SPI Master execution task rate or increase the
SPI clock rate.
For example, if SCK is set as 180000 Hz, and is expected to transmit a packet
of 4 words at 8 bits per word, then the time it would take to transmit one
packet is
1
· 4 · 8 = 1.78 · 10−4 seconds.
180000
In this case, the execution step size of the SPI Master must be set to values
greater than 0.178 milliseconds.
Parameters
Setup
SPI module
Selects the SPI module to use.
78
SPI Master
Offline simulation
Enables or disables data inspection in an offline simulation. If set to en-
able, terminals are added to the subsystem in the top-level schematic. If
set to disable, no such terminals are added to the subsystem.
GPIO Settings
SCK Port
Selects the port name of the clock frequency signal.
SCK Pin
Defines the pin number of the clock frequency signal.
MISO Port
Selects the port name of the MISO signal.
79
4 STM32 Target Support Library Component Reference
MISO Pin
Defines the pin number of the MISO signal.
MOSI Port
Selects the port name of the MOSI signal.
MOSI Pin
Defines the pin number of the MOSI signal.
Slave(s)
CS Port
Selects the port name to use for chip-select. In a multi-salve setup, all in-
dividual chip-select signals must be assigned to the same port group.
CS Pin(s)
Defines the pin number of the chip-select signal. Any GPIO can be con-
figured to be a chip-select signal. Provide a vector to configure multiple
slaves.
Words per transmission (vector for multiple slaves)
Configures the number of transmitted data words in each simulation step.
Provide a vector to configure multiple slaves.
80
SPI Slave
SPI Slave
Library STM32
Description For a detailed description of the SPI protocol and signals, refer to the SPI
Master (see page 76) block.
ST The SPI Slave is synchronized to the clock generated by the SPI Master. The
v
SPI 1 o SPI Master uses a dedicated active-low chip-select signal that enables the
Slave MISO and MOSI ports of the SPI Slave.
TX RX The data to be transmitted is provided at the input TX and the data received
SPI Slave is available at the output RX. An output value of 1 at the v port indicates a
valid data exchange with the SPI Master.
If the SPI RX port receives new data before the previous data has been read,
the existing data will be overwritten and lost. If this occurs, the output o
turns 1 to indicate an overrun error.
There are two considerations to note when overrun errors occur:
• The master is not allowed to start transmitting before the slave is up and
running. If the slave is booting up while the master is transmitting, then it
may receive an incomplete first message, from which it will not be able to
recover.
• In order to avoid overruns, the SPI Slave block must be executed faster
than the rate at which the SPI Master is sending data.
Parameters
Setup
SPI module
Selects the SPI module to use.
Bits per word (4-16)
Defines the length of a single data word during transmission. The allowed
length is 4 to 16 bits per word.
81
4 STM32 Target Support Library Component Reference
GPIO Settings
SCK Port
Selects the port name of the clock frequency signal.
SCK Pin
Defines the pin number of the clock frequency signal.
MISO Port
Selects the port name of the MISO signal.
MISO Pin
Defines the pin number of the MISO signal.
MOSI Port
Selects the port name of the MOSI signal.
82
SPI Slave
MOSI Pin
Defines the pin number of the MOSI signal.
CS Port
Selects the port name of the chip-select signal.
CS Pin
Defines the pin number of the chip-select signal.
83
4 STM32 Target Support Library Component Reference
Timer
Purpose Generate trigger signals for the ADC start-of-conversion and the control task
using a general-purpose timer
Library STM32
Description The Timer block configures the general-purpose timers TIM3 or TIM4, to gen-
erate an interrupt at the specified frequency. The timer interrupt can be used
ST to trigger the ADC start-of-conversion or the Control Task Trigger.
ADC
Timer The exact timer frequency may not be achievable based on the system clock
frequency. The Frequency tolerance parameter allows automatically round-
Task
ing to the closest achievable value when the exact timer frequency is un-
achievable.
Parameters Frequency
Defines the frequency of the timer in Hertz (Hz).
Frequency tolerance
Specifies the behavior when the desired timer frequency is not achievable.
84
electrical engineering soft ware