]> rtime.felk.cvut.cz Git - jenkicar/rpp-simulink.git/blob - doc/rpp_simulink.tex
Merge branch 'maint-rm48' into rm48/master
[jenkicar/rpp-simulink.git] / doc / rpp_simulink.tex
1 \newcommand{\superscript}[1]{\ensuremath{^{\textrm{\small#1}}}}
2 \newcommand{\subscript}[1]{\ensuremath{_{\textrm{\small#1}}}}
3
4 \documentclass{scrreprt}
5
6 \usepackage{graphicx} % images and graphics
7 \usepackage{paralist} % needed for compact lists
8 \usepackage[normalem]{ulem} % needed by strike
9 \usepackage{listings} % required for code blocks
10 \usepackage[urlcolor=blue,colorlinks=true,hyperfootnotes=false]{hyperref} % links
11 \usepackage[utf8x]{inputenc}  % char encoding
12 \usepackage[bottom]{footmisc} % footnotes
13 \usepackage{todonotes}
14
15 % header
16 \usepackage[top=2.5cm, bottom=2.5cm, left=2.5cm, right=2.5cm]{geometry}
17 \usepackage{float} % To fix images position
18
19 % Prettify code documentation
20 \usepackage{color}
21 \definecolor{gray97}{gray}{.97}
22 \definecolor{gray75}{gray}{.75}
23 \definecolor{gray45}{gray}{.45}
24 \lstset{ frame=Ltb,
25      framerule=0pt,
26      aboveskip=0.5cm,
27      framextopmargin=3pt,
28      framexbottommargin=3pt,
29      framexleftmargin=0.4cm,
30      framesep=0pt,
31      rulesep=.4pt,
32      backgroundcolor=\color{gray97},
33      rulesepcolor=\color{black},
34      %
35      stringstyle=\ttfamily,
36      showstringspaces = false,
37      basicstyle=\small\ttfamily,
38      commentstyle=\color{gray45},
39      keywordstyle=\bfseries,
40      %
41      numbers=left,
42      numbersep=15pt,
43      numberstyle=\tiny,
44      numberfirstline = false,
45      breaklines=true,
46      xleftmargin=20px,
47    }
48
49 % Spacing
50 \linespread{1.15} % Lines spacing
51 \setlength{\plitemsep}{0.5\baselineskip} % List items spacing
52 \definecolor{deepblue}{RGB}{0,0,61}
53 \definecolor{deepgreen}{RGB}{0,80,0}
54 \hypersetup{linkcolor=deepblue,citecolor=deepgreen,}
55
56 % Table of content depth
57 \setcounter{tocdepth}{2}
58
59 % Landscape pages
60 \usepackage{lscape}
61 \usepackage{pdflscape}
62
63 % Change page
64 \usepackage{changepage}
65
66 % Font options
67 % Sans-serif
68 % \renewcommand{\familydefault}{\sfdefault}
69 % Better PDF font
70 \usepackage{lmodern}
71
72 % Multiple columns
73 \usepackage{multicol}
74 \usepackage{caption}
75
76 \newcommand{\repo}{$\langle$repo$\rangle$}
77
78 \begin{document}
79
80 % Title
81 \newcommand{\HRule}{\rule{\linewidth}{0.5mm}}
82
83 \begin{titlepage}
84 \begin{center}
85
86 % Upper part of the page
87 \includegraphics[width=0.40\textwidth]{images/logo_ctu.pdf}\\[1cm]
88 \textsc{\LARGE Czech Technical University in Prague}\\[1.5cm]
89
90
91 % Document title
92 \HRule
93 \vspace{0.4cm}
94 {\huge \bfseries Simulink code generation target for Texas~Instruments
95   RM48 platform\par}
96 \vspace{0.4cm}
97 \HRule \\[1.5cm]
98
99
100 % Author
101 \emph{Authors:}\\
102 Carlos \textsc{Jenkins}\\
103 Michal \textsc{Horn}\\
104 Michal \textsc{Sojka}\\[\baselineskip]
105
106 \vfill
107
108 \emph{Version:}
109 \input{version.tex}
110
111 % Bottom of the page
112 {\large \today}
113
114 \end{center}
115 \end{titlepage}
116 % Title end
117
118 \tableofcontents
119
120 \newpage
121
122 \listoffigures
123
124 \newpage
125
126 %\addtolength{\parskip}{\baselineskip} % Paragraph spacing
127
128 \chapter{Introduction}
129 \label{chap-introduction}
130
131 This text serves as a documentation for the Rapid Prototyping Platform
132 (RPP) project based on Texas Instruments RM48 safety microcontroller.
133 Originally, the RPP project was created for TMS570 microcontroller and
134 the port to RM48 was derived from it under a contract with Eaton
135 Corporation. As this document is still in beta version, some
136 references to the original TMS570-based RPP remain in it.
137
138
139 The document contains step-by-step instructions for installation of
140 development tools, information about Simulink Coder configuration,
141 describes how to create new models as well as how to download the
142 resulting firmware to the hardware. It can also be used as a reference
143 for a testing tool, Matlab Simulink blocks and RPP Matlab Simulink
144 Code generator. The document also provides an overall description of
145 the hardware design and architecture of its control software.
146
147 \section{Background}
148 \label{sec-background}
149
150 The Rapid Prototyping Platform is an ECU (Electronic Control Unit) designed for
151 use in Automotive, thus requirements for Automotive communication interfaces,
152 durable IO ports and analog-digital converters were applied.
153
154 The ECU is controlled by TMS570LS5137ZWT MCU, which is an ARM Cortex R4 based
155 microcontroller developed by Texas Instruments. This MCU contains several
156 protective mechanisms (two cores in lockstep, error correction mechanisms for
157 SRAM and Flash memory, voltage monitoring, etc.) to fulfill the requirements for
158 safety critical applications. See~\cite{rm48xtechnicalreferencemanual2013}
159 for details.
160
161 In order to develop non-trivial applications for the RPP, an operating
162 system is necessary. The RPP is based on FreeRTOS -- an opensource operating
163 system real-time kernel, aimed not only at embedded systems. The FreeRTOS
164 provides an API for creating and managing multiple tasks, scheduler, memory
165 manager, semaphores, queues, mutexes, timers and lots of other features which can
166 be used in the applications. See~\cite{usingthefreertos2009} for more details.
167
168 Even with the operating system it is quite hard and non-intuitive to
169 control the hardware directly. That is the point when abstraction
170 comes into the play. The RPP software is made of several layers
171 implementing, from the bottom to the top, low-level device drivers,
172 hardware abstraction for common functionality on different hardware
173 and an API which is easy to use in applications. The operating
174 system and the control software, can be compiled as a library and
175 easily used in any project. More details about the library can be
176 found in Chapter~\ref{chap-c-support-library} and in~\cite{michalhorn2013}.
177
178 Because humans make mistakes and in safety critical applications any mistake can
179 cause damage, looses of money or in the worst case even death of other people,
180 the area for making mistakes has to be as small as possible. An approach called
181 Model--based \cite{modelbasedwiki2013} development has been introduced. In
182 Simulink  the application is developed as a model made of interconnected blocks. 
183 Every block implements some functionality. For example one block
184 receives a voltage from an analog--digital converter, provides the value as an
185 input to another block which implements some clever algorithm and the product is
186 passed as an input to another block, which sends the value as a CAN message to
187 some other MCU. The final model can be simulated and tested even before the real
188 hardware exists. Finally a C code is generated from the model by a Simulink Code
189 Generator. The code can be compiled by the MCU compatible compiler and
190 downloaded to the MCU Flash memory on the device. Because every block and code
191 generated from the block has to pass a series of tests during their development,
192 the area for making mistakes during the application development has
193 been significantly reduced and developers can focus on the application instead of
194 the hardware and control software implementation. More information about Code
195 generation can be found in Chapter \ref{chap-simulink-coder-target}. For a
196 reference about Matlab Simulink, Embedded Coder and Simulink Coder,
197 refer to
198 \cite{embeddedcoderreference2013, ebmeddedcoderusersguide2013,
199   simulinkcoderreference2013, targetlanguagecompiler2013,
200   simulinkcoderusersguide2013, simulinkdevelopingsfunctions2013}.
201
202 \section{Software architecture}
203 \label{sec-software-architecture}
204 The basic RPP software, also called the RPP Library, is structured
205 into 5 layers, depicted in Figure~\ref{fig-layers}. The architecture
206 design was driven by the following guidelines:
207
208 \begin{compactitem}
209         \item Top-down dependency only. No lower layer depends on anything from
210 upper layers.
211 %       \item 1-1 layer dependency only. The top layer depends
212 % exclusively on the bottom layer, not on any lower level layer (except for a
213 % couple of exceptions).
214         \item Each layer should provide a unified layer interface
215 (\textsc{rpp.h}, \textsc{drv.h}, \textsc {hal.h}, \textsc{sys.h} and
216 \textsc{os.h}), so top layers depends on that layer  interface and not on
217 individual elements from that layer.  \end{compactitem}
218
219 \begin{figure}[H]
220 \begin{center}
221 \noindent
222 \includegraphics[width=250px]{images/layers.pdf}
223 \caption{The RPP library layers.}
224 \label{fig-layers}
225 \end{center}
226 \end{figure}
227
228 As a consequence of this division the source code files and interface files are
229 placed in private directories like \textsc{drv/din.h}. With this organization
230 user applications only needs to include the top layer interface files (for
231 example \textsc{rpp/rpp\_can.h}) to be able to use the selected library API.
232
233 The rest of the section provides basic description of each layer.
234
235 \subsection{Operating System layer}
236 \label{sec-operating-system-layer}
237 This is an operating system interchangeable layer, containing the FreeRTOS
238 source files. The system can be easily replaced by another version thanks to
239 this layer. For example it is possible to compile the library for Linux (using
240 POSIX version of the FreeRTOS), which can be desirable for some testing. The
241 source files can be found in the \textsc{$\langle$rpp\_lib$\rangle$/os}
242 folder.
243
244 The following FreeRTOS versions are distributed:
245 \begin{description}
246         \item[6.0.4\_posix] POSIX version, usable for compilation of the library
247 for Linux system.
248         \item[7.0.2] Prefered version of the FreeRTOS, distributed by
249 Texas Instruments. This version has been tested and is used in the current
250 version of the library.
251         \item[7.4.0] Newest version distributed by the Texas Instruments.
252         \item[7.4.2] Newer version available from FreeRTOS pages. Slightly
253 modified to run on RM48 MCU.
254 \end{description}
255
256 \subsection{System Layer} 
257 \label{sec-system-layer}
258 This layer contains system files with data types definitions, clock definitions,
259 interrupts mapping, MCU startup sequence, MCU selftests, and other low level
260 code for controlling some of the MCU peripherals. The source files can be found
261 in \textsc{$\langle$rpp\_lib$\rangle$/rpp/src/sys}, the header files can
262 be found in \textsc{$\langle$rpp\_lib$\rangle$/rpp/include/sys}
263 folder.
264
265 Large part of this layer was generated by the HalCoGen tool \ref{sec-halcogen}.
266
267 \subsection{HAL abstraction layer}
268 \label{sec-hal-abstraction-layer}
269 Hardware Abstraction Layer (HAL) creates an abstraction over the real hardware.
270 For example imagine an IO port with 8 pins. First four pins are connected to the
271 MCU directly to GPIO pins, another four pins are connected to an external
272 integrated circuit, communicating with the MCU via SPI. It would be annoying to
273 have to remember which group is which and to have two sets of control functions
274 for one peripheral. This layer maps every pin of the port to a control function
275 from the System Layer, groups the pins together, names them in a unified style
276 and provides common read, write and configure functions.
277
278 As a result, the higher layers do not have to know anything about the wiring of
279 the peripherals, they can just call read, write or configure function with a pin
280 name as a parameter and the HAL handles all the details.
281
282 The source files can be found in
283 \textsc{$\langle$rpp\_lib$\rangle$/rpp/src/hal} and the header files can
284 be found in \textsc{$\langle$rpp\_lib$\rangle$/rpp/include/hal} folder.
285
286 \subsection{Drivers layer} 
287 \label{sec-drivers-layer}
288 The Drivers layer contains code for controlling the RPP peripherals. The layer
289 benefits from the lower layers thus it is not too low level, but still there are
290 some peripherals like ADC or H-bridge, which needs some special procedure for
291 initialization and running, that would not be very intuitive for the user. For
292 example the H-bridge needs a watchdog reset task to be started before the bridge
293 is enabled.
294
295 The source files can be found in
296 \textsc{$\langle$rpp\_lib$\rangle$/rpp/src/drv} and the header files can
297 be found in \textsc{$\langle$rpp\_lib$\rangle$/rpp/include/drv} folder.
298
299 \subsection{RPP Layer}
300 \label{sec-rpp-layer} 
301 The RPP Layer is the highest layer of the control software. This layer provides
302 an easy to use set of functions for every peripheral and requires only basic
303 knowledge about them. For example, to control the H-bridge,
304 the user can  just call  \textsc{rpp\_hbr\_init()} function to enable the H-bridge
305 and the function calls a sequence of Drivers layer functions to start the
306 Watchdog and configure the peripheral.
307
308 The source files can be found in
309 \textsc{$\langle$rpp\_lib$\rangle$/rpp/src/rpp} and the header files can
310 be found in \textsc{$\langle$rpp\_lib$\rangle$/rpp/include/rpp}.
311
312 \section{Hardware description}
313 \label{sec-hardware-description}
314
315 This section provides reference documentation for the RPP board:
316
317 %%TODO: operating conditions as a reference to the Ti documentation
318
319 \begin{compactitem}
320         \item Layout description.
321         \item Connectors pinout.
322         \item Modules capabilities and features.
323 \end{compactitem}
324
325 The Rapid Prototyping Platform is based on a TMDSRM48HDK development kit developed and distributed by Texas Instruments. The kit is depicted in Figure \ref{fig-board_photo}.
326
327 \begin{figure}[H]\begin{center}
328         \noindent
329         \includegraphics[width=300px]{images/board.png}
330         \caption{The RPP board \cite[p. 8]{rm48hdkusersguide2013}}
331         \label{fig-board_photo}
332 \end{center}\end{figure}
333
334 Only a subset of the peripherals available on the kit is implemented in the control software. A block scheme in Figure \ref{fig-blocks} ilustrates the implemented peripherals and their connection with the MCU, expansion connectors and other components on the development kit.
335
336 \begin{figure}[H]\begin{center}
337         \noindent
338         \includegraphics[width=400px]{images/blocks.png}
339         \caption{The peripherals block scheme.}
340         \label{fig-blocks}
341 \end{center}\end{figure}
342
343 For pinout description of the implemented peripherals refer the RM48HDK User's Guide \cite{rm48hdkusersguide2013}.
344
345 \subsection{Logic IO}
346 \label{sec-logic-io}
347
348 \subsubsection{Digital Inputs and Outputs (DIN and DOUT)}
349 \label{par-digital-inputs-outputs}
350  \begin{compactitem}
351         \item 46 pins available on Expansion connector J11.
352         \item 8 pins available on GIOA
353         \item 8 pins available on GIOB
354         \item 30 pins available on NHET1. Pins NHET1 6 and NHET1 13 are disabled.
355         \item All the pins are configurable as inputs and outputs with different modes:
356          \begin{compactitem}
357                 \item Push/Pull or Open Drain for Output configuration.
358                 \item Pull up, Pull down or tri-stated for Input configuration.
359          \end{compactitem}
360         \item Some of the pins are connected to LEDs or to a button. See Figure \ref{fig-blocks} or refer \cite{rm48hdkusersguide2013} for the connection description.
361  \end{compactitem}
362
363 \subsubsection{Analog Input (ADC)}
364 \label{par-analog-input}
365  \begin{compactitem}
366         \item 16 channels available on the Expansion connector J9.
367         \item Range for 0-5 volts.
368         \item 12 bits resolution.
369         \item Using CPU ADC.
370  \end{compactitem}
371
372 \subsection{Communication}
373 \label{sec-communication}
374 \subsubsection{CAN bus (CAN)}
375 \label{par-can}
376 \begin{compactitem}
377         \item 2 ports available ready for connection to the CAN bus on connector J2 and J3.
378         \item 3 ports available as an interface for external CAN bus drivers on the Expansion connector J11.
379         \item High speed.
380         \item Recover from error.
381         \item Detection of network errors.
382 \end{compactitem}
383
384 \subsubsection{Serial Comm. Interface (SCI)}
385 \label{par-sci}
386 \begin{compactitem}
387         \item 1 port available on connector J7.
388         \item Variable baud rate. Tested on 9600 and 115200.
389         \item RS232 standard compatible.
390 \end{compactitem}
391
392 \section{Document structure}
393 \label{sec-document-structure}
394 The structure of this document is as follows:
395 Chapter~\ref{chap-getting-started} gets you started using the RPP.
396 Chapter~\ref{chap-c-support-library} describes the RPP library.
397 Chapter~\ref{chap-simulink-coder-target} covers the Simulink code
398 generation target and finally Chapter~\ref{chap-rpp-test-software}
399 documents a tool for interactive testing of RPP functionality.
400
401 \chapter{Getting started}
402 \label{chap-getting-started}
403
404 \section{Software requirements}
405 \label{sec-software-requirements}
406 The RPP software stack has been developed to be functional on Windows and
407 Linux platforms. The following subsections mention the recommended
408 versions of the required software tools/packages.
409
410 \subsection{Linux environment} 
411 \label{sec-linux-environment}
412 \begin{itemize}
413         \item Debian based 64b Linux distribution (Debian 7.0 or Ubuntu 14.4 for
414 example).
415         \item Kernel version 3.11.0-12.
416         \item GCC version 4.8.1
417         \item GtkTerm 0.99.7-rc1
418         \item TI Code Composer Studio 5.5.0.00077
419         \item Matlab 2013b 64b
420         \item HalCoGen 4.00 (optional)
421         \item Uncrustify 0.59 (optional, see Section \ref{sec-compilation})
422         \item Doxygen 1.8.4 (optional, see Section \ref{sec-compiling-api-documentation})
423     \item Git 1.7.10.4 (optional)
424 \end{itemize}
425
426 \subsection{Windows environment}
427 \label{sec-windows-environment}
428 \begin{itemize}
429         \item Windows 7 Enterprise 64b Service Pack 1.
430         \item Microsoft Windows SDK v7.1
431         \item Bray Terminal v1.9b
432         \item TI Code Composer Studio 5.5.0.00077
433         \item Matlab 2013b 64b
434         \item HalCoGen 4.00 (optionally)
435         \item Doxygen 1.8.4 (optionally, see Section \ref{sec-compiling-api-documentation}) 
436         \item Uncrustify 0.59 (optionally, see Section \ref{sec-compilation})
437     \item Git 1.9.4.msysgit.2 (optional)
438 \end{itemize}
439
440 \section{Software and tools} 
441 \label{sec-software-and-tools}
442
443 \subsection{TI Code Composer Studio}
444 \label{sec-ti-ccs}
445 Code Composer Studio (CCS) is the official Integrated Development Environment
446 (IDE) for developing applications for Texas Instruments embedded processors. CCS
447 is multiplatform Software based on
448 Eclipse Open Source IDE.
449
450 CCS includes Texas Instruments Code Generation Tools (CGT)
451 \cite{armoptimizingccppcompiler2012, armassemblylanguagetools2012}
452 (compiler, linker, etc). Simulink code generation requires the CGT to be
453 available in the system, and thus, even if no library development
454 will be done or the IDE is not going to be used CCS is still required.
455
456 You can find documentation for CGT compiler in \cite{armoptimizingccppcompiler2012} and
457 for CGT archiver in \cite{armassemblylanguagetools2012}.
458
459 \subsubsection{Installation on Linux} 
460 \label{sec-installation-on-linux}
461 Download CCS for Linux from:
462
463         \begin{quotation}
464 \url{http://processors.wiki.ti.com/index.php/Category:Code\_Composer\_Studio\_v5}
465         \end{quotation}
466
467 Once downloaded, add executable permission to the installation file and launch
468 the installation by executing it. Installation must be done as root in order to
469 install a driver set.
470
471 \lstset{language=bash}
472 \begin{lstlisting}
473 chmod +x ccs_setup_5.5.0.00077.bin
474 sudo ./ccs_setup_5.5.0.00077.bin
475 \end{lstlisting}
476
477 After installation the application can be executed with:
478
479 \lstset{language=bash}
480 \begin{lstlisting}
481 cd <ccs>/ccsv5/eclipse/
482 ./ccstudio
483 \end{lstlisting}
484
485 The first launch on 64bits systems might fail. This can happen because CCS5 is
486 32b application and thus requires 32bits libraries:
487
488 \lstset{language=bash}
489 \begin{lstlisting}
490 sudo apt-get install libgtk2.0-0:i386 libxtst6:i386
491 \end{lstlisting}
492
493 If the application crashes with a segmentation fault edit file:
494
495 \lstset{language=bash}
496 \begin{lstlisting}
497 nano
498 <ccs>/ccsv5/eclipse/plugins/com.ti.ccstudio.branding_<version>/plugin_customization.ini
499 \end{lstlisting}
500
501 And change key \textsc{org.eclipse.ui/showIntro} to false.
502
503 \subsubsection{Installation on Windows}
504 \label{sec-installation-on-windows}
505 The installation for Windows is more straightforward than the previous procedure
506 for Linux.
507
508 Download CCS for Windows from:
509
510         \begin{quotation}
511 \url{http://processors.wiki.ti.com/index.php/Category:Code\_Composer\_Studio\_v5}
512         \end{quotation}
513
514 Once downloaded run the ccs\_setup\_5.5.0.00077.exe and install the CCS.
515
516 \subsubsection{First launch} 
517 \label{sec-first-launch}
518 If no other licence is available, choose ``FREE License -- for use with XDS100
519 JTAG Emulators'' from the licensing options. Code download for the board is using
520 that particular hardware.
521
522 \subsection{Matlab/Simulink}
523 \label{sec-matlab-simulink}
524 Matlab Simulink is a set of tools, runtime environment and development
525 environment for Model--Based \cite{modelbasedwiki2013} applications development,
526 simulations and generation code for target platforms.  Supported Matlab Simulink
527 version is R2013b for 64 bits Linux and Windows.
528
529 \subsection{HalCoGen}
530 \label{sec-halcogen}
531 HalCoGen (HAL Code Generator) is a tool for graphical configuration of peripherals, clocks, interrupts and other MCU parameters. It generates C code which can be imported to the Code Composer Studio.
532
533 The tool is available for Windows at 
534         \begin{quotation}
535 \url{http://www.ti.com/tool/halcogen?keyMatch=halcogen&tisearch=Search-EN}
536         \end{quotation}
537
538 The HalCoGen has been used in early development stage to generate the base code for some of the peripheral. The trend is to not to use the HalCoGen any more, because the generated code is not reliable enough for safety application. Anyway it is sometimes helpful to use it as a reference.
539
540 The HalCoGen is distributed for Windows only, but can be run on Linux with Wine 1.6.2.
541
542 \subsection{GtkTerm and Bray Terminal}
543 \label{sec-gtkterm-bray-terminal}
544 Most of the interaction with the board is done through a RS-232 serial
545 connection. The terminal Software used for communication is called GtkTerm for
546 Linux and Bray terminal for Windows.
547
548 To install GtkTerm execute:
549
550 \lstset{language=bash}
551 \begin{lstlisting}
552 sudo apt-get install gtkterm
553 \end{lstlisting}
554
555 The Bray Terminal does not require any installation and the executable file is
556 available at 
557
558 \begin{quotation}
559 \url{https://sites.google.com/site/terminalbpp/}
560 \end{quotation}
561
562 \subsection{C Compiler}
563 \label{sec-c-compiler}
564 A C language compiler has to be available on the development system to be able to
565 compile Matlab Simulink blocks S-functions.
566
567 For Linux a GCC 4.8.1 compiler is recommended and can be installed with a
568 command
569
570 \lstset{language=bash}
571 \begin{lstlisting}
572 sudo apt-get install gcc
573 \end{lstlisting}
574
575 For Windows, the C/C++ compiler is a part of Windows SDK, which installation
576 file is available at 
577
578 \begin{quotation}
579 \url{http://www.microsoft.com/en-us/download/details.aspx?id=8279}
580 \end{quotation}
581
582 \section{Project Installation}
583 \label{sec-project-installation}
584 The RPP project is distributed in three packages and a standalone pdf file,
585 containing this documentation. Every package is named like
586 \textsc{package\_name-version.zip}. The three packages are: 
587
588 \begin{description}
589         \item[rpp-lib] Contains the source codes of the RPP Library,
590 described in Chapter \ref{chap-c-support-library}. If you want to make any
591 changes in the drivers or RPP API, this library has to be compiled and linked
592 with the other two applications in the other two packages. The compile procedure
593 can be found in Section \ref{sec-compilation}.  
594         \item[rpp-simulink] Contains source codes of the Matlab Simulink blocks, demo
595 models and scripts for downloading the resulting firmware to the target from the
596 Matlab Simulink. Details can be found in Chapter \ref{chap-simulink-coder-target}.
597
598 The package also contains the binary file of the RPP Library and all headers and
599 other files necessary for building and downloading the models.
600         \item[rpp-test-sw]  Contains an application for rapid testing and direct
601 controlling the RPP board over the Serial Interface.
602
603 The package also contains the binary file of the RPP Library and all headers and
604 other files necessary for building and downloading the application.
605 \end{description}
606
607 \subsection{rpp-lib}
608 \label{sec-rpp-lib-installation}
609 You may not need to deal with this package at all because the compiled library is
610 distributed with the applications. But in case of contributions or further
611 development done by your team, this subsection describes how to open the project
612 in development environment and how to use the resulting static library in an
613 application.
614
615 \begin{enumerate}
616         \item Unzip the \textsc{rpp-lib-version.zip} file.
617         \item Open the Code Composer Studio (see Section \ref{sec-ti-ccs}).
618         \item Follow the procedure for openning the projects in CCS in Section
619 \ref{sec-openning-of-existing-project} and open the rpp-lib project.  \item
620 Compile the static library using a procedure in Section \ref{sec-compilation}.
621 The binary file will appear in the project root directory.
622         \item Copy the binary file to the application, where you want to test
623 and use the new library version.  
624         \begin{itemize}
625                 \item In the rpp-simulink application the library binary file is
626 present in \textsc{rpp/lib} folder. 
627                 \item In the rpp-test-sw application the library binary file is
628 present in \textsc{rpp-lib} folder.  
629         \end{itemize}
630 \end{enumerate}
631
632 \subsection{rpp-simulink}
633 \label{sec-rpp-simulink-installation}
634 If you want to access the demo models or build your own models using the RPP blocks, if
635 you want to generate a C code from the models, build it to a binary firmware for the RPP board and download it to the real hardware, follow these steps.
636
637 \begin{enumerate}
638         \item Unzip the \textsc{rpp-simulink-version.zip} file.
639         \item Follow the procedure in Section
640 \ref{sec-configuration-simulink-for-rpp} for configuring the Matlab Simulink for
641 the RPP project.  
642         \item Follow the procedure in Section \ref{sec-crating-new-model} for
643 instruction about creating your own model which will be using the RPP Simulink
644 blocks or follow the instructions in Section \ref{sec-running-model-on-hw}
645 for downloading the firmware to the real RPP hardware.
646 \end{enumerate}
647
648 \subsection{rpp-test-sw}
649 \label{sec-test-sw-installation}
650 If you want a direct control over the hardware for example to test your
651 modifications in the RPP Library follow this procedure for the rpp-test-sw
652 application installation.
653
654 \begin{enumerate}
655         \item Unzip the \textsc{rpp-test-sw-version.zip} file.
656         \item Open the Code Composer Studio (see Section \ref{sec-ti-ccs}).
657         \item Follow the procedure for openning the projects in CCS in Section
658 \ref{sec-openning-of-existing-project} and open both, the \textsc{rpp-lib} and
659 the \textsc{rpp-test-sw} projects.  
660         \item Right click on the \textsc{rpp-test-sw} project in the
661 \textsc{Project Explorer} and select \textsc{Build Project}. Ignore any errors
662 in the \textsc{rpp-lib} project.  
663         \item Follow the instructions in Section
664 \ref{sec-running-software-on-hw} to download, debug and run the software on the
665 target hardware. CCS will ask you wether to proceed with the detected errors in
666 \textsc{rpp-lib} project. Do not mind them and click to the \textsc{Proceed} button
667 to continue.
668 \end{enumerate}
669
670 \section{Code Composer Studio usage}
671 \label{sec-code-composerpstudio-usage}
672
673 \subsection{Opening of existing project}
674 \label{sec-openning-of-existing-project}
675 The project opening procedure is similar to standard Eclipse project opening.
676
677 \begin{enumerate}
678         \item Launch Code Composer Studio
679         \item Select \textsc{File$\rightarrow$Import}
680         \item In the dialog window select \textsc{Code Composer
681 Studio$\rightarrow$Existing CCS Eclipse project} as an import source as depicted
682 in Figure \ref{fig-import-project}.  
683         \item In the next dialog window click on
684 \textsc{Browse} button and find the root directory of the project.
685         \item Select the requested project in the \textsc{Discovered project}
686 section so that the result looks like in Figure \ref{fig-select-project}.  
687         \item Click on \textsc{Finish} button.
688 \end{enumerate}
689
690 \begin{figure}[H]\begin{center}
691         \includegraphics[width=350px]{images/import_project.png}
692         \caption{Import project dialog}
693         \label{fig-import-project}
694 \end{center}\end{figure}
695
696 \begin{figure}[H]\begin{center}
697         \includegraphics[width=350px]{images/select_project.png}
698         \caption{Select project dialog}
699         \label{fig-select-project}
700 \end{center}\end{figure}
701
702 \subsection{Creating new project}
703 \label{sec-creating-new-project}
704 In \textsc{\repo/rpp/lib/apps/} there are two RPP based
705 applications, \textsc{helloworld} and \textsc{helloworld\_posix}, that are
706 already configured for the RPP Library. It is advised that new applications use
707 this project as a foundation.
708
709 To create a new application copy this directory and rename it. Now open files
710 \textsc{.project}, \textsc{.cproject} and \textsc{.ccsproject} (if available)
711 and change any occurrence of the work \textsc{helloworld}
712 with the name of your project. Use lower case ASCII letters and underscores only.
713
714 \textbf{Steps to configure a new CCS (ARM, using CGT) RPP application:}
715
716 \begin{compactenum}
717         \item Create a new CCS project. \newline{}
718 \noindent\includegraphics[width=400px]{images/base_1.png}
719         \item Create a normal folder \textsc{include}.
720         \item Create a source folder \textsc{src}.
721         \item Add common \textsc{.gitignore} to the root of that project:
722 \lstset{language=}
723 \begin{lstlisting}
724 Debug
725 Release
726 .settings/*
727 \end{lstlisting}
728 \newpage
729         \item Add new variable \textsc{RPP\_LIB\_ROOT} and point to this
730 repository branch root.\newline{}
731 \noindent\includegraphics[width=400px]{images/base_2.png}
732         \item Add \textsc{rpp-lib.lib} static library to linker libraries and
733 add \textsc{RPP\_LIB\_ROOT} to the library search path.\newline{}
734 \noindent\includegraphics[width=400px]{images/base_3.png}
735 \newpage
736         \item Configure linker to retain \textsc{.intvecs} from RPP static
737 library.\newline{} \noindent\includegraphics[width=350px]{images/base_4.png}
738         \item Configure compiler to include local includes, OS includes for
739 RM48 and RPP includes, in that order.\newline{}
740 \noindent\includegraphics[width=350px]{images/base_5.png}
741 \newpage
742         \item Configure compiler to allow GCC extensions.\newline{}
743 \noindent\includegraphics[width=400px]{images/base_6.png}
744         \item Import and link (\underline{do not copy!}) linker file and board
745 upload descriptor.\newline{}
746 \noindent\includegraphics[width=200px]{images/base_7.png}
747 \end{compactenum}
748
749 \textbf{Steps to configure a new GCC (x86(\_64)) RPP simulated application:}
750
751 \begin{compactenum}
752         \item Create a new managed C project that uses Linux GCC toolchain.
753         \item Create a source folder \textsc{src}. Link all files from original
754 CCS application to this folder.
755         \item Create a normal folder \textsc{include}. Create a folder
756 \textsc{rpp} inside of it.  
757         \item Add common \textsc{.gitignore} to the root of that project:
758 \lstset{language=}
759 \begin{lstlisting}
760 Debug
761 Release
762 .settings/*
763 \end{lstlisting}
764 \newpage
765         \item Add new variable \textsc{RPP\_LIB\_ROOT} and point to this
766 repository branch root.\newline{}
767 \noindent\includegraphics[width=400px]{images/base_posix_1.png}
768         \item Configure compiler to include local includes, CCS application
769 includes, OS includes for POSIX and RPP includes, in that order.\newline{}
770 \noindent\includegraphics[width=400px]{images/base_posix_2.png}
771 \newpage
772         \item Add \textsc{rpp} and \textsc{pthread}to linker libraries and add
773 \textsc{RPP\_LIB\_ROOT} to the library search path.\newline{}
774 \noindent\includegraphics[width=400px]{images/base_posix_3.png}
775 \end{compactenum}
776
777 \textbf{In general any RPP application uses the layout/template:}
778
779 \begin{enumerate}
780         \item Include RPP library header file. You may also include only a
781 selected modules to save space.  \lstset{language=c++}
782 \begin{lstlisting}
783 #include "rpp/rpp.h"
784 \end{lstlisting}
785
786 You may not want to include the whole library to save space and compile time. In
787 this case you may include only those modules, that you want to use. Inclusion
788 selected modules only requires two more
789 header files to be included as well: base.h and, in case sci is used for printing, rpp/sci.h.
790 \begin{lstlisting}
791 #include "rpp/hbr.h" /* We want to use H-bridge */
792 #include <base.h>       /* This is a necessary base header file of the rpp library. */
793 #include "rpp/sci.h" /* This is needed, because we are using rpp_sci_printf in following examples. */
794 \end{lstlisting}
795
796 \newpage
797 \item Create one or as many FreeRTOS task function definitions as required. Those tasks should use
798   functions from this library.
799 \lstset{language=c++}
800 \begin{lstlisting}
801 void my_task(void* p)
802 {
803     static const portTickType freq_ticks = 1000 / portTICK_RATE_MS;
804     portTickType last_wake_time = xTaskGetTickCount();
805     while (TRUE) {
806         /* Wait until next step */
807         vTaskDelayUntil(&last_wake_time, freq_ticks);
808         rpp_sci_printf((const char*)"Hello RPP.\r\n");
809     }
810 }
811 \end{lstlisting}
812
813 \item Create the main function that will:
814  \begin{itemize}
815         \item Initialize the RPP board. If you have included only selected
816 modules in step 1, initialize only those modules by calling their init
817 functions, for
818 example rpp\_hbr\_init\(\).
819         \item Spawn the tasks the application requires. Refer to FreeRTOS API
820 for details.
821         \item Start the FreeRTOS Scheduler. Refer to FreeRTOS API for details.
822         \item Catch if idle task could not be created.
823
824 \lstset{language=c++}
825 \begin{lstlisting}
826 void main(void)
827 {
828     /* In case whole library is included: */
829         /* Initialize RPP board */
830         rpp_init();
831     /* In case only selected modules are included: */
832         /* Initialize HBR */
833             rpp_hbr_init();
834         /* Initialize sci for printf */
835         rpp_sci_init();
836         /* Enable interrups */
837         _enable_IRQ();
838
839     /* Spawn tasks */
840     if (xTaskCreate(my_task, (const signed char*)"my_task",
841             512, NULL, 0, NULL) != pdPASS) {
842         #ifdef DEBUG
843         rpp_sci_printf((const char*)
844             "ERROR: Cannot spawn control task.\r\n"
845         );
846         #endif
847         while (TRUE) { asm(" nop"); }
848     }
849
850     /* Start the FreeRTOS Scheduler */
851     vTaskStartScheduler();
852
853     /* Catch scheduler start error */
854     #ifdef DEBUG
855     rpp_sci_printf((const char*)
856             "ERROR: Problem allocating memory for idle task.\r\n"
857         );
858     #endif
859     while (TRUE) { asm(" nop"); }
860 }
861 \end{lstlisting}
862
863  \end{itemize}
864 \item Create hook functions for FreeRTOS:
865  \begin{itemize}
866  \item \textsc{vApplicationMallocFailedHook()} allows to catch memory allocation
867 errors.
868  \item \textsc{vApplicationStackOverflowHook()} allows to catch if a task
869 overflows it's stack.
870
871 \lstset{language=c++}
872 \begin{lstlisting}
873 #if configUSE_MALLOC_FAILED_HOOK == 1
874 /**
875  * FreeRTOS malloc() failed hook.
876  */
877 void vApplicationMallocFailedHook(void) {
878     #ifdef DEBUG
879     rpp_sci_printf((const char*)
880             "ERROR: manual memory allocation failed.\r\n"
881         );
882     #endif
883 }
884 #endif
885
886
887 #if configCHECK_FOR_STACK_OVERFLOW > 0
888 /**
889  * FreeRTOS stack overflow hook.
890  */
891 void vApplicationStackOverflowHook(xTaskHandle xTask,
892                                    signed portCHAR *pcTaskName) {
893     #ifdef DEBUG
894     rpp_sci_printf((const char*)
895             "ERROR: Stack overflow : \"%s\".\r\n", pcTaskName
896         );
897     #endif
898 }
899 #endif
900 \end{lstlisting}
901
902 \newpage
903  \end{itemize}
904 \end{enumerate}
905
906
907 \subsection{Running the software on the HW}
908 \label{sec-running-software-on-hw}
909 \subsubsection{Code Composer Studio Project}
910 \label{sec-ccs-run-project}
911 When the application is distributed as a CCS project, you have to open the
912 project in the CCS as described in the Section
913 \ref{sec-openning-of-existing-project}. Once the project is opened and built, it
914 can be easily downloaded to the target hardware with the following procedure:
915
916 \begin{enumerate}
917         \item Connect the Texas Instruments XDS100v2 USB emulator to the JTAG
918 port.  
919         \item Connect a USB cable to the XDS100v2 USB emulator and the
920 development computer.
921         \item Plug in the power supply.  
922         \item In the Code Composer Studio click on the
923 \textsc{Run$\rightarrow$Debug}. The project will  be optionally built and
924 the download process will start. The Code Composer Studio will switch into the debug
925 mode, when the download is finished.
926         \item Run the program by clicking on the \textsc{Run} button, with the
927 green arrow.  
928 \end{enumerate}
929
930 \subsubsection{Binary File}
931 \label{sec-binary-file}
932 If the application is distributed as a binary file, without source codes and CCS
933 project files, you can download and run just the binary file by creating a new
934 empty CCS project and configuring the debug session according to the following
935 procedure:
936
937 \begin{enumerate}
938         \item In Code Composer Studio click on
939 \textsc{File$\rightarrow$New$\rightarrow$CCS Project}.  
940         \item In the dialog window, type in a project name, for example
941 myBinaryLoad, Select \textsc{Device
942 variant} (ARM, Cortex R, RM48L952, Texas Instruments XDS100v2 USB Emulator)
943 and select project template to \textsc{Empty Project}. The filled dialog should
944 look like on the Figure \ref{fig-new-empty-project}
945         \item Click on the \textsc{Finish} button and new empty project will be
946 created.  
947         \item In the \textsc{Project Explorer} click on the project with a right
948 mouse button and in the context menu select \textsc{Debug
949 as$\rightarrow$Debug configurations}.
950         \item Click on a button \textsc{New launch configuration}
951         \item Rename the New\_configuration, for example to myConfiguration.
952         \item Select configuration target file by clicking the \textsc{File
953 System} button, finding and selecting the TMS5703137.ccxml file. The result
954 should look like on the Figure \ref{fig-debug-conf-main-diag}.  
955         \item On the \textsc{program} pane select the binary file you want to
956 download to the board.
957 Click on the \textsc{File System} button, find and select the binary file.
958 Rpp-test-sw.out for example. The result should look like on the Figure
959 \ref{fig-debug-conf-program-diag}.
960         \item You may also tune the target configuration like in the Section
961 \ref{sec-target-configuration}. 
962         \item Finish the configuration by clicking on the \textsc{Apply} button
963 and download the code by clicking on the \textsc{Debug} button. You can later
964 invoke the download also from the \textsc{Run$\rightarrow$Debug} CCS menu. You
965 may not need to create more Debug configurations and CCS empty projects as you
966 can easily change the binary file in the Debug configuration to load different
967 binary file.  
968 \end{enumerate}
969
970 \begin{figure}[H]\begin{center}
971         \includegraphics[width=350px]{images/new_empty_project.png}
972         \caption{New empty project dialog}
973         \label{fig-new-empty-project}
974 \end{center}\end{figure}
975
976 \begin{figure}[H]\begin{center}
977         \includegraphics[width=350px]{images/debug_configuration_main.png}
978         \caption{Debug Configuration Main dialog}
979         \label{fig-debug-conf-main-diag}
980 \end{center}\end{figure}
981
982 \subsection{Target configuration}
983 \label{sec-target-configuration}
984 Default target configuration erases the whole Flash memory, before downloading
985 the code. This is however not needed in most cases. You may disable this feature
986 by the following procedure: 
987 \begin{enumerate}
988         \item Right click on the project name in the \textsc{Project Browser}
989         \item Select \textsc{Debug as$\rightarrow$Debug Configurations}
990         \item In the dialog window select \textsc{Target} pane.
991         \item In the \textsc{Flash Settings}, \textsc{Erase Options} select
992 \textsc{Necessary sectors only}.
993         \item Save the configuration by clicking on the \textsc{Apply} button
994 and close the dialog.
995 \end{enumerate}
996
997 \begin{figure}[H]\begin{center}
998         \includegraphics[width=350px]{images/debug_configuration_program.png}
999         \caption{Configuration Program dialog}
1000         \label{fig-debug-conf-program-diag}
1001 \end{center}\end{figure}
1002
1003 \section{Matlab Simulink usage}
1004 \label{sec-matlab-simulink-usage}
1005
1006 \subsection{Configuring Simulink for RPP}
1007 \label{sec-configuration-simulink-for-rpp}
1008 Before any work or experiments with the RPP blocks and models can be done, the RPP target has to be configured to be able to find the ARM compiler, C compiler and some necessary files. Also the S-Functions of the blocks have to be compiled by the mex tool.
1009 \begin{enumerate}
1010 \item Download and install CCS for Linux:
1011
1012 Details on how to setup CCS are available in Section \ref{sec-ti-ccs}.
1013
1014 \item On Windows you have to tell the \textsc{mex} which C compiler it should be using. Open the command line, run the \textsc{mex} tool from the Matlab installation folder and select the C compiler.
1015
1016 \begin{lstlisting}[language=bash]
1017 C:\Program Files\MATLAB\R2013b\bin>mex -setup
1018
1019 Welcome to mex -setup.  This utility will help you set up
1020 a default compiler.  For a list of supported compilers, see
1021 http://www.mathworks.com/support/compilers/R2013b/win64.html
1022
1023 Please choose your compiler for building MEX-files:
1024
1025 Would you like mex to locate installed compilers [y]/n? y
1026
1027 Select a compiler:
1028 [1] Microsoft Software Development Kit (SDK) 7.1 in c:\Program Files (x86)\Microsoft Visual Studio 10.0
1029
1030 [0] None
1031
1032 Compiler: 1
1033
1034 Please verify your choices:
1035
1036 Compiler: Microsoft Software Development Kit (SDK) 7.1
1037 Location: c:\Program Files (x86)\Microsoft Visual Studio 10.0
1038
1039 Are these correct [y]/n? y
1040
1041 ***************************************************************************
1042   Warning: MEX-files generated using Microsoft Windows Software Development
1043            Kit (SDK) require that Microsoft Visual Studio 2010 run-time
1044            libraries be available on the computer they are run on.
1045            If you plan to redistribute your MEX-files to other MATLAB
1046            users, be sure that they have the run-time libraries.
1047 ***************************************************************************
1048
1049
1050 Trying to update options file: C:\Users\Michal\AppData\Roaming\MathWorks\MATLAB\R2013b\mexopts.bat
1051 From template:              C:\PROGRA~1\MATLAB\R2013b\bin\win64\mexopts\mssdk71opts.bat
1052
1053 Done . . .
1054
1055 **************************************************************************
1056   Warning: The MATLAB C and Fortran API has changed to support MATLAB
1057            variables with more than 2^32-1 elements.  In the near future
1058            you will be required to update your code to utilize the new
1059            API. You can find more information about this at:
1060            http://www.mathworks.com/help/matlab/matlab_external/upgrading-mex-files-to-use-64-bit-api.html
1061            Building with the -largeArrayDims option enables the new API.
1062 **************************************************************************
1063
1064 C:\Program Files\MATLAB\R2013b\bin>
1065 \end{lstlisting}
1066
1067 \item Install RPP Target:
1068
1069 Open Matlab and type on command window:
1070
1071 \lstset{language=Matlab}
1072 \begin{lstlisting}
1073 cd <rpp-simulink>/rpp/rpp/
1074 rpp_setup
1075 \end{lstlisting}
1076
1077 This will launch the RPP setup script. This script will ask the user to provide
1078 the path to the CCS compiler root directory (the directory where \textsc{armcl}
1079 binary is located), normally:
1080
1081 \begin{verbatim}
1082 <ccs>/tools/compiler/arm_5.X.X/
1083 \end{verbatim}
1084
1085 This script will, among other things, ask the user to provide the location of
1086 the armcl parent directory, infer and save some relevant CCS paths, add paths to
1087 Matlab path and build S-Function
1088 blocks for user's architecture (using Matlab's mex command line tool).
1089
1090 \item Create new model or load a demo:
1091
1092 Demos are located on \textsc{\repo/rpp/demo} or you can start a new model and
1093 configure target to RPP.  For new models see \htmladdnormallink{Target
1094 Reference}{\#target\_reference} section below.
1095 \end{enumerate}
1096
1097
1098 \subsection{Working with demo models}
1099 \label{sec-openning-demo-models}
1100 The demo models are available from the directory \textsc{\repo/rpp/demos}. To
1101 access the demo models for reference or for downloading to the RPP board you
1102 have to change the directory to the one, containing the desired demo. For
1103 example to open the cantransmit demo you have to type these commands into the
1104 Matlab command line:
1105
1106 \begin{lstlisting}[language=Matlab]
1107 cd <rpp-simulink>/rpp/demos
1108 open cantransmit.slx
1109 \end{lstlisting}
1110
1111 The same procedure can be used to open any other models. To run the model on
1112 the target hardware see Section \ref{sec-running-model-on-hw}.
1113
1114 \subsection{Creating a new model}
1115 \label{sec-crating-new-model}
1116 \begin{enumerate}
1117         \item Create a model by clicking \textsc{New$\rightarrow$Simulink Model}.
1118         \item Open a configuration dialog by clicking \textsc{Simulation$\rightarrow$Model Configuration Parameters}.
1119         \item The new Simulink model needs to be configured in the following way:
1120         \begin{compactitem}
1121         \item Solver (Figure \ref{fig-solver}):
1122          \begin{compactitem}
1123          \item Options: \emph{Fixed-step, discrete}
1124          \item Tasking mode set to \textit{SingleTasking}.
1125            \begin{figure}
1126                  \centering
1127                  \includegraphics[width=400px]{images/simulink_solver.png}
1128                  \caption{Solver settings}
1129                  \label{fig-solver}
1130         \end{figure}
1131          \end{compactitem}
1132         \item Diagnostics $\rightarrow$ Sample Time (Figure~\ref{fig-sample-time-settings}):
1133          \begin{compactitem}
1134          \item Disable warning source block specifies -1 sampling time. It's ok for the
1135 source blocks to run once per tick.
1136            \begin{figure}
1137                  \centering
1138                  \includegraphics[width=400px]{images/simulink_diagnostics.png}
1139                  \caption{Sample Time settings}
1140                  \label{fig-sample-time-settings}
1141         \end{figure}
1142         \end{compactitem}
1143         \item Code generation (Figure~\ref{fig-code-gen-settings}):
1144          \begin{compactitem}
1145          \item Set to \textsc{rpp.tlc}.
1146            \begin{figure}
1147                  \centering
1148                  \includegraphics[width=400px]{images/simulink_code.png}
1149                  \caption{Code Generation settings}
1150                  \label{fig-code-gen-settings}
1151         \end{figure}
1152         \end{compactitem}
1153 \end{compactitem}
1154         \item From Matlab command window change the current directory to where
1155 you want your generated code to appear, e.g.:
1156 \begin{lstlisting}[language=Matlab]
1157 cd /tmp/my-code
1158 \end{lstlisting}
1159   The code will be generated in a subdirectory of that directory. The name of
1160 the subdirectory will be \textsc{<model>\_rpp}, where \textsc{model} is the name
1161 of the Simulink model.
1162         \item Generate the code by choosing \textsc{Code $\rightarrow$ C/C++
1163 Code  $\rightarrow$ Build Model}.
1164 \end{enumerate}
1165
1166 If you want to run the model on the RPP board, see Section
1167 \ref{sec-running-model-on-hw}.
1168
1169 \subsection{Running model on the RPP board}
1170 \label{sec-running-model-on-hw}
1171 To run the model on the target RPP hardware you have to enable the download
1172 feature and build the model by following this procedure: \begin{enumerate}
1173         \item Open the model you want to run (See Section
1174 \ref{sec-openning-demo-models}.)
1175         \item Click on \textsc{Simulation$\rightarrow$Model Configuration
1176 Parameters}.
1177         \item In the \textsc{Code Generation$\rightarrow$RPP Options} pane
1178 check \textsc{Download compiled binary to RPP} checkbox.
1179         \item Click on \textsc{OK} button, connect the target HW to the computer
1180 like in the Section \ref{sec-ccs-run-project} and build the model by \textsc{Code $\rightarrow$ C/C++
1181 Code  $\rightarrow$ Build Model}. If the build
1182 ends with a success, the download process will start and once the downloading is
1183 finished, the application will run immediatelly.
1184 \end{enumerate}
1185
1186 The code downloading is supported for Windows and Linux development systems. If
1187 you are using Linux, you may also try to use the OpenOCD by checking Use OpenOCD
1188 to download the compiled binary checkbox in addition. For more information about
1189 the OpenOCD configuration refer 
1190
1191 \begin{verbatim}
1192 http://rtime.felk.cvut.cz/hw/index.php/TMS570LS3137#OpenOCD_setup_and_Flashing
1193 \end{verbatim}
1194
1195 Note: You should end the Code Composer Studio debug session before
1196 downloading the generated code to the RPP board. Otherwise the
1197 download will fail.
1198  
1199 \section{Configuring serial interface}
1200 \label{sec-configuration-serial-interface}
1201 The main interface for communicating with the RPP board is the serial interface.
1202 The application may define its own interface settings, but the following
1203 settings is the default one:
1204
1205 \begin{itemize}
1206         \item Baudrate: 115200
1207         \item Parity: none
1208         \item Bits: 8
1209         \item Stopbits: 1
1210         \item Flow control: none
1211 \end{itemize}
1212
1213 Use GtkTerm in Linux or Bray Terminal for accessing the serial interface. See
1214 Section \ref{sec-hardware-description} for reference about the position of the
1215 serial interface connector on the RPP board.
1216
1217 \section{Bug reporting}
1218 \label{sec-bug-reporting}
1219
1220 Please report any problems at CTU's bug tracking system at
1221 \url{https://redmine.felk.cvut.cz/projects/eaton-rm48}. New users have
1222 to register in the system and notify Michal Sojka about their
1223 registration via $\langle{}sojkam1@fel.cvut.cz\rangle{}$ email
1224 address.
1225
1226 \chapter{C Support Library}
1227 \label{chap-c-support-library}
1228
1229 This chapter describes the implementation of the C support library
1230 (RPP Library), which is used both for Simulink code generation target
1231 and command line testing tool.
1232
1233 \section{Description}
1234 \label{sec-description}
1235 The RPP C Support Library (also called RPP library) defines the API for
1236 working with the board. It includes drivers and an operating system.
1237 The library is
1238 designed from the board user perspective and exposes a simplified high-level API
1239 to handle the board's peripheral modules in a safe manner. The library is
1240 compiled as a static library named \texttt{rpp-lib.lib} and can be found in
1241 \textsc{\repo/rpp/lib}.
1242
1243 The RPP library can be used in any project, where the RPP hardware support is
1244 required and it is also used in two applications -- the Command line testing
1245 tool, described in Chapter \ref{chap-rpp-test-software}, and Simulink Coder
1246 target, described in Chapter \ref{chap-simulink-coder-target}.
1247
1248 For details about the library architecture, refer Section \ref{sec-software-architecture}.
1249
1250 \section{API development guidelines}
1251 \label{sec-api-development-guidlines}
1252
1253 The following are the development guidelines used for developing the RPP API:
1254
1255 \begin{compactitem}
1256         \item User documentation should be placed in header files, not in source
1257 code, and should be Doxygen formatted using autobrief. Documentation for each
1258 function present is mandatory.
1259         \item Function declarations in the headers files is for public functions
1260 only. Do not declare local/static/private functions in the header.
1261         \item Documentation in source code files should be non-doxygen formatted
1262 and intended for developers, not users. Documentation here is optional and at
1263 the discretion of the developer.
1264         \item Always use standard data types for IO when possible. Use custom
1265 structs as very last resort.  \item Use prefix based functions names to avoid
1266 clash. The prefix is of the form \textsc{$\langle$layer$\rangle$\_$\langle$module$\rangle$\_}, for example
1267 \textsc{rpp\_din\_update()} for the update function of the DIN module in the RPP
1268 Layer.  
1269         \item Be very careful about symbol export. Because it is used as a
1270 static library the modules should not export any symbol that is not intended to
1271 be used (function) or \textsc{extern}'ed (variable) from application. As a rule
1272 of thumb declare all global variables as static. 
1273         \item Only the RPP Layer symbols are available to user applications. All
1274 information related to lower layers is hidden for the application. This is
1275 accomplished by the inclusion of the rpp.h or rpp\_\{mnemonic\}.h file on the
1276 implementations files only and never on the interface files. Never expose any
1277 other layer to the application or to the whole system below the RPP layer. In
1278 other words, never \textsc{\#include "foo/foo.h"} in any RPP Layer interface
1279 file. 
1280 \end{compactitem}
1281
1282 \section{Coding style}
1283 \label{sec-coding-style}
1284 In order to keep the code as clean as possible, a unified coding style
1285 should be followed by any contributor to the code. The used coding
1286 style is based on the default configuration of Code Composer Studio
1287 editor. Most notable rule is that the Tab character is 4 spaces.
1288
1289 The RPP library project is prepared for a usage of a program named
1290 Uncrustify. The Uncrustify program checks the code and fixes those
1291 lines that does not match the coding style. However, keep in mind that
1292 the program is not perfect and sometimes some lines can be modified
1293 even when the suggested coding style has been followed. This does not
1294 causes problems as long as the contributor follows the committing
1295 procedure described in next paragraph.
1296
1297 When contributing to the code, the contributor should learn the current coding
1298 style from the existing code. When a new feature is implemented, before
1299 committing to the repository, a command: 
1300
1301 \lstset{language=bash}
1302 \begin{lstlisting}
1303 make uncrustify
1304 \end{lstlisting}
1305 in a Linux terminal should be called. This command fixes any coding style
1306 errors. After that all changes can be committed.
1307
1308 \section{Subdirectory content description}
1309 \label{sec-rpp-lib-subdirectory-content-description}
1310 \begin{description}
1311 \item[librpp.a and rpp-lib.lib] static RPP libraries.
1312
1313 The first one is for POSIX simulation, the second one for Simulink models and
1314 other ARM/RM48 applications. This files are placed here by the Makefile, when
1315 the library is built.
1316
1317         \item[apps/] Demo applications related to the RPP library.
1318
1319 This include the CCS studio project for generating of the static library and
1320 a test suite. The test suit in this directory has nothing common with the test suite
1321 mentioned later in Chapter 5 and those two suits are going to be merged in the
1322 future. Also other Hello World applications are included as a reference about how
1323 to create a RM48 application.
1324         \item[os/] OS layers directory. See OS interchangeable layer in Section
1325 \ref{sec-software-architecture} for more information.  
1326 information.  
1327         \item[rpp/] Main directory for the RPP Library.
1328         \item[rpp/doc/] Documentation directory for the RPP Library API documentation.
1329         \item[rpp/TMS570LS3137.ccxml] Descriptor for code download.
1330
1331 This file is used by all the projects including the Simulink RPP Target for code
1332 download. It is configured to use the Texas Instruments XDS100v2 USB Emulator.
1333         \item[rpp/TMS570LS313xFlashLnk.cmd] CGT Linker command file.
1334
1335 This file is used by all applications linked for the RPP board, including the
1336 Simulink models, static library and test suite. It includes instructions for the
1337 CGT Linker on where to place sections and sizes of some sections.
1338         \item[rpp/include/\{layer\} and rpp/src/\{layer\}] Interface files and
1339 implementations files for given \textsc{\{layer\}}. See Section
1340 \ref{sec-software-architecture} in Chapter \ref{chap-introduction} for details
1341 on the RPP Layer.  
1342         \item[rpp/include/rpp/rpp.h] Main library header file.
1343
1344 To use this library with all its modules, just include this file and this file
1345 only. Also, before using any library function call the \textsc{rpp\_init()}
1346 function for hardware initialization.
1347         \item[rpp/include/rpp/rpp\_\{mnemonic\}.h] Header file for
1348 \textsc{\{mnemonic\}} module.
1349
1350 This files includes function definitions, pin definitions, etc, specific to
1351 \{mnemonic\} module. See Section \ref{sec-api-development-guidlines}.
1352
1353 You may include only selected \textsc{rpp\_\{mnemonic\}.h} header files and call the
1354 specific \textsc{rpp\_\{mnemonic\}\_init} functions, instead of the \textsc{rpp.h} and
1355 \textsc{rpp\_init} function, if you want to use only a subset of the library functions.
1356         \item[rpp/src/rpp/rpp\_\{mnemonic\}.c] Module implementation.
1357
1358 Implementation of \textsc{rpp\_\{mnemonic\}.h}'s functions on top of the DRV
1359 library. 
1360         \item[rpp/src/rpp/rpp.c] Implementation of library-wide functions.
1361 \end{description}
1362
1363 \section{Compilation}
1364 \label{sec-compilation}
1365
1366 The RPP Library can be compiled as a static library using a Code
1367 Composer Studio project. The compilation process will automatically
1368 update the generated binary static library file in the library root
1369 directory.
1370
1371 For the compilation of the library as a static library open the Code
1372 Composer studio project \textsc{rpp-lib} (see
1373 Section~\ref{sec-openning-of-existing-project}) and build the project.
1374 If the build process is successful, the \textsc{rpp-lib.lib} file will
1375 appear in the library root directory.
1376
1377 Because compilation of the libraries in Eclipse IDE can be error
1378 prone, there is a \textsc{Makefile} that allows to compile the
1379 libraries from the Linux or Windows command line:
1380
1381 \begin{lstlisting}[language=bash]
1382 cd <library-root>
1383 make
1384 \end{lstlisting}
1385
1386 On Windows use \texttt{gmake.exe} supplied with CCS instead of
1387 \texttt{make}. The rpp-lib CCS project is configured to invoke this
1388 build procedure from IDE rather than using a building compilation
1389 procedure. One of the results is that the compilation is much faster
1390 this way.
1391
1392 Note that this Makefile still requires the Code Composer Studio (ARM
1393 compiler) to be installed.
1394
1395 The relevant aspects for compiling and linking an application using the static
1396 libraries are: 
1397
1398 \begin{itemize}
1399         \item \textbf{ARM compilation using CCS for the RPP board:}
1400         \begin{compactitem}
1401                 \item Include headers files of the OS for which the library was
1402 compiled against. At the time of this writing the OS is FreeRTOS 7.0.2. See
1403 Section \ref{sec-software-architecture}
1404                 \item Include header files for the RPP library or for modules
1405 you want to use rpp\_can.h for CAN module for example.  
1406                 \item Add library \textsc{rpp-lib.lib} to the linker libraries.
1407 The RPP library \textbf{MUST} be looked for  before Texas Instruments support
1408 library \textsc{rtsv7R4\_T\_be\_v3D16\_eabi.lib}.
1409                 \item Configure linker to retain \textsc{.intvecs} section from
1410 RPP Library:\newline{}
1411 \textsc{--retain="rpp-lib.lib$\langle$sys\_intvecs.obj$\rangle$(.intvecs)"}
1412                 \item Use the provided linker command file
1413 \textsc{TMS570LS313xFlashLnk.cmd}.  
1414         \end{compactitem}
1415         \item \textbf{x86(\_64) compilation using GCC for Simulation:}
1416         \begin{compactitem}
1417                 \item Include headers files of the OS for Simulation. At the
1418 time of this writing the OS is POSIX FreeRTOS 6.0.4.  
1419                 \item Include header files for the RPP library or for modules
1420 you want to use (rpp\_can.h for CAN module for example).  
1421                 \item Add library \textsc{librpp.a} to the linker libraries.
1422                 \item Add \textsc{pthread} to the linker libraries.
1423         \end{compactitem}
1424 \end{itemize}
1425
1426 As an important note, all the models compiled using Simulink will link against
1427 \textsc{rpp-lib.lib}.  When compiling a Simulink model, neither Simulink nor the
1428 \textsc{make} invoked during the build process, will update the generated binary
1429 if the model hasn't changed, and then if the source code hasn't changed. Static
1430 libraries changes are not considered for re-compilation and re-linking. If
1431 library development is being done and static library is updated, in order for
1432 the Simulink model to generate a newly linked version of the binary the whole
1433 code generation folder needs to be deleted in order to force code generation,
1434 compilation and linking with the new static library.
1435
1436 \section{Compiling API documentation}
1437 \label{sec-compiling-api-documentation}
1438 The RPP Layer is formatted using Doxygen documentation generator. This allows to
1439 generate a high quality API reference. To generate the API reference run in a
1440 Linux terminal:
1441
1442 \lstset{language=bash}
1443 \begin{lstlisting}
1444 cd <repo>/rpp/doc/api
1445 make
1446 xdg-open html/index.html
1447 \end{lstlisting}
1448
1449 The files under \textsc{\repo/rpp/lib/rpp/doc/api/content} are used for the API
1450 reference generation are their name is self-explanatory:
1451
1452 \begin{verbatim}
1453 blocks_map.html
1454 blocks.png
1455 cvut.png
1456 footer.html
1457 main_page.dox
1458 \end{verbatim}
1459
1460 \chapter{Simulink Coder Target}
1461 \label{chap-simulink-coder-target}
1462
1463 The Simulink Coder Target allows to convert Simulink models to a C code,
1464 compile it and download to the board.
1465
1466 \section{Introduction}
1467 \label{sec-introduction}
1468
1469 The Simulink RPP Target provides support for C source code generation from Simulink models and
1470 compilation of that code on top of the RPP library and the FreeRTOS operating system. This target
1471 uses Texas Instruments ARM compiler (\textsc{armcl}) included in the Code Generation Tools distributed with
1472 Code Composer Studio, and thus it depends on it for proper functioning.
1473
1474 This target also provides support for automatic download of the compiled binary to the RPP
1475 board.
1476
1477 \begin{figure}[H]\begin{center}
1478 \noindent
1479 \includegraphics[width=300px]{images/tlc_process.png}
1480 \caption{TLC code generation process. \cite[p. 1-6]{targetlanguagecompiler2013}}
1481 \end{center}\end{figure}
1482
1483 \section{Features and limitations}
1484 \label{sec-features}
1485
1486 \begin{itemize}
1487 \item Sampling frequencies up to 1\,kHz.
1488 \item Supports only single-tasking and single-rate systems. Support
1489   for single-rate systems will be available in the final version.
1490   Support for multitasking system will require careful audit of the
1491   RPP library with respect to thread-safe code.
1492 \item No External mode support yet. We work on it.
1493 \item Custom compiler options, available via OPTS variable in
1494   \emph{Make command} at \emph{Code Generation} tab (see Figure
1495   \ref{fig-code-gen-settings}). For example \textsc{make\_rtw
1496     OPTS="-O0 -g"}.
1497 \end{itemize}
1498
1499 \section{RPP Options pane}
1500 \label{sec-rpp-target-options}
1501
1502 The RPP Target includes the following configuration options, all of them
1503 configurable per model under  \textsc{Code Generation} \noindent$\rightarrow$
1504 \textsc{RPP Options}:
1505
1506 \begin{itemize}
1507 \item \textbf{C system stack size}: this parameter is passed directly
1508   to the linker for the allocation of the stack. Note that this stack
1509   is used only for initializing the application and FreeRTOS. Once
1510   everything is initialized, another stack is used by the generated
1511   code. See below. Default value is 4096.
1512
1513 \item \textbf{C system heap size}:
1514   \label{sec-rpp-target-options-heap-size} this parameter is passed
1515   directly to the linker for the allocation of the heap. Currently,
1516   the heap is not used, but will be used by the external mode in the future.
1517 Note that FreeRTOS uses its own heap whose size is independent of this
1518 parameter. 
1519 \item \textbf{Model step task stack size}: this parameter will be
1520 passed to the \textsc{xTaskCreate()} that
1521   creates the task for the model to run. In a Simulink model there are always two tasks:
1522  \begin{itemize}
1523  \item The worker task. This task is the one that executes the model
1524    step. This task requires enough stack memory to execute the step.
1525    If your model does not run, it might be caused by too small stack.
1526    The memory needed for the stack depends on the size and structure
1527    of the model.
1528  \item The control task. This task controls when the worker task should execute and controls overruns.
1529
1530  \end{itemize}
1531 \item \textbf{Download compiled binary to RPP}: if set, this option will download the generated binary to
1532   the board after the model is successfully built. Note that this option is unaware of the option
1533   \textit{Generate code only} in the \textit{Code Generation} options panel, so it will try to download even if
1534   only source code has been generated, failing graciously or uploading an old binary laying around
1535   in the build directory. This option calls the \textsc{rpp\_download.m} script, which is in turn a
1536   wrapper on the \textsc{loadti.sh}, \textsc{loadti.bat} and \textsc{loadopenocd.sh} script. More information on the \textsc{loadti.sh}
1537   script can be found in:
1538 \begin{verbatim}
1539 <css>/ccs_base/scripting/examples/loadti/readme.txt
1540 http://processors.wiki.ti.com/index.php/Loadti
1541 \end{verbatim}
1542
1543   The \textsc{loadti.sh} and \textsc{loadti.bat} script will close after the
1544 download of the generated program, leaving the loaded program running.
1545
1546   The \textsc{loadopenocd.sh} script will close after the download of the
1547 generated program as well, but the program will be stopped.  In order to run
1548 the loaded program a manual reset of the board is required.
1549
1550 \item \textbf{Download compiled binary to SDRAM}: This feature is not yet
1551 implemented for the simulink target.
1552
1553 \item \textbf{Use OpenOCD to download the compiled binary}: This option switches
1554 from Ti loading script \textsc{loadti.sh} to OpenOCD script
1555 \textsc{loadopenocd.sh}. The benefit of using OpenOCD, besides that it is open
1556 source
1557   software, is much shorter loading time. More information about the right
1558 OpenOCD version and its installation can be found at:
1559 \begin{verbatim}
1560 http://rtime.felk.cvut.cz/hw/index.php/TMS570LS3137#OpenOCD_setup_and_Flashing
1561 \end{verbatim}
1562 This feature is available for Linux system only.
1563
1564 \item \textbf{Print model metadata to SCI at start}: if set this option will
1565 print a message to the Serial Communication Interface when the model start
1566 execution on the board. This is very helpful to identify the model running on
1567 the board. The message is in the form: 
1568
1569 \begin{verbatim}
1570 `model_name' - generated_date (TLC tlc_version)
1571 \end{verbatim}
1572
1573   For example:
1574 \begin{verbatim}
1575 `hbridge_analog_control' - Wed Jun 19 14:10:44 2013 (TLC 8.3 (Jul 20 2012))
1576 \end{verbatim}
1577 \end{itemize}
1578
1579 \section{Subdirectory  content description}
1580 \label{sec-simulink-subdirectory-content-description}
1581 This section describes the directories of the Simulink Coder. If you are
1582 interested in particular file, refer the description at the beginning of the
1583 file.
1584
1585 \begin{description}
1586         \item[doc/] Contains the sources of the documentation, you are now
1587 reading.  
1588         \item[refs/] Contains third party references, which license allows the
1589 distribution.
1590         \item[rpp/blocks] Contains the TLC files, which defines the blocks for
1591 the Matlab Simulink and \textsc{rpp\_lib.slx}, which is the Simulink RPP
1592 Library, containing all the Simulink blocks for RPP.
1593         \item[rpp/blocks/tlc\_c]Contains the templates for C code generation from the
1594 Matlab Simulink model.
1595         \item[rpp/demos] Contains demo models, which purpose is to serve as a
1596 reference for the usage and for testing.  
1597         \item[rpp/lib] Contains the C Support Library. See Chapter
1598 \ref{chap-c-support-library}.  \item[rpp/loadopenocd] Contains download scripts
1599 for Linux support of the OpenOCD, for code downloading to the target.
1600         \item[rpp/loadti] Contains download scripts for Linux and Windows
1601 support for code downloading to the target, using Texas Instruments CCS code
1602 downloader.  
1603         \item[rpp/rpp] Contains set of support script for the Code Generator.
1604 \end{description}
1605
1606 \section{Block Library Overview}
1607 \label{sec-block-library-overview}
1608 The Simulink Block Library is a set of blocks that allows Simulink models to use
1609 board IO and communication peripherals. The available blocks are summarized in
1610 Table~\ref{tab:block-lib-status} and more detailed description is
1611 given in Section~\ref{sec-blocks-description}.
1612
1613 \begin{table}
1614 \begin{center}\begin{tabular}{|lp{5cm}lll|}
1615 \hline
1616 \textbf{Category} & \textbf{Name} & \textbf{Status} & \textbf{Mnemonic} & \textbf{Header} \\
1617 \hline
1618 \input{block_table.tex}
1619 \hline
1620 \end{tabular}\end{center}
1621
1622   \caption{Block library overview}
1623   \label{tab:block-lib-status}
1624 \end{table}
1625
1626 \label{sec-blocks-implementation}
1627 All of the blocks are implemented as manually created C Mex S-Function . In this section the 
1628 approach taken is briefly explained.
1629
1630 \subsection{C MEX S-Functions}
1631 \label{sec-c-mex-functions}
1632  \begin{compactitem}
1633  \item C : Implemented in C language. Other options are Fortran and Matlab language itself.
1634  \item MEX: Matlab Executable. They are compiled by Matlab - C compiler wrapper called MEX.
1635  \item S-Function: System Function, as opposed to standard functions, or user functions.
1636  \end{compactitem}
1637
1638 A C-MEX S-Function is a structured C file that implements some mandatory and
1639 optional  callbacks for a specification of a number of inputs, outputs, data
1640 types, parameters, rate, validity checking, etc.  A complete list of callbacks
1641 can be found in:
1642         \begin{quotation}
1643 \htmladdnormallink{http://www.mathworks.com/help/simulink/create-cc-s-functions.html}{http://www.mathworks.com/help/simulink/create-cc-s-functions.html}
1644 \end{quotation}
1645
1646 The way a C-MEX S-Function participates in a Simulink simulation is shown on the
1647 diagram \ref{fig-sfunctions-process}:
1648
1649 \begin{figure}[H]\begin{center}
1650 \noindent
1651 \includegraphics[width=250px]{images/sfunctions_process.png}
1652 \caption{Simulation cycle of a S-Function. \cite[p. 57]{simulinkdevelopingsfunctions2013}}
1653 \label{fig-sfunctions-process}
1654 \end{center}\end{figure}
1655
1656 In general, the S-Function can perform calculations, inputs and outputs for simulation. Because 
1657 the RPP blocks are for hardware peripherals control and IO the blocks are 
1658 implemented as pure sink or pure source, the S-Function is just a descriptor of
1659 the block and does not perform any calculation and does not provide any input or
1660 output for simulations. 
1661
1662 The implementation of the S-Functions in the RPP project has following layout:
1663
1664 \begin{itemize}
1665   \item Define S-Function name \textsc{S\_FUNCTION\_NAME}.
1666   \item Include header file \textsc{header.c}, which in connection with
1667 \textsc{trailer.c} creates a miniframework for writing S-Functions.  
1668   \item In \textsc{mdlInitializeSizes} define:
1669   \begin{itemize}
1670         \item Number of \textit{dialog} parameter.
1671         \item Number of input ports.
1672         \begin{compactitem}
1673                 \item Data type of each input port.
1674         \end{compactitem}
1675         \item Number of output ports.
1676         \begin{compactitem}
1677                 \item Data type of each output port.
1678         \end{compactitem}
1679         \item Standard options for driver blocks.
1680   \end{itemize}
1681   \item In \textsc{mdlCheckParameters}:
1682   \begin{itemize}
1683         \item Check data type of each parameter.
1684         \item Check range, if applicable, of each parameter.
1685   \end{itemize}
1686   \item In \textsc{mdlSetWorkWidths}:
1687   \begin{compactitem}
1688         \item Map \textit{dialog} parameter to \textit{runtime} parameters.
1689         \begin{itemize}
1690                 \item Data type of each \textit{runtime} parameter.
1691         \end{itemize}
1692   \end{compactitem}
1693   \item Define symbols for unused functions.
1694   \item Include trailer file \textsc{trailer.c}.
1695 \end{itemize}
1696
1697 The C-MEX S-Function implemented can be compiled with the following command:
1698
1699 \lstset{language=bash}
1700 \begin{lstlisting}
1701 <matlabroot>/bin/mex sfunction_{mnemonic}.c
1702 \end{lstlisting}
1703
1704 As noted the standard is to always prefix S-Function with \textsc{sfunction\_}
1705 and use lower case mnemonic of the block.
1706
1707 Also a script called \textsc{compile\_blocks.m} is included. The script that
1708 allows all \textsc{sfunctions\_*.c} to be fed to the \textsc{mex} compiler so
1709 all S-Functions are compiled at once. To use this script, in Matlab do:
1710
1711 \lstset{language=Matlab}
1712 \begin{lstlisting}
1713 cd <repo>/rpp/blocks/
1714 compile_blocks()
1715 \end{lstlisting}
1716
1717 \subsection{Target Language Compiler files}
1718 \label{sec-target-language-compiler-files}
1719
1720 In order to generate code for each one of the S-Functions, every S-Function implements a TLC file
1721 for \textit{inlining} the S-Function on the generated code. The TLC files describe how to 
1722 generate code for a specific C-MEX S-Function block. They are programmed using TLC own language and 
1723 include C code within TLC instructions, just like LaTeX files include normal text in between LaTeX 
1724 macros.
1725
1726 The standard for a TLC file is to be located under the \textsc{tlc\_c} subfolder from where the 
1727 S-Function is located and to use the very exact file name as the S-Function but with the \textsc{.tlc}
1728 extension: \textsc{sfunction\_foo.c} \noindent$\rightarrow$ \textsc{tlc\_c/sfunction\_foo.tlc}
1729
1730 The TLC files implemented for this project use 3 hook functions in particular (other are available, 
1731 see TLC reference documentation):
1732 \begin{itemize}
1733 \item \textsc{BlockTypeSetup}: \newline{}
1734   BlockTypeSetup executes once per block type before code generation begins.
1735   This function can be used to include elements required by this block type, like includes or
1736   definitions.
1737 \item \textsc{Start}: \newline{}
1738   Code here will be placed in the \textsc{void
1739 $\langle$modelname$\rangle$\_initialize(void)}. Code placed here will execute
1740 only once.
1741 \item \textsc{Outputs}: \newline{}
1742   Code here will be placed in the \textsc{void
1743 $\langle$modelname$\rangle$\_step(void)} function. Should be used to get the
1744 inputs o a block and/or to set the outputs of that block.
1745 \end{itemize}
1746
1747 The general layout of the TLC files implemented for this project are:
1748 \begin{itemize}
1749 \item In \textsc{BlockTypeSetup}: \newline{}
1750   Call common function \textsc{\%$<$RppCommonBlockTypeSetup(block, system)$>$} that will include the 
1751   \textsc{rpp/rpp\i\_mnemonic.h} header file (can be called multiple times but header is included only once).
1752 \item \textsc{Start}: \newline{}
1753   Call setup routines from RPP Layer for the specific block type, like HBR enable, DIN pin setup, 
1754   DAC value initialization, SCI baud rate setup, among others.
1755 \item \textsc{Outputs}: \newline{}
1756   Call common IO routines from RPP Layer, like DIN read, DAC set, etc. Success of this functions
1757   is checked and in case of failure error is reported to the block using ErrFlag.
1758 \end{itemize}
1759
1760 C code generated from a Simulink model is placed on a file called
1761 \textsc{$\langle$modelname$\rangle$.c} along with other support files in a
1762 folder called \textsc{$\langle$modelname$\rangle$\_$\langle$target$\rangle$/}.
1763 For example, the source code generated for model \textsc{foobar} will be placed
1764 in current Matlab directory \textsc{foobar\_rpp/foobar.c}.
1765
1766 The file \textsc{$\langle$modelname$\rangle$.c} has 3 main functions:
1767 \begin{compactitem}
1768 \item \textsc{void $\langle$modelname$\rangle$\_step(void)}: \newline{}
1769   This function recalculates all the outputs of the blocks and should be called once per step. This
1770   is the main working function.
1771 \item \textsc{void $\langle$modelname$\rangle$\_initialize(void)}: \newline{}
1772   This function is called only once before the first step is issued. Default values for blocks IOs
1773   should be placed here.
1774 \item \textsc{void $\langle$modelname$\rangle$\_terminate(void)}: \newline{}
1775   This function is called when terminating the model. This should be used to free memory of revert 
1776   other operations made on the initialization function. With current implementation this function
1777   should never be called unless an error is detected and in most models it is empty.
1778 \end{compactitem}
1779
1780 \section{Block reference}
1781 \label{sec-blocks-description}
1782
1783 This section describes each one of the Simulink blocks present in the Simulink
1784 RPP block library, shown in Figure \ref{fig-block-library}.
1785
1786 \begin{figure}[h]
1787   \begin{center}
1788     \includegraphics[width=\textwidth]{images/block_library.png}
1789   \end{center}
1790 \caption{Simulink RPP Block Library.}
1791 \label{fig-block-library}
1792 \end{figure}
1793 \clearpage
1794 \input{block_desc.tex}
1795
1796 \section{Demos}
1797 The Simulink RPP Demo Library is a set of Simulink models that use blocks from
1798 the Simulink RPP Block Library and generates code using the Simulink RPP Target.
1799
1800 This demos library is used as a test suite for the Simulink RPP Block Library
1801 but they are also intended to show basic programs built using it. Because of
1802 this, the demos try to use more than one
1803 type of block and more than one block per block type.
1804
1805 In the reference below you can find a complete description for each of the demos.
1806
1807 \subsection{ADC demo}
1808 \begin{figure}[H]\begin{center}
1809 \noindent
1810 \includegraphics[width=450px]{images/demo_adc.png}
1811 \caption{Example of the usage of the Analog Input blocks for RPP.}
1812 \end{center}\end{figure}
1813
1814 \textbf{Description:}
1815
1816 Demostrates how to use Analog Input blocks in order to measure voltage. This demo
1817 measures voltage on every available Analog Input and prints the values on the
1818 Serial Interface.
1819
1820 \subsection{Simple CAN demo}
1821 \begin{figure}[H]\begin{center}
1822 \noindent
1823 \includegraphics[width=450px]{images/demo_simple_can.png}
1824 \caption{The simplest CAN demonstration.}
1825 \end{center}\end{figure}
1826
1827 \textbf{Description:}
1828
1829 The simplest possible usage of the CAN bus. This demo is above all designed for
1830 testing the CAN configuration and transmission.
1831
1832 \subsection{CAN transmit}
1833 \begin{figure}[H]\begin{center}
1834 \noindent
1835 \includegraphics[width=450px]{images/demo_cantransmit.png}
1836 \caption{Example of the usage of the CAN blocks for RPP.}
1837 \end{center}\end{figure}
1838
1839 \textbf{Description:}
1840
1841 Demostrates how to use CAN Transmit blocks in order to:
1842
1843 \begin{compactenum}
1844 \item Send unpacked data with data type uint8, uint16 and uint32.
1845 \item Send single and multiple signals packed into CAN\_MESSAGE by CAN Pack block.
1846 \item Send a message as extended frame type to be received by CAN Receive
1847 configured to receive both, standard and extended frame types.
1848 \end{compactenum}
1849
1850 Demostrates how to use CAN Receive blocks in order to:
1851
1852 \begin{compactenum}
1853 \item Receive unpacked data of data types uint8, uint16 and uint32.
1854 \item Receive and unpack received CAN\_MESSAGE by CAN Unpack block.
1855 \item Configure CAN Receive block to receive Standard, Extended and both frame types.
1856 \item Use function-call mechanism to process received messages
1857 \end{compactenum}
1858
1859 \subsection{Simulink Demo model}
1860 \begin{figure}[H]\begin{center}
1861 \noindent
1862 \includegraphics[width=450px]{images/demo_board.png}
1863 \caption{Model of the complex demonstration of the boards peripherals.}
1864 \end{center}\end{figure}
1865
1866 \textbf{Description:}
1867
1868 This model demonstrates the usage of RPP Simulink blocks in a complex and interactive
1869 application. The Ti HDK kit has eight LEDs placed around the MCU. The application
1870 rotates the light around the MCU in one direction. Every time the user presses the button
1871 on the HDK, the direction is switched.
1872
1873 The state of the LEDs is sent on the CAN bus as a message with ID 0x1. The button can
1874 be emulated by CAN messages with ID 0x0. The message 0x00000000 simulates button release
1875 and the message 0xFFFFFFFF simulates the button press.
1876
1877 Information about the state of the application are printed on the Serial Interface. 
1878
1879 \subsection{Echo char}
1880 \begin{figure}[H]\begin{center}
1881 \noindent
1882 \includegraphics[width=450px]{images/demo_echo_char.png}
1883 \caption{Echo Character Simulink demo for RPP.}
1884 \end{center}\end{figure}
1885
1886 \textbf{Description:}
1887
1888 This demo will echo (print back) any character received through the Serial Communication
1889 Interface (115200-8-N-1).
1890
1891 Note that the send subsystem is implemented a as \textit{triggered} subsystem and will execute only
1892 if data is received, that is, Serial Receive output is non-negative. Negative values are errors.
1893
1894 \subsection{GIO demo}
1895 \begin{figure}[H]\begin{center}
1896 \noindent
1897 \includegraphics[width=450px]{images/demo_gio.png}
1898 \caption{Demonstration of DIN and DOUT blocks}
1899 \end{center}\end{figure}
1900
1901 \textbf{Description:}
1902
1903 The model demonstrates how to use the DIN blocks and DOUT blocks, configured in every mode. The DOUTs
1904 are pusched high and low with period 1 second. The DINs are reading inputs and printing the values
1905 on the Serial Interface with the same period.
1906
1907 \subsection{Hello world}
1908 \begin{figure}[H]\begin{center}
1909 \noindent
1910 \includegraphics[width=450px]{images/demo_hello_world.png}
1911 \caption{Hello World Simulink demo for RPP.}
1912 \end{center}\end{figure}
1913
1914 \textbf{Description:}
1915
1916 This demo will print \textsc{"Hello Simulink"} to the Serial Communication Interface (115200-8-N-1) one
1917 character per second. The output speed is driven by the Simulink model step which is set to one
1918 second.
1919
1920 \chapter{Command line testing tool}
1921 \label{chap-rpp-test-software}
1922 The \textsc{rpp-test-suite} is a RPP application developed testing and direct
1923 control of the RPP hardware. The test suite implements a command processor,
1924 which is listening for a commands and prints some output related to the commands
1925 on the serial interface. The command processor is modular and each peripheral
1926 has its commands in a separated module.
1927
1928 The command processor is implemented in \textsc{$\langle$rpp-test-sw$\rangle$/cmdproc} and commands
1929 modules are implemented in \textsc{$\langle$rpp-test-sw$\rangle$/commands} directory.
1930
1931 The application enables a command processor using the SCI at
1932 \textbf{115200-8-N-1}. When the software starts, the received welcome message
1933 and prompt should look like:
1934
1935 \begin{verbatim}
1936 TODO: FILL
1937 \end{verbatim}
1938
1939 Type in command help for a complete list of available command, or help command
1940 for a description of concrete command.
1941
1942 \section{Command description}
1943
1944 This section contains the description of the available commands. The
1945 same description is also available in the program itself via the
1946 \texttt{help} command.
1947
1948 \input{rpp-test-sw-cmds.tex}
1949
1950 \chapter{Glossary}
1951
1952 \begin{description}
1953 \item[ADC]
1954   \textit{Analog to Digital Converter.} \newline{}
1955   Hardware circuitry that converts a continuous physical quantity (usually voltage) to a
1956   digital number that represents the quantity's amplitude.
1957
1958 \item[AIN]
1959   \textit{Analog Input.} \newline{}
1960   Mnemonic to refer to or something related to the analog input (ADC) hardware module.
1961
1962 \item[AOUT]
1963   \textit{Analog Output.} \newline{}
1964   Mnemonic to refer to or something related to the analog output (DAC) hardware module.
1965
1966 \item[CAN]
1967   \textit{Controller Area Network.} \newline{}
1968   The CAN Bus is a vehicle bus standard designed to allow microcontrollers and devices to
1969   communicate with each other within a vehicle without a host computer.
1970   In this project it is also used as mnemonic to refer to or something related to the CAN
1971   hardware module.
1972
1973 \item[CGT]
1974   \textit{Code Generation Tools.} \newline{}
1975   Name given to the tool set produced by Texas Instruments used to compile, link, optimize,
1976   assemble, archive, among others. In this project is normally used as synonym for
1977   ``Texas Instruments ARM compiler and linker."
1978
1979 \item[DAC]
1980   \textit{Digital to Analog Converter.} \newline{}
1981   Hardware circuitry that converts a digital (usually binary) code to an analog signal
1982   (current, voltage, or electric charge).
1983
1984 \item[DIN]
1985   \textit{Digital Input.} \newline{}
1986   Mnemonic to refer to or something related to the digital input hardware module.
1987
1988 \item[ECU]
1989   \textit{Engine Control Unit.} \newline{}
1990   A type of electronic control unit that controls a series of actuators on an internal combustion
1991   engine to ensure the optimum running.
1992
1993 \item[ETH]
1994   \textit{Ethernet.} \newline{}
1995   Mnemonic to refer to or something related to the Ethernet hardware module.
1996
1997 \item[FR]
1998   \textit{FlexRay.} \newline{}
1999   FlexRay is an automotive network communications protocol developed to govern on-board automotive
2000   computing.
2001   In this project it is also used as mnemonic to refer to or something related to the FlexRay
2002   hardware module.
2003
2004 \item[GPIO]
2005   \textit{General Purpose Input/Output.} \newline{}
2006   Generic pin on a chip whose behavior (including whether it is an input or output pin) can be
2007   controlled (programmed) by the user at run time.
2008
2009 \item[HBR]
2010   \textit{H-Bridge.} \newline{}
2011   Mnemonic to refer to or something related to the H-Bridge hardware module. A H-Bridge is
2012   an electronic circuit that enables a voltage to be applied across a load in either direction.
2013
2014 \item[HOUT]
2015   \textit{High-Power Output.} \newline{}
2016   Mnemonic to refer to or something related to the 10A, PWM, with current sensing, high-power
2017   output hardware module.
2018
2019 \item[IDE]
2020   \textit{Integrated Development Environment.} \newline{}
2021   An IDE is a Software application that provides comprehensive facilities to computer programmers
2022   for software development.
2023
2024 \item[LCT]
2025   \textit{Legacy Code Tool.} \newline{}
2026   Matlab tool that allows to generate source code for S-Functions given the descriptor of a C 
2027   function call.
2028
2029 \item[LIN]
2030   \textit{Local Interconnect Network.} \newline{}
2031   The LIN is a serial network protocol used for communication between components in vehicles.
2032   In this project it is also used as mnemonic to refer to or something related to the LIN
2033   hardware module.
2034
2035 \item[LOUT]
2036   \textit{Logic Output.} \newline{}
2037   Mnemonic to refer to or something related to the digital output hardware module.
2038   It is logic output (100mA), as opposed to power outputs (2A, 10A).
2039
2040 \item[MBD]
2041   \textit{Model-Based Design.} \newline{}
2042   Model-Based Design (MBD) is a mathematical and visual method of addressing problems associated
2043   with designing complex control, signal processing and communication systems. \cite{modelbasedwiki2013}
2044
2045 \item[MEX]
2046   \textit{Matlab Executable.} \newline{}
2047   Type of binary executable that can be called within Matlab. In this document the common term
2048   used is `C MEX S-Function", which means Matlab executable written in C that implements a system
2049   function.
2050
2051 \item[MOUT]
2052   \textit{(Motor) Power Output.} \newline{}
2053   Mnemonic to refer to or something related to the 2A push/pull power output hardware module.
2054
2055 \item[PWM]
2056   \textit{Pulse-width modulation.} \newline{}
2057   Technique for getting analog results with digital means. Digital control is used to create a
2058   square wave, a signal switched between on and off. This on-off pattern can simulate voltages
2059   in between full on and off by changing the portion of the time the signal spends on versus
2060   the time that the signal spends off. The duration of ``on time" is called the pulse width or
2061   \textit{duty cycle}.
2062
2063 \item[RPP]
2064   \textit{Rapid Prototyping Platform.} \newline{}
2065   Name of the automotive hardware board. Also generic term to define something related
2066   to the board, like the RPP Library, RPP Layer, RPP API, etc.
2067
2068 \item[SCI]
2069   \textit{Serial Communication Interface.} \newline{}
2070   Serial Interface for communication through hardware's UART using communication standard RS-232.
2071   In this project it is also used as mnemonic to refer to or something related to the Serial
2072   Communication Interface hardware module.
2073
2074 \item[SDC]
2075   \textit{SD-Card.} \newline{}
2076   Mnemonic to refer to or something related to the SD-Card hardware module.
2077
2078 \item[SDR]
2079   \textit{SD-RAM.} \newline{}
2080   Mnemonic to refer to or something related to the SD-RAM hardware module for logging.
2081
2082 \item[TLC]
2083   \textit{Target Language Compiler.} \newline{}
2084   Technology and language used to generate code in Matlab/Simulink.
2085
2086 \item[UART]
2087   \textit{Universal Asynchronous Receiver/Transmitter.} \newline{}
2088   Hardware circuitry that translates data between parallel and serial forms.
2089 \end{description}
2090
2091 \bibliography{rpp_simulink}
2092 \bibliographystyle{plain}
2093
2094 \end{document}
2095
2096 %  LocalWords:  FreeRTOS RPP POSIX