1 © 2013 The MathWorks, Inc.
Automatic Code Generation
Sang-Ho Yoon
Senior Application Engineer
2
What kind of code can I generate
using automatically code generation?
I’ve heard of HIL and RCP, but I'm not
sure what they are...
Frequently Asked Questions from everyone
I will show an overview of code
generation solutions, and
introduce features through a few
demos
3
Specification &
Validation data
Hand code and
verification
results
A world without automatic code generation
System Design &
Algorithm Development Explore, verify, implement
① Hand coding of the model is inaccurate and inefficient
② Difficult, time consuming, and costly to develop and prototype
electro-mechanical systems & software
③ Difficult to verify and validate data and specifications
MATLAB File/
Simulink Model
Specs Validate data Prototype Hand code
Specs
③
② ①
4
MATLAB File/
Simulink Model
Specs Validate data
① Updates to specs take effect immediately using automatic
code generation!
② Develop electro-mechanical system in parallel with real-time
simulation test hardware!
③ Validate the generated code!
Using Automatic Code Generation
System Design &
Algorithm Development Explore, verify, implement
Simulation
hardware
Automatically
generated code
MATLAB File /
Simulink Model
③
②
Specifications &
Validation data
+ Models
Verification
results
+ Generated
code
①
5
C/C++ Coders
MATLAB Coder - Code from MATLAB
– Portable code for numerical algorithms
– Desktop applications (standalone, library)
Simulink Coder - Code from Simulink
– RCP or HIL
– Real-time machines (xPC Target)
Embedded Coder – Production optimized code
– MATLAB and Simulink (for embedded systems)
– MCU and DSP (fixed or float)
– Code verification (in-the-loop)
– Target-specific support (APIs and examples)
All coders generate portable code (ANSI/ISO C) by default.
C/C++
Gen
era
te
MATLAB and Simulink Algorithm and System Design
Verify
6
HDL Coder
HDL Coder
MATLAB and Simulink
VHDL and Verilog
ASIC and FPGA
Target-independent
– By default
Target-specific
– Xilinx FPGA
– Altera FPGA
HDL Verifier
HDL co-simulation
– ModelSim, Incisive
FPGA in-the-loop (FIL)
– Xilinx, Altera
MCU DSP FPGA ASIC
C/C++ VHDL/Verilog
Gen
era
te
MATLAB and Simulink
Algorithm and System Design
V
erify
Gen
era
te
Verify
7
PLC Coder
Simulink PLC Coder
Simulink
ST (Structured Text)
PLC and PAC
Target-independent
– By default
(IEC 61131)
Target-specific
– Rockwell
– Siemens
– B&R
– Omron
– Others
MCU DSP FPGA ASIC
C/C++ VHDL / Verilog
Gen
era
te
MATLAB and Simulink
Algorithm and System Design
Verify
Gen
era
te
Ve
rify
PLC PAC
Stuctured Text
Gen
era
te
Verify
8
MATLAB File
Desk
top FPGA ASIC
MEX / C VHDL / Verilog
Gen
era
te
MATLAB Coder Algorithm Design
Verify
Gen
era
te
Verify
PLC PAC
Structured Text
Gen
era
te
Verify
Additional Coders
MPU
9
.c
MATLAB Coder Generate C code from MATLAB algorithms
.exe
MEX
Generate C source code
Prototype as standalone
executable
Integrate into existing C
environment as
static/dynamic libraries
Accelerate MATLAB
algorithms
MATLAB File
ANSI-C/ISO-C/GNU-C Compliant
Floating-point C code
Fixed-point C code (requires Fixed-
Point Designer)
.lib
.dll
10
function edge_img = detect_edge(img, threshold) % Change data type img_sgl = single(img) / 255; % Filter kernel k = [ 1 2 1; ... 0 0 0; ... -1 -2 -1]; H = conv2(img_sgl, k, 'same'); V = conv2(img_sgl, k','same'); % Detect edge E = sqrt(H.*H + V.*V); edge_img_bin = E > threshold; edge_img = uint8(edge_img_bin) .* 255;
MATLAB Coder Demo Generate C code and MEX file from Sobel Edge Detection Algorithm
MATLAB File
C Code/MEX-File
MATLAB Coder Project
11
function S = mytimes2(S, a) coder.cstructname(S,'myStruct') S.x = S.x * S.y; S.y = S.y * a;
function y = mytimes1(a, b) y = a .* b;
MATLAB Coder Optimization
Reuse input argument, pass struct by reference
void mytimes1(const real_T a[10], const real_T b[10], real_T y[10])
{
int32_T i;
for (i = 0; i < 10; i++) {
y[i] = a[i] * b[i];
}
}
void mytimes2(myStruct *S, const real_T a[10])
{
int32_T i0;
for (i0 = 0; i0 < 10; i0++) {
S->x[i0] *= S->y[i0];
}
for (i0 = 0; i0 < 10; i0++) {
S->y[i0] *= a[i0];
}
}
Pass struct by
reference
Reduced number
of arguments
12
Advantages of MATLAB Coder
Maintain one design in MATLAB
– Spend more time improving algorithms in MATLAB
– Leverage MATLAB’s rich language and Toolbox functions
– Use MATLAB’s graphics and debugging capabilities
Design faster and get to C code quickly
Accelerate using MEX-files
Deploy your algorithm as C code royalty-free
13
ESA’s First-Ever Lunar Mission Satellite
Orbits Moon with Automatically Generated
Flight Code
Challenge Develop ESA’s first lunar mission in a short time frame
and at minimal cost
Solution Use MathWorks tools for Model-Based Design to
model, simulate, generate, and test the flight code
Results Reduced system development time by 50%
Improved process efficiency
Produced efficient code
―MathWorks tools for simulation
and flight-code generation played
a key role in this success and will
serve as the foundation for future
satellite programs, such as
Prisma.‖
Per Bodin
Swedish Space Corporation
Artist’s rendition of SMART-1 traveling to
the Moon.
Link to user story
14
Simulink/Stateflow Model
RCP FPGA ASIC
EXE / C VHDL / Verilog
Gen
era
te
Simulink Coder Real-Time Testing
Tu
ne/L
og
Gen
era
te
Verify
PLC PAC
Structured Text
Gen
era
te
Verify
Additional Coders
HIL
15
Simulink Coder Generate C code from Simulink for Real-Time Testing
HIL Test
RCP
.exe
Rapid simulation
acceleration
Hardware In the Loop
Simulink/Stateflow Model
Simulink Coder support wide variety of Real-Time Simulators, including xPC Target
16
ECU
Sim
ula
tion
En
viro
nm
en
t R
eal E
nviro
nm
en
t
What is RCP(Rapid Control Prototyping)?
Actual Plant
Plant Model Control Model
Generate C code from the
control model, implement in the
experimental (general-purpose
controller) RCP controller
Real-time signal monitoring
Online parameter tuning
Early verification of
algorithm before final
controller design
Fast implementing for
engineers who are not
programming experts
Fast design iterations
based on real-world
physical behavior
RCP
C
17
Sim
ula
tion
En
viro
nm
en
t R
eal E
nviro
nm
en
t
What is HIL(Hardware In the Loop Testing)?
Plant Model Control Model
ECU
Generate C code from control
model to implement on HIL
simulator. Test software that
simulates actual control ECU.
Test ECU with real engine for
nominal and fault conditions
Find errors in lab not field
Fault injection test is easier
Improve test coverage by
increasing the operating
environment conditions
Easy test automation
Actual Plant HIL Simulator
C
18
I / O driver block library that corresponds to the board a
wealth of input and output
Supports multi-core processors and FPGAs
Provides turnkey hardware manufactured by Speedgoat
xPC Target Perform RCP / HIL using Real-Time Systems
Host PC
TargetPC
Ethernet or RS 232
1
2
3
19
xPC Target Hardware
Other HW 일반PC/산업용PC에 입출력
포트를 사용
직접 세팅을 해야함. 하지만,
적절한 가격으로 구현할 수 있음.
가능한 입출력 보드의 목록
Speedgoat HW CPU + input and output module
housing Turnkey for xPC
summarizes the Immediately
available solution
CPU to fit the needs of our
customers, Input and output
modules, the housing Provided in
combination
Korean Distributor: Autotron
http://www.speedgoat.ch/
http://www.mathworks.co.jp/products/
xpctarget/supported/hardware-
drivers.html
20
Benefits of Simulink Coder
Automate control system experimentation with RCP
Test the embedded system using HIL simulation,
You can test system response to faults!
Accelerate Monte Carlo tests by converting to
executable code (.exe) using code generation
May achieve faster simulation*
*But try Rapid Acceleration simulation mode first
21
Challenge Verify design ideas for printer path control, while
streamlining the development process
Solution Use MathWorks tools to model plants and controllers,
automatically generate code, and run the code in real
time on target hardware
Results Controls development time reduced by 80%
Workflow streamlined with integrated tools
Tests conducted independently of hardware
development schedule
―The main advantage in using
MathWorks tools for Model-Based
Design is that the approach is easy
to understand, the models are self
documenting, and the tools are
completely integrated, which
speeds up development.‖
Dr. Martin Krucinski
Xerox
Complex printer path technology.
Xerox Reduces Development Time
Using MathWorks Tools
22
Simulink/Stateflow
MCU FPGA ASIC
C / C++ VHDL / Verilog
Gen
era
te
Embedded Coder
Production Code
SIL
/PIL
Gen
era
te
Verify
PLC PAC
Structured Text
Gen
era
te
Verify
Additional Coders
DSP
MATLAB
23
Embedded Coder Generate C / C + + code for mass production
Verify generated code
Deploy on evaluation boards
for On Target RCP
Software In the Loop Simulation
.c
.cpp
Processor In the Loop Simulation
MATLAB File Portable ANSI/ISO C code, or
target-specific optimizations
Floating-point or fixed-point*
*requires Fixed-Point Designer
Optimizations for RAM/ROM
and Execution speed
Simulink/Stateflow Model
24
Optimization and Verification Support
Code Replacement Result
Execution profiling Stack usage
MCU/
DSP Operation
Replace-
ment
Speed-
Up
Infineon
Tricore
32-bit
addition
(_sat int)
a + b; 17.1X
TI
C6416 FIR filter
_sadd
(a, b); 6.2X
Profiling for specific targets
Code Replacement APIs and Reference Examples
Processor-in-the-Loop APIs and Reference Examples
25
Embedded Coder Demo Code Optimization and Code Replacement
26
Benefits of Embedded Coder
With Simulink / Stateflow models and MATLAB files
You can program embedded system for production!
RCP on the target processor provides more realistic
production behavior!
Automated code verification using SIL / PIL helps ensure
that embedded behavior matches the model simulation!
27
General Motors: Development of the Volt
Nearly 100% of the software for
many of Volt’s modules was
generated automatically.
“We have a single source for
how a particular function
should behave. Automatic
code generation using The
MathWorks’ Real-Time
Workshop Embedded Coder
was vital to meeting Volt’s
aggressive program timing.”
Greg Hubbard
Senior Manager
Credit: General Motors LLC 2011
Credit: General Motors LLC 2011
28
Simulink/Stateflow
MCU FPGA ASIC
C / C++ VHDL / Verilog
Gen
era
te
C Coders
Verify
Gen
era
te
Verify
PLC PAC
Structured Text
Gen
era
te
Verify
DSP
MATLAB
HDL Coder
PLC Coder
29
Target independent VHDL /
Verilog HDL
Optimized design resources
(Circuit size & speed trade off)
Iterative design in conjunction
with FPGA IDE
HDL Coder Generate HDL code from MATLAB and Simulink
Testbench generation for
verifying generated code
Verification using HDL simulator
or FPGA (Requires HDL Verifier)
.v
.vhd
HDL Coder
Simulink/Stateflow Model
MATLAB File
31
HDL Coder Demo HDL code generation resource settings for FIR filter
Original Model Optimized for circuit diagram( Resource
sharing time-sharing )
Optimized for speed
(Pipeline)
Multiplier
×4
Multiplier
×1
Multiplier
×4
Code generation
report
Block properties for
generating HDL
32
Benefits of HDL Coder
Can develop FPGA / ASIC designs using models!
Automate code generation
Optimization of hardware / software is possible!
– Algorithm developed in MTLAB/Simulink, is then implemented for
optimized performance and resource utilization
Verification using cosimulation with HDl simulators
RCP / HIL model and verification on FPGAs!
– FILS = FPGA In the Loop Simulation
33
Faraday Accelerates SIP Development and
Shrinks NAND Flash Controller ECC Engine
Gate Count by 57%
Challenge Accelerate the development of SoCs and ASICs
Solution Use MathWorks tools for Model-Based Design to
speed up system-level simulations, improve system
performance, and shorten time-to-market
Results Simulations 200 times faster
Throughput performance increased by 15%
Gate count cut by 57%
―The Simulink environment is ideal for
system-level architecture exploration.
The simulations are 200 times faster
than they were in our previous
workflow — and Simulink models can
be easily converted to C as well as to
HDL code, which enables high
scalability and reusability.‖
Ken Chen
Faraday
Faraday’s silicon IP on an SoC.
34
Simulink/Stateflow
MCU FPGA ASIC
C / C++ VHDL / Verilog
Gen
era
te
C Coders
Verify
Gen
era
te
Verify
PLC PAC
Structured Text
Gen
era
te
Verify
DSP
HDL Coder
PLC Coder
35
Simulink PLC Coder Generate code for PLCs
Generate techbench
for verifying
generated ST
.st
Generate Structured Text
IEC 61131-3 Compliant
Structured Text
Supports various IDEs
– 3S CoDeSys
– B&R Automation Studio
– Beckhoff TwinCAT
– Siemens SIMATIC Step 7
– Open PLC
– Etc Simulink/Stateflow Model
36
Simulink Model
PLC Coder Demo
Structured Text (for CoDeSys)
37
Model-Based Design for PLCs
HIL Testing Test controller running on PLC
with HIL simulator
Develop Controller Use model to develop and
implement controller
Machine
Machine model Controller model
PLC
ST
Machine model Controller model
PLC
ST C
HILS simulator
38
Benefits of Simulink PLC Coder
Develop PLC control logic using Model-Based Design
Rapid deploy controller software to PLC
Test controller software running on PLC with actual
machine or HILS simulator
39
Festo Develops Innovative Robotic Arm Using
Model-Based Design
Challenge Design and implement a control system for
a pneumatic robotic arm
Solution Use Simulink and Simulink PLC Coder to
model, simulate, optimize, and implement the
controller on a programmable logic controller
Results
Complex PLC implementation automated
Technology and innovation award won
New business opportunities opened
The Festo Bionic Handling Assistant.
Image © Festo AG.
40
Summary
System Design
Algorithm Development Explore, verify, implement
MATLAB File/
Simulink Model
Specs Validate Data
MATLAB File/
Simulink Model
MCU/DSP
FPGA/ASIC
HDL
C/C++
RCP/HILS
PLC
ST
C
Code generation bridges design and
implementation to improve development
efficiency and increase verification rigor
41
Thank you!
© 2013 The MathWorks, Inc. MATLAB and Simulink are registered
trademarks of The MathWorks, Inc. See www.mathworks.com/trademarks
for a list of additional trademarks. Other product or brand names may be
trademarks or registered trademarks of their respective holders.