# Converting Models from Floating Point to MATLAB Digest

```MATLAB Digest
Converting Models from Floating Point to
Fixed Point for Production Code Generation
By Bill Chou and Tom Erkkinen
An essential step in embedded software development, floating- to fixed-point
conversion can be tedious, labor-intensive, and error-prone. System engineers
frequently design algorithms in floating-point math, usually double-precision.
This format represents the ideal algorithm behavior but takes little account of
the algorithm’s final realization in production software and hardware. Software
engineers and suppliers in mass production environments often need to convert
these algorithms to fixed-point math for their integer-only hardware. As a result,
multiple iterations between system and software engineers are often required.
Products Used
■ Stateflow®
■ Fixed-Point Toolbox™
■ Real-Time Workshop®
■ Real-Time Workshop Embedded Coder™
■ Stateflow Coder™
Using a fault-tolerant fuel system model as
and several sensors. We concentrate on the
be deployed on a floating-point embedded
ECU controller for fixed-point modeling,
workflow for converting models from float-
conversion, and code generation.
an interactive tool designed to facilitate
ing point to fixed point for production code
generation. Topics covered include:
Some preparation tasks are required even
model preparation (Figure 1).
if the code generated from the ECU is to
• Preparing the model data
•A
nalyzing, refining, and optimizing the
fixed-point scaling
• Generating optimized code
• Verifying and validating the code
The approach described here uses two
tools in Simulink Fixed Point™: Fixed-Point
Preparing the Model And Data
For Conversion
The fault-tolerant fuel system model contains three main components: an ECU controller, a plant for the engine gas dynamics,
1
MATLAB Digest
Figure 1. Model preparation using Fixed-Point Advisor.
www.mathworks.com
Figure 2. Block data type
Using Fixed-Point Advisor, we will complete the following steps:
• Replace unsupported blocks
• Set up signal logging and create initial
reference data
hundreds of functions that support fixed
subsystem hierarchy (Figure 3). Once we
point, including those typically used in em-
have configured the signals to be logged, we
bedded algorithm design.
create and store the reference data using the
floating-point model.
Setting Up Signal Logging And
Creating Initial Reference Data
• Specify target hardware characteristics
We log signals of interest from simulation
Specifying Target Hardware
Characteristics
• Prepare for and perform data typing
for use in equivalence comparisons with
Model simulation behavior and code gen-
the fixed-point model and for code gener-
eration outputs are determined by the
ation. Typically, input and output signals
characteristics of the target hardware.
Model Advisor reminds us to specify the
a list of additional signals that it might be
correct word lengths for char, int, long,
and other attributes unique to a particular
and scaling
• Check model suitability for production
code deployment
Replacing Unsupported Blocks
We begin by replacing blocks that do not support fixed-point data types—including replacing continuous-time with discrete-time
To make signal logging easier, we can log
all signals or select signals, including unnamed ones, from portions of the model
embedded microprocessor so as to avoid
producing incorrect results from simulation or code generation.
blocks. We can use rate transition blocks
to convert the continuous-time signals
to discrete-time signals sampled at 10ms, as
required by the controller. At this stage, we
must also analyze the effect of sampling and
quantization on system performance and
stability. Simulink® provides a list of data
types supported by each block (Figure 2).
Most blocks support fixed-point data types.
Stateflow® fully supports fixed point.
MATLAB™ functions, you can choose from
2
MATLAB Digest
Figure 3. Logging fixed-point data, including unnamed signals.
www.mathworks.com
Preparing For Data Typing
And Scaling
Data type inheritance and other propagation settings affect the time needed to
convert the model from floating to fixed
point. During the initial design phase, engineers frequently use inherited data type
propagation to speed up prototyping and to
quickly iterate several designs. As the project approaches production, they fine-tune
and specify individual data types and scal-
Figure 4. Identifying issues that could lead to the generation of inefficient code.
ing to optimize fixed-point results.
Fixed-Point Advisor facilitates this workflow by automating the following steps:
• Removing output data type inheritance
to help avoid data type propagation
conflicts
• Relaxing input data type settings or
constraints that might lead to data-type
propagation errors
• Verifying that state charts have strong
We must specify design minimum and
maximum values for inport blocks. We can
also specify these values for other block outputs and parameters.
Performing Initial Data Typing And
Scaling
Using Fixed-Point Advisor, we specify initial data typing and scaling for blocks.
Based on our initial input and direction,
and initial scaling for inport blocks, constants, blocks that do not fall into either
category, parameters, and blocks that use
intermediate data types, such as the Sum
3
MATLAB Digest
uses either the design or simulation minimum and maximum from the floatingpoint data to propose the initial fixed-point
scaling. The tool reports scaling conflicts
and suggests ways to resolve them. It then
checks for numerical errors and analyzes
the logged signals.
An initially scaled fixed-point model is
then produced, together with plots comparing
Analyzing, Refining, and
Optimizing the Fixed-Point
Scaling
Using the Fixed-Point Tool’s automatic
scaling function, we analyze, refine, and
optimize scaling for relevant blocks in the
model that we initially scaled using FixedPoint Advisor.
We use the data type override feature
the floating-to-fixed-point model results.
to collect the dynamic range of signals in
Checking the Model’s Suitability For
Production Code Deployment
this information to propose a more suitable
Using Fixed-Point Advisor, we run final
on the number of available bits. Individual
checks to determine the model’s suitability
blocks can be locked down to prevent them
for production code deployment (Figure 4).
from being modified by the tool. We can
These include:
then use automatic scaling with individu-
• Disabling signal logging to avoid declaring extra signal memory in the generated code
double precision. The Fixed-Point Tool uses
fixed-point scaling for each block, based
ally scaled blocks and accept or reject the
proposed scaling for each signal.
With the Fixed-Point Tool we can use one
• Identifying blocks that generate expensive saturation and rounding code
• Identifying questionable fixed-point
operations—for example, ensuring that
lookup tables are spaced so as to maximize code efficiency
www.mathworks.com
model for both the floating- and fixed-point
designs, reducing the need to maintain separate models during design iterations.
Figure 5. Automated scaling using the Fixed-Point Tool.
Generating Optimized Code
sor-optimized code. We could also target
easy way to analyze and contrast the behav-
Before generating code for the system,
middleware or abstraction layers, such
ior of the fixed- and floating-point designs.
we run checks in Simulink using Model
as AUTOSAR.
The Fixed-Point Tool records the number
Advisor. Some checks, such as “identify
of overflows and saturations that occurred
questionable fixed-point operations” and
in the simulation. Figure 5 shows the tool
“check hardware implementation,” are cru-
and its proposed scaling for the Fuel System
model. Further analysis showed the output
model standards checks are available in
of the Sum block saturated during simula-
tion. The automatic scaler proposed chang-
cluding checks based on the MAAB guide-
ing the fraction length from 11 to 10 bits, in-
lines and safety-related standards such as
creasing the output dynamic range to avoid
IEC 61508 and DO-178B.
Comparison plots provide a quick and
saturation and retain maximum precision.
Once we have made this change, the results
match closely (Figure 6), and we are ready
for code generation.
To generate code from an optimized
design, we must first select a deployment
target. Options range from the default
ANSI/ISO C/C++ to a target with proces-
For ANSI/ISO C code generation, we select the Embedded Real-Time Target (ERT)
option in Real-Time Workshop Embedded
Coder™, which is optimized for fixed-point
code (Figure 7). Other than word sizes and
other target characteristic settings, this
code is portable and can be deployed on any
target with the specified word sizes.
There are several capabilities for generating target-optimized code. The first is to
have the generated code call an existing C
function at the appropriate point within
the algorithm, typically by using the Legacy
Figure 6. Comparison with original floating-point results.
4
MATLAB Digest
Figure 7. ANSI-C code optimized for a fixed-point target using
Real-Time Workshop Embedded Coder.
www.mathworks.com
A second capability is to automatically
replace generated math functions, math
operators, and memory-allocation functions such as memcpy with target-specific
versions. This is done using Target Function Libraries (TFL), tables mapping default
functions and operators to their target-specific equivalents. Several pre-built TFLs are
Figure 8. Selecting optimized Target Function Libraries.
available (Figure 8). In addition, end users
can create customized tables for their own
targets. The TFL is then available as a codegeneration setting.
Once a TFL is selected, the generated
code incorporates the replacement items.
One advantage of this option is that you can
quickly generate optimized code for several
different targets from the same model simply by changing the TFL. Figure 9 compares
ANSI-C- and TriCore® optimized code for
fixed-point addition of 32-bit integers with
saturation logic. The code is smaller and the
execution time dramatically reduced—by a
factor of 17.
Verifying and Validating the
Production Code
The reference data collected from the floating-point behavioral model can be reused
for equivalence testing throughout the development process. We first use the data to
int32 _ T _ add _ s32 _ s32 _ s32 _ sat(int32 _ T a, int32 _ T b)
{
int32 _ T tmp;
tmp = a+b;
{
if ((a < 0) && (b < 0) && (tmp >= 0))
}
tmp = MIN _ int32 _ T;
} elseif ((a > 0) && (b > 0) && (tmp <= 0))
{
}
tmp = MAX _ int32 _ T;
return tmp;
int32 _ Tadd _ s32 _ s32 _ s32 _ sat(int32_ T a, int32_ T b)
{
}
return ( _sat int)a+b;
compare the results of the initial fixed-point
design to the original floating-point model.
We do not need to generate code just to
Figure 9. Fixed-point code optimized for ANSI-C (top) and TriCore (bottom) using TFL.
compare the model results because bit-accurate fixed-point simulation is supported
5
MATLAB Digest
www.mathworks.com
Resources
visit
www.mathworks.com
Technical Support
www.mathworks.com/support
Online User Community
www.mathworks.com/matlabcentral
Demos
www.mathworks.com/demos
Training Services
www.mathworks.com/training
Third-Party Products
and Services
www.mathworks.com/connections
Worldwide CONTACTS
www.mathworks.com/contact
e-mail
[email protected]
Figure 10. PIL testing. The scope (right) shows no difference between the
signal output from the model and the generated object code using the
PIL block.
We test the code on the target processor
Bit-accurate fixed-point simulation helps
using processor-in-the-loop (PIL) testing
you model designs within the Simulink
(Figure 10). PIL cosimulates the object
code on an embedded hardware or in-
Fixed Point let you automate time-con-
struction set simulator with the original
suming parts of the fixed-point conver-
plant model or test harness in Simulink.
sion workflow and explore designs to fur-
MathWorks link products, such as Em-
ther refine the fixed-point performance.
bedded IDE Link™ MU (for Green Hills®
Real-Time Workshop Embedded Coder
MULTI®), automate PIL testing using third-
provides an automated path to production
party integrated development environments
code deployment.
(IDEs). It is possible to run PIL testing on
Freescale™ MPC 5500.
■ Using Diagnostics to Improve Your
Another way to verify the code is to use
www.mathworks.com/diagnostics
Polyspace™ products, which formally ana-
■ Fixed-Point Modeling and Code
lyze code to identify defects such as fixed-
(R2008a)
point overflow, division-by-zero, and array
out-of-bounds.
MATLAB Digest
80368V00 11/08
■
processors supported by these IDEs, such as
6