Converting Models from Floating Point to MATLAB Digest

Converting Models from Floating Point to  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
■ Simulink®
■ Stateflow®
■ Fixed-Point Toolbox™
■ Simulink Fixed Point™
■ Simulink Verification and Validation™
■ 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
an example, this article describes tools and a
ECU controller for fixed-point modeling,
micro-processor. Fixed-Point Advisor is
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
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
Advisor and Fixed-Point Tool.
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,
Figure 1. Model preparation using Fixed-Point Advisor.
Figure 2. Block data type
support table in Simulink.
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
• 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.
are logged. Fixed-Point Advisor provides
Model Advisor reminds us to specify the
a list of additional signals that it might be
correct word lengths for char, int, long,
helpful to log.
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.
If your model includes Embedded
MATLAB™ functions, you can choose from
Figure 3. Logging fixed-point data, including unnamed signals.
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
• Relaxing input data type settings or
constraints that might lead to data-type
propagation errors
• Verifying that state charts have strong
data typing with Simulink
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
Using Fixed-Point Advisor, we specify initial data typing and scaling for blocks.
Based on our initial input and direction,
Fixed-Point Advisor proposes data typing
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
and Product blocks. Fixed-Point Advisor
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
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
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
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
cial for fixed-point development. Additional
model. Further analysis showed the output
model standards checks are available in
of the Sum block saturated during simula-
Simulink Verification and Validation™, in-
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
Code Tool in Simulink.
Figure 6. Comparison with original floating-point results.
Figure 7. ANSI-C code optimized for a fixed-point target using
Real-Time Workshop Embedded Coder.
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
by Simulink Fixed Point.
Technical Support
Online User Community
Training Services
Third-Party Products
and Services
Worldwide CONTACTS
[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
environment. Tools provided by Simulink
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
For More Information
Freescale™ MPC 5500.
■ Using Diagnostics to Improve Your
Simulink Model
Another way to verify the code is to use
Polyspace™ products, which formally ana-
■ Fixed-Point Modeling and Code
lyze code to identify defects such as fixed-
Generation Tips for Simulink 7
point overflow, division-by-zero, and array
80368V00 11/08
processors supported by these IDEs, such as
© 2008 The MathWorks, Inc. MATLAB and Simulink
are registered trademarks of The MathWorks, Inc. See for a list of additional
trademarks. Other product or brand names may be trademarks or registered trademarks of their respective holders.
Was this manual useful for you? yes no
Thank you for your participation!

* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project

Download PDF