]> rtime.felk.cvut.cz Git - pes-rpp/rpp-simulink.git/blob - doc/rpp_simulink.tex
doc: Update the date of revision 0.7
[pes-rpp/rpp-simulink.git] / doc / rpp_simulink.tex
1 \documentclass{scrreprt}
2
3 \usepackage{graphicx} % images and graphics
4 \usepackage{paralist} % needed for compact lists
5 \usepackage[normalem]{ulem} % needed by strike
6 \usepackage{listings} % required for code blocks
7 \usepackage[urlcolor=blue,colorlinks=true,hyperfootnotes=false]{hyperref} % links
8 \usepackage[utf8]{inputenc}  % char encoding
9 \usepackage[bottom]{footmisc} % footnotes
10 \usepackage{todonotes}
11 \usepackage[backend=biber,style=alphabetic,sortcites=true]{biblatex}
12 \usepackage{tabularx}
13 \usepackage{textcomp}
14 \addbibresource{rpp_simulink.bib}
15
16 % header
17 \usepackage[top=2.5cm, bottom=2.5cm, left=2.5cm, right=2.5cm]{geometry}
18 \usepackage{float} % To fix images position
19
20 % Prettify code documentation
21 \usepackage{color}
22 \usepackage{colortbl}
23 % \usepackage[table]{xcolor}
24
25 \definecolor{gray97}{gray}{.97}
26 \definecolor{gray75}{gray}{.75}
27 \definecolor{gray45}{gray}{.45}
28 \lstset{ frame=Ltb,
29      framerule=0pt,
30      aboveskip=0.5cm,
31      framextopmargin=3pt,
32      framexbottommargin=3pt,
33      framexleftmargin=0.4cm,
34      framesep=0pt,
35      rulesep=.4pt,
36      backgroundcolor=\color{gray97},
37      rulesepcolor=\color{black},
38      %
39      stringstyle=\ttfamily,
40      showstringspaces = false,
41      basicstyle=\small\ttfamily,
42      commentstyle=\color{gray45},
43      keywordstyle=\bfseries,
44      %
45      numbers=left,
46      numbersep=15pt,
47      numberstyle=\tiny,
48      numberfirstline = false,
49      breaklines=true,
50      xleftmargin=20px,
51    }
52
53 \usepackage{lastpage}
54 \usepackage{fancyhdr}
55
56 % Spacing
57 \linespread{1.15} % Lines spacing
58 \setlength{\plitemsep}{0.5\baselineskip} % List items spacing
59 \definecolor{deepblue}{RGB}{0,0,61}
60 \definecolor{deepgreen}{RGB}{0,80,0}
61 \hypersetup{linkcolor=deepblue,citecolor=deepgreen,}
62
63 % Table of content depth
64 \setcounter{tocdepth}{2}
65
66 % Landscape pages
67 \usepackage{lscape}
68 \usepackage{pdflscape}
69
70 % Change page
71 \usepackage{changepage}
72
73 % Font options
74 % Sans-serif
75 % \renewcommand{\familydefault}{\sfdefault}
76 % Better PDF font
77 \usepackage{lmodern}
78
79 % Multiple columns
80 \usepackage{multicol}
81 \usepackage{caption}
82
83 \newcommand{\repo}{$\langle$repo$\rangle$}
84 \newcommand{\superscript}[1]{\ensuremath{^{\textrm{\small#1}}}}
85 \newcommand{\subscript}[1]{\ensuremath{_{\textrm{\small#1}}}}
86
87 % Supported targets - to be used with \ifx\tgtId\tgtIdXXX
88 \def\tgtIdTMSHDK{tms570\_hdk}
89 \def\tgtIdRMHDK{rm48\_hdk}
90 \def\tgtIdTMSRPP{tms570\_rpp}
91 \def\tgtIdHydCtr{tms570\_hydctr}
92
93 % Include target specific macros etc.
94 \input{target_def}
95
96 \begin{document}
97
98 % Title
99 \newcommand{\HRule}{\rule{\linewidth}{0.5mm}}
100
101 \begin{titlepage}
102 \begin{center}
103
104 % Upper part of the page
105 \vspace{3cm}
106
107 \includegraphics[width=0.35\textwidth]{images/cvut.pdf}\\[1cm]
108 \textsc{\LARGE Czech Technical University in Prague}\\[1.5cm]
109
110
111 % Document title
112 \HRule
113 \vspace{0.4cm}
114 {\huge \bfseries Simulink code generation target for Texas~Instruments
115   \tgname{} platform\par}
116 \vspace{0.8cm}
117 {\Large Version for \tgtBoardName{} board\par}
118 \vspace{0.4cm}
119 \HRule \\[1.5cm]
120
121
122 % Author
123 \emph{Authors:}\\
124 Carlos \textsc{Jenkins}\\
125 Michal \textsc{Horn}\\
126 Michal \textsc{Sojka}\\[\baselineskip]
127
128 \vfill
129 \emph{Version:}
130 \input{version.tex}
131
132 % Bottom of the page
133 {\large \today}
134
135 \end{center}
136 \end{titlepage}
137 % Title end
138
139 \section*{Revision history}
140
141 \noindent\begin{tabularx}{\linewidth}{|l|l|l|X|}
142   \rowcolor[gray]{0.9}\hline
143   Revision     & Date      & Author(s) & Comments \\ \hline
144
145   0.1 beta & 2014-12-04 & Sojka, Horn & Initial version \\ \hline
146
147   0.2 & 2015-02-16 & Sojka, Horn & Improvements, clarifications,
148   cleanup \\ \hline
149
150   0.3 & 2015-03-31 & Sojka, Horn & Added sections
151                                    \ref{sec-changing-os}, \ref{sec:adding-new-funct} and
152                                    \ref{sec:mult-single-thre}. Minor
153                                    updates. \\ \hline
154
155            0.4 & 2015-04-30 & Sojka, Horn & Added support for TMS570 HDK
156                                             platform. All RPP software
157                                             supports multiple
158                                             platforms by
159                                             recompilation. \\ \hline
160
161            0.5 beta & 2015-07-03 & Sojka & Updated section \ref{sec:adding-new-funct}.
162                                            Added support for Eaton Hydraulics
163                                            Controller board (TMS570LS1227).
164            \\\hline
165
166            0.5.5 & 2015-08-27 & Sojka, Horn & rpp-lib: HAL merged into DRV
167                                               layer, FreeRTOS upgraded to version 8.2.2.
168            \\\hline
169
170            0.6 & 2015-09-03 & Sojka & Multi-rate models can be
171                                       compiled in multi-tasking mode
172                                       (see
173                                       sec.~\ref{sec-singlet-multit-modes}
174                                       and \ref{sec:mult-multi-thre}).
175                                       Added board init block (sec.
176                                       \ref{sec:block:sfunction_hydctr_init.c}).
177                                       Documented halcogen directory in
178                                       sec.~\ref{sec-rpp-lib-subdirectory-content-description}.
179            \\\hline
180
181            0.6a & 2015-09-11 & Sojka & Removed reference of
182                                        Simulink blocks that are not
183                                        part of Eaton distribution.
184            \\\hline
185
186            0.7 & 2015-10-05 & Sojka & Simulink GIO blocks
187                                       (sec.
188                                       \ref{sec:block:sfunction_gio_in.c},
189                                       \ref{sec:block:sfunction_gio_out.c})
190                                       have different parameters and
191                                       support certain SPI5 pins on the
192                                       tms570\_hydctr board. Parameters
193                                       of old GIO blocks are
194                                       automatically transformed to the
195                                       new ones.
196
197                                       Added section \ref{sec:board-init-hydctr}: ``Hydraulics controller
198                                       initialization demo''.
199            \\\hline
200 \end{tabularx}
201
202 \tableofcontents
203
204 \newpage
205
206 \listoffigures
207
208 \newpage
209
210 \fancypagestyle{plain}{%
211 \fancyhf{} % clear all header and footer fields
212 \renewcommand{\footrulewidth}{0.4pt} 
213 \renewcommand{\headrulewidth}{0pt}
214         \fancyfoot[L]{Version \input{version.tex}}
215         \fancyfoot[C]{}
216         \fancyfoot[R]{Page {\thepage} of \pageref{LastPage}}
217 }
218 \renewcommand{\headrulewidth}{0.4pt} 
219 \renewcommand{\footrulewidth}{0.4pt} 
220 \pagestyle{fancy} {
221         \fancyhead[R]{\includegraphics[width=1cm]{images/cvut.pdf}}
222         \fancyhead[C]{}
223         \fancyhead[L]{\nouppercase \leftmark}
224         \fancyfoot[L]{Version \input{version.tex}}
225         \fancyfoot[C]{}
226         \fancyfoot[R]{Page {\thepage} of \pageref{LastPage}}
227 }
228 \headheight=26pt
229 %\addtolength{\parskip}{\baselineskip} % Paragraph spacing
230
231 \chapter{Introduction}
232 \label{chap-introduction}
233
234 This text documents software part of Rapid Prototyping Platform (RPP)
235 project for Texas Instruments \tgname{} safety microcontroller
236 developed by Czech Technical University in Prague (CTU). The software
237 consists of code generation target for Simulink Embedded Coder, a
238 low-level run-time C library and a tool for interactive testing of
239 hardware and software functionality.
240
241 Originally, the RPP project was created for a custom TMS570-based board
242 and the port to other platforms such as RM48 HDK and TMS570 HDK
243 development kits. Porting to other platforms was done under a contract
244 from Eaton Corporation.
245
246 The document contains step-by-step instructions for installation of
247 development tools, information about Simulink Coder configuration,
248 describes how to create new models as well as how to download the
249 resulting firmware to the hardware. It can also be used as a reference
250 for the testing tool, Matlab Simulink blocks and RPP Matlab Simulink
251 Code generator. Additionally, an overall description of the used
252 hardware platform and the architecture of included software is
253 provided.
254
255 \section{Background}
256 \label{sec-background}
257
258 In this document, the term \emph{Rapid Prototyping Platform} denotes a
259 hardware board and accompanying software. The hardware board is
260 \tgtBoardName{} based on ARM Cortex R4 safety microcontroller
261 \mcuname{}. This MCU contains several protective mechanisms (two cores
262 in lockstep, error correction mechanisms for SRAM and Flash memory,
263 voltage monitoring, etc.) to fulfill the requirements for safety
264 critical applications. See~\cite{\tgrefman} for details.
265
266 In order to develop non-trivial applications for the RPP, an operating
267 system is necessary. The RPP is based on FreeRTOS -- a simple
268 opensource real-time operating system kernel. The FreeRTOS provides an
269 API for creating and managing and scheduling multiple tasks, memory
270 manager, semaphores, queues, mutexes, timers and a few of other
271 features which can be used in the applications.
272 See~\cite{usingthefreertos2009} for more details.
273
274 Even with the operating system it is quite hard and non-intuitive to
275 manipulate the hardware directly. That is the point when abstraction
276 comes into the play. The RPP software is made of several layers
277 implementing, from the bottom to the top, low-level device drivers,
278 hardware abstraction for common functionality on different hardware
279 and an API which is easy to use in applications. The operating system
280 and the basic software layers, can be compiled as a library and easily
281 used in any project. More details about the library can be found in
282 Chapter~\ref{chap-c-support-library} and in~\cite{michalhorn2013}.
283
284 Because human beings make mistakes and in safety critical applications
285 any mistake can cause damage, loos of money or in the worst case even
286 death of other people, the area for making mistakes has to be as small
287 as possible. An approach called Model-based development
288 \cite{modelbasedwiki2013} has been introduced to reduce the
289 probability of making mistakes. In model-based development, the
290 applications are designed at higher level from models and the
291 functionality of the models can be simulated in a computer before the
292 final application/hardware is finished. This allows to discover
293 potential errors earlier in the development process.
294
295 One commonly used tool-chain for model-based development is
296 Matlab/Simulink. In Simulink the application is developed as a model
297 made of interconnected blocks. Every block implements some
298 functionality. For example one block reads a value from an
299 analog-to-digital converter and provides the value as an input to
300 another block. This block can implement some clever algorithm and its
301 output is passed to another block, which sends the computed value as a
302 message over CAN bus to some other MCU. Such a model can be simulated
303 and tested even before the real hardware is available by replacing the
304 input and output blocks with simulated ones. Once the hardware is
305 ready, C code is automatically generated from the model by a Simulink
306 Coder. The code is then compiled by the MCU compatible compiler and
307 downloaded to the MCU Flash memory on the device. Because every block
308 and code generated from the block has to pass a series of tests during
309 their development, the area for making mistakes during the application
310 development has been significantly reduced and developers can focus on
311 the application instead of the hardware and control software
312 implementation. More information about code generation can be found in
313 Chapter \ref{chap-simulink-coder-target}. For information about Matlab
314 Simulink, Embedded Coder and Simulink Coder, refer to
315 \cite{embeddedcoderreference2013, ebmeddedcoderusersguide2013,
316   simulinkcoderreference2013, targetlanguagecompiler2013,
317   simulinkcoderusersguide2013, simulinkdevelopingsfunctions2013}.
318
319 \section{Hardware description}
320 \label{sec-hardware-description}
321
322 \input{hwdesc}
323
324 \section{Software architecture}
325 \label{sec-software-architecture}
326
327 The core of the RPP software is the so called RPP Library. This
328 library is conceptualy structured into 5 layers, depicted in
329 Figure~\ref{fig-layers}. The architecture design was driven by the
330 following guidelines:
331
332 \begin{compactitem}
333         \item Top-down dependency only. No lower layer depends on anything from
334 upper layers.
335 %       \item 1-1 layer dependency only. The top layer depends
336 % exclusively on the bottom layer, not on any lower level layer (except for a
337 % couple of exceptions).
338 \item Each layer should provide a unified layer interface
339   (\texttt{rpp.h}, \texttt{drv.h}, \texttt {hal.h}, \texttt{sys.h} and
340   \texttt{os.h}), so that higher layers depend on the lower layer's interface
341   and not on individual elements from that layer.
342 \end{compactitem}
343
344 \begin{figure}
345 \begin{center}
346 \noindent
347 \includegraphics[width=250px]{images/layers.pdf}
348 \caption{The RPP library layers.}
349 \label{fig-layers}
350 \end{center}
351 \end{figure}
352
353 As a consequence of this division the source code files and interface files are
354 placed in private directories like \texttt{drv/din.h}. With this organization
355 user applications only needs to include the top layer interface files (for
356 example \texttt{rpp/rpp\_can.h}) to be able to use the selected library API.
357
358 The rest of the section provides basic description of each layer.
359
360 \subsection{Operating System layer}
361 \label{sec-operating-system-layer}
362 This is an interchangeable operating system (OS) layer containing the
363 FreeRTOS source files. The system can be easily replaced by another
364 version. For example it is possible to compile the RPP library for
365 Linux (using POSIX version of the FreeRTOS), which can be desirable
366 for some testing. The source files can be found in the
367 \texttt{$\langle$rpp\_lib$\rangle$/os} folder.
368
369 The following FreeRTOS versions are distributed:
370 \begin{description}
371 \item[6.0.4\_posix] POSIX version, usable for compilation of the
372   library for Linux system.
373 \item[8.2.2] Currently used FreeRTOS version. This is the version
374   downloaded from FreeRTOS.org with changes in directory structure.
375   Namely, include files have added the \emph{os/} prefix and platform
376   dependent code (portable) for \tgname{} is copied to the same
377   directory as platform independent code.
378 \end{description}
379
380 \subsection{System Layer} 
381 \label{sec-system-layer}
382 This layer contains system files with data types definitions, clock definitions,
383 interrupts mapping, MCU start-up sequence, MCU selftests, and other low level
384 code for controlling some of the MCU peripherals. The source files can be found
385 in \texttt{$\langle$rpp\_lib$\rangle$/rpp/src/sys}, the header files can
386 be found in \texttt{$\langle$rpp\_lib$\rangle$/rpp/include/sys}
387 folder.
388
389 Large part of this layer was generated by the HalCoGen tool (see
390 Section~\ref{sec-halcogen}). Some files were then modified by hand.
391
392 \subsection{Drivers layer} 
393 \label{sec-drivers-layer}
394 The Drivers layer contains code for controlling the RPP peripherals.
395 Typically, it contains code implementing IRQ handling, software
396 queues, management threads, etc. The layer benefits from the lower
397 layer thus it is not too low level, but still there are some
398 peripherals like ADC, which need some special procedure for
399 initialization and running, that would not be very intuitive for the
400 typical end user.
401
402 The source files can be found in
403 \texttt{$\langle$rpp\_lib$\rangle$/rpp/src/drv} and the header files can
404 be found in \texttt{$\langle$rpp\_lib$\rangle$/rpp/include/drv} folder.
405
406 \subsection{RPP Layer}
407 \label{sec-rpp-layer} 
408 The RPP Layer is the highest layer of the library. It provides an easy
409 to use set of functions for every peripheral and requires only basic
410 knowledge about them. For example, to use the ADC, the user can just
411 call \texttt{rpp\_adc\_init()} function and it calls a sequence of
412 Driver layer functions to initialize the hardware and software.
413
414 The source files can be found in
415 \texttt{$\langle$rpp\_lib$\rangle$/rpp/src/rpp} and the header files can
416 be found in \texttt{$\langle$rpp\_lib$\rangle$/rpp/include/rpp}.
417
418 \section{Document structure}
419 \label{sec-document-structure}
420 The structure of this document is as follows:
421 Chapter~\ref{chap-getting-started} gets you started using the RPP
422 software. Chapter~\ref{chap-c-support-library} describes the RPP
423 library. Chapter~\ref{chap-simulink-coder-target} covers the Simulink
424 code generation target and finally
425 Chapter~\ref{chap-rpp-test-software} documents a tool for interactive
426 testing of the RPP functionality.
427
428 \chapter{Getting started}
429 \label{chap-getting-started}
430
431 \section{Software requirements}
432 \label{sec-software-requirements}
433 The RPP software stack can be used on Windows and Linux platforms. The
434 following subsections mention the recommended versions of the required
435 software tools/packages.
436
437 \subsection{Linux environment} 
438 \label{sec-linux-environment}
439 \begin{itemize}
440         \item Debian based 64b Linux distribution (Debian 7.0 or Ubuntu 14.4 for
441 example).
442         \item Kernel version 3.11.0-12.
443         \item GCC version 4.8.1
444         \item GtkTerm 0.99.7-rc1
445         \item TI Code Composer Studio 5.5.0.00077
446         \item Matlab 2013b 64b with Embedded Coder
447         \item HalCoGen 4.00 (optional)
448         \item Uncrustify 0.59 (optional, see Section \ref{sec-compilation})
449         \item Doxygen 1.8.4 (optional, see Section \ref{sec-compiling-api-documentation})
450     \item Git 1.7.10.4 (optional)
451 \end{itemize}
452
453 \subsection{Windows environment}
454 \label{sec-windows-environment}
455 \begin{itemize}
456         \item Windows 7 Enterprise 64b Service Pack 1.
457         \item Microsoft Windows SDK v7.1
458         \item Bray Terminal v1.9b
459         \item TI Code Composer Studio 5.5.0.00077
460         \item Matlab 2013b 64b with Embedded Coder
461         \item HalCoGen 4.00 (optional)
462         \item Doxygen 1.8.4 (optional, see Section \ref{sec-compiling-api-documentation}) 
463         \item Uncrustify 0.59 (optional, see Section \ref{sec-compilation})
464     \item Git 1.9.4.msysgit.2 (optional)
465 \end{itemize}
466
467 \section{Software tools}
468 \label{sec-software-and-tools}
469
470 This section covers tool which are needed or recommended for work with
471 the RPP project.
472
473 \subsection{TI Code Composer Studio}
474 \label{sec-ti-ccs}
475 Code Composer Studio (CCS) is the official Integrated Development Environment
476 (IDE) for developing applications for Texas Instruments embedded processors. CCS
477 is multiplatform software based on
478 Eclipse open source IDE.
479
480 CCS includes Texas Instruments Code Generation Tools (CGT)
481 \cite{armoptimizingccppcompiler2012, armassemblylanguagetools2012}
482 (compiler, linker, etc). Simulink code generation target requires the
483 CGT to be available in the system, and thus, even if no library
484 development will be done or the IDE is not going to be used CCS is
485 still required.
486
487 You can find documentation for CGT compiler in \cite{armoptimizingccppcompiler2012} and
488 for CGT archiver in \cite{armassemblylanguagetools2012}.
489
490 \subsubsection{Installation on Linux} 
491 \label{sec-installation-on-linux}
492 Download CCS for Linux from:\\
493 \url{http://processors.wiki.ti.com/index.php/Category:Code\_Composer\_Studio\_v5}
494
495 Once downloaded, add executable permission to the installation file
496 and launch the installation by executing it. Installation must be done
497 by the root user in order to install a driver set.
498
499 \lstset{language=bash}
500 \begin{lstlisting}
501 chmod +x ccs_setup_5.5.0.00077.bin
502 sudo ./ccs_setup_5.5.0.00077.bin
503 \end{lstlisting}
504
505 After installation the application can be executed with:
506
507 \lstset{language=bash}
508 \begin{lstlisting}
509 cd <ccs>/ccsv5/eclipse/
510 ./ccstudio
511 \end{lstlisting}
512
513 The first launch on 64bits systems might fail. This can happen because CCS5 is
514 a 32 bit application and thus requires 32 bit libraries. They can be
515 installed by:
516
517 \lstset{language=bash}
518 \begin{lstlisting}
519 sudo apt-get install libgtk2.0-0:i386 libxtst6:i386
520 \end{lstlisting}
521
522 If the application crashes with a segmentation fault edit file:
523
524 \lstset{language=bash}
525 \begin{lstlisting}
526 nano <ccs>/ccsv5/eclipse/plugins/com.ti.ccstudio.branding_<version>/plugin_customization.ini
527 \end{lstlisting}
528
529 And change key \texttt{org.eclipse.ui/showIntro} to \texttt{false}.
530
531 \subsubsection{Installation on Windows}
532 \label{sec-installation-on-windows}
533 Installation for Windows is more straightforward than the installation
534 procedure for Linux. Download CCS for Windows from:\\
535 \url{http://processors.wiki.ti.com/index.php/Category:Code\_Composer\_Studio\_v5}
536
537 Once downloaded run the ccs\_setup\_5.5.0.00077.exe and install the CCS.
538
539 \subsubsection{First launch} 
540 \label{sec-first-launch}
541 If no other licence is available, choose ``FREE License -- for use
542 with XDS100 JTAG Emulators'' from the licensing options. Code download
543 for the board uses the XDS100 hardware.
544
545 \subsection{Matlab/Simulink}
546 \label{sec-matlab-simulink}
547 Matlab Simulink is a set of tools, runtime environment and development
548 environment for Model--Based \cite{modelbasedwiki2013} applications development,
549 simulations and code generation for target platforms.  Supported Matlab Simulink
550 version is R2013b for 64 bits Linux and Windows. A licence for an Embedded Coder is
551 necessary to be able to generate code from Simulink models, containing RPP blocks.
552
553 \subsection{HalCoGen}
554 \label{sec-halcogen}
555 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.
556
557 The tool is available for Windows at 
558 \begin{quotation}
559 \url{http://www.ti.com/tool/halcogen}
560 \end{quotation}
561
562 The HalCoGen has been used in early development stage of the RPP
563 project to generate the base code for some of the peripheral. The
564 trend is to not to use the HalCoGen any more, because the generated
565 code is not reliable enough for safety critical applications. Anyway it is
566 sometimes helpful to use it as a reference.
567
568 The HalCoGen is distributed for Windows only, but can be run on Linux
569 under Wine (tested with Wine version 1.6.2).
570
571 \subsection{GtkTerm and Bray Terminal}
572 \label{sec-gtkterm-bray-terminal}
573 Most of the interaction with the board is done through a RS-232 serial
574 connection. The terminal software used for communication is called GtkTerm for
575 Linux and Bray terminal for Windows.
576
577 To install GtkTerm execute:
578
579 \lstset{language=bash}
580 \begin{lstlisting}
581 sudo apt-get install gtkterm
582 \end{lstlisting}
583
584 The Bray Terminal does not require any installation and the executable file is
585 available at\\
586 \url{https://sites.google.com/site/terminalbpp/}
587
588 \subsection{C Compiler}
589 \label{sec-c-compiler}
590 A C language compiler has to be available on the development system to be able to
591 compile Matlab Simulink blocks S-functions.
592
593 For Linux a GCC 4.8.1 compiler is recommended and can be installed with a
594 command
595
596 \lstset{language=bash}
597 \begin{lstlisting}
598 sudo apt-get install gcc
599 \end{lstlisting}
600
601 For Windows, the C/C++ compiler is a part of Windows SDK, which is available from\\
602 \url{http://www.microsoft.com/en-us/download/details.aspx?id=8279}
603
604 \section{Project installation}
605 \label{sec-project-installation}
606 The RPP software is distributed in three packages and a standalone pdf
607 file containing this documentation. Every package is named like
608 \emph{$\langle$package\_name$\rangle$-version.zip}. The three packages
609 are:
610
611 \begin{description}
612 \item[rpp-simulink] Contains the source code of Matlab Simulink
613   blocks, demo models and scripts for downloading the generated
614   firmware to the target board from Matlab/Simulink. Details can be
615   found in Chapter \ref{chap-simulink-coder-target}.
616
617   The package also contains the binary of the RPP Library and all its
618   headers and other files necessary for building and downloading
619   Simulink models.
620 \item[rpp-test-sw] Contains an application for interactive testing and
621   control of the \tgtBoardName{} board over the serial interface. Details can be
622   found in Chapter~\ref{chap-rpp-test-software}.
623
624   The package also contains the binary of the RPP Library and all
625   headers and other files necessary for building and downloading the
626   application.
627 \item[rpp-lib] Contains the source code of the RPP library, described
628   in Chapter \ref{chap-c-support-library}. If you want to make any
629   changes in the drivers or the RPP API, this library has to be
630   compiled and linked with applications in the other two packages.
631   Library compilation is described in Section \ref{sec-compilation}.
632 \end{description}
633
634 The following sections describe how to start working with individual
635 packages.
636
637 \ifx\tgtId\tgtIdTMSRPP
638 \subsection{Getting sources from git repository}
639 \begin{verbatim}
640 git clone --recursive git@rtime.felk.cvut.cz:jenkicar/rpp-simulink
641 \end{verbatim}
642 If you get release packages, follow the instructions in the next sections.
643 \fi 
644
645 \subsection{rpp-simulink}
646 \label{sec-rpp-simulink-installation}
647 This section describes how to install the rpp-simulink project, which
648 is needed to try the demo models or to build your own models that use
649 the RPP blocks.
650
651 \begin{enumerate}
652 \item Unzip the \texttt{rpp-simulink-version.zip} file.
653 \item Follow the procedure  from Section
654   \ref{sec-configuration-simulink-for-rpp} for configuring Matlab
655   Simulink for the RPP project.
656 \item Follow the procedure from Section \ref{sec-crating-new-model}
657   for instructions about creating your own model which will use the
658   RPP Simulink blocks or follow the instructions in
659   Section~\ref{sec-running-model-on-hw} for downloading the firmware to the RPP hardware.
660 \end{enumerate}
661
662 \subsection{rpp-test-sw}
663 \label{sec-test-sw-installation}
664 This section describes how to install and run the application that
665 allows you to interactively control the RPP hardware. This can be
666 useful, for example, to test your modifications of the RPP library.
667
668 \begin{enumerate}
669         \item Unzip the \texttt{rpp-test-sw-version.zip} file.
670         \item Open the Code Composer Studio (see Section \ref{sec-ti-ccs}).
671         \item Import the \texttt{rpp-test-sw} project as described in
672           Section \ref{sec-openning-of-existing-project}.
673         \item Right click on the \texttt{rpp-test-sw} project in the
674       \textsc{Project Explorer} and select \textsc{Build Project}.
675         \item Follow the instructions in
676       Section~\ref{sec-running-software-on-hw} to download, debug and
677       run the software on the target hardware.
678 \end{enumerate}
679
680 \subsection{rpp-lib}
681 \label{sec-rpp-lib-installation}
682
683 This section describes how to open the rpp-lib project in Code
684 Composer Studio and how to use the resulting static library in an
685 application. This is only necessary if you need to modify the library
686 for some reason.
687
688 \begin{enumerate}
689         \item Unzip the \texttt{rpp-lib-version.zip} file.
690         \item Open the Code Composer Studio (see Section \ref{sec-ti-ccs}).
691         \item Import the rpp-lib project from directory
692           \texttt{rpp-lib-XXX/build/\tgtId} as described in
693           Section~\ref{sec-openning-of-existing-project}.
694         \item Compile the static library by selecting \textsc{Project
695             $\rightarrow$ Build Project} (see Section
696           \ref{sec-compilation} for more information). The compiled
697           library \texttt{rpp-lib.lib} and file
698           \texttt{Makefile.config} will appear in the
699           \texttt{rpp-lib-XXX} directory.
700     \item Either copy the compiled library and the content of the
701       \texttt{rpp/include} directory to the application, where you
702       want to use it or use the library in place, as described in
703       Section~\ref{sec:creating-new-project}.
704       \begin{itemize}
705       \item In the rpp-simulink application the library is located in
706         the \texttt{rpp/lib} folder.
707       \item In the rpp-test-sw application the library is located in
708         the \texttt{rpp-lib} folder.
709       \end{itemize}
710 \end{enumerate}
711
712 \section{Code Composer Studio usage}
713 \label{sec-code-composerpstudio-usage}
714
715 \subsection{Opening an existing project}
716 \label{sec-openning-of-existing-project}
717 The procedure for opening a project is similar to opening a project in
718 the standard Eclipse IDE.
719
720 \begin{enumerate}
721         \item Launch Code Composer Studio
722         \item Select \textsc{File$\rightarrow$Import}
723         \item In the dialog window select \textsc{Code Composer
724         Studio$\rightarrow$Existing CCS Eclipse project} as an import
725       source (see Figure \ref{fig-import-project}).
726         \item In the next dialog window click on \textsc{Browse} button
727       and find the root directory of the project.
728     \item Select the requested project in the \textsc{Discovered
729         project} section so that the result looks like in Figure
730       \ref{fig-select-project}.
731     \item Click the \textsc{Finish} button.
732 \end{enumerate}
733
734 \begin{figure}[H]\begin{center}
735         \includegraphics[width=350px]{images/import_project.png}
736         \caption{Import project dialog}
737         \label{fig-import-project}
738 \end{center}\end{figure}
739
740 \begin{figure}[H]\begin{center}
741         \includegraphics[width=350px]{images/select_project.png}
742         \caption{Select project dialog}
743         \label{fig-select-project}
744 \end{center}\end{figure}
745
746 \newpage
747 \subsection{Creating new project}
748 \label{sec:creating-new-project}
749 Follow these steps to create an application for \tgname{} MCU compiled with
750 CGT.
751
752 \begin{compactenum}
753 \item Create a new empty CCS project. Select \mcuname{} device, XDS100v2
754   connection and set Linker command file to
755   \texttt{rpp-lib/build/\tgtId/\ldscriptname}.
756
757   \noindent\includegraphics[scale=0.45]{images/base_1.png}
758
759 \item In \textsc{Project Explorer}, create normal folders
760   named \texttt{include} and \texttt{src}.
761
762 \item If you use Git version control system, add \texttt{.gitignore}
763   file with the following content to the root of that project:
764   \lstset{language=}
765 \begin{lstlisting}
766 Debug
767 Release
768 .settings/*
769 \end{lstlisting}
770
771   \newpage
772 \item In project \textsc{Properties}, add new variable of type
773   \texttt{Directory} named \texttt{RPP\_LIB\_ROOT} and set it to the
774   rpp-lib directory
775   root.
776
777   \noindent\includegraphics[scale=.45]{images/base_2.png}
778
779 \item Configure the compiler \#include search path to contain
780   project's \texttt{include} directory, \penalty-100
781   \texttt{\$\{RPP\_LIB\_ROOT\}/os/8.2.2/include} and
782   \texttt{\$\{RPP\_LIB\_ROOT\}/rpp/include}, in that order.
783
784   \includegraphics[scale=.43]{images/base_5.png}
785
786   \newpage
787 \item Add \texttt{\$\{RPP\_LIB\_ROOT\}/rpp-lib.lib} to the list of
788   linked libraries before the runtime support library
789   (\texttt{\tgtRtlib}).
790
791   \noindent\includegraphics[scale=.45]{images/base_3.png}
792
793 \item Configure the compiler to allow GCC extensions.
794
795   \noindent\includegraphics[scale=.45]{images/base_6.png}
796
797 \newpage
798 \item Create \texttt{main.c} file with the following content:
799 \begin{lstlisting}[language=C]
800 #include <rpp/rpp.h>
801
802 int main(void)
803 {
804         rpp_init();
805         rpp_sci_printf("Hello world\n");
806         vTaskStartScheduler();
807         return 0; /* not reached */
808 }
809
810 void vApplicationMallocFailedHook()
811 {}
812 void vApplicationStackOverflowHook()
813 {}
814 \end{lstlisting}
815
816 \item Compile the application by e.g. \textsc{Project $\rightarrow$
817     Build All}.
818 \item Select \textsc{Run} $\rightarrow$ \textsc{Debug}. The
819   application will be downloaded to the processor and run. A
820   breakpoint is automatically placed at \texttt{main()} entry. To
821   continue executing the application select \textsc{Run} $\rightarrow$
822   \textsc{Resume}.
823 \item If your application fails to run with a \texttt{\_dabort} interrupt, check
824 that the linker script selected in step 1 is not excluded from the build.
825 You can do this by right clicking the \texttt{\ldscriptname}  file
826 in the \textsc{Project Explorer} and unchecking the \textsc{Exclude from build}
827 item. The Code Composer Studio sometimes automaticaly excludes this file from
828 the build process when creating a new project.
829
830 % \item If not already created for another project, create new target
831 %   configuration. Select \textsc{Windows $\rightarrow$ Show View
832 %     $\rightarrow$ Target Configurations}. In the shown window, click
833 %   on \textsc{New Target Configuration} icon and configure XDS100v2
834 %   connection and \mcuname{} device as shown below. Click \textsc{Save},
835 %   connect your board and click \textsc{Test Connection}.
836
837 %   \medskip
838 %   \includegraphics[width=\linewidth]{images/target_conf.png}
839
840 % \newpage
841 \item Optionally, you can change debugger configuration by selecting
842   \textsc{Run $\rightarrow$ Debug Configurations}. In the
843   \textsc{Target} tab, you can configure not to break at \texttt{main}
844   or not to erase the whole flash, but necessary sectors only (see the
845   figure below).
846
847   \includegraphics[width=\linewidth]{images/debug_conf_flash.png}
848
849
850 \end{compactenum}
851
852 %% Comment this out for Eaton
853 % \subsubsection{Steps to configure new POSIX application:}
854 % Such an application can be used to test certain FreeRTOS features on
855 % Linux and can be compiled with a native GCC compiler.
856
857 % \begin{compactenum}
858 %       \item Create a new managed C project that uses Linux GCC toolchain.
859 %       \item Create a source folder \texttt{src}. Link all files from original
860 % CCS application to this folder.
861 %       \item Create a normal folder \texttt{include}. Create a folder
862 % \texttt{rpp} inside of it.  
863 %       \item Add common \texttt{.gitignore} to the root of that project:
864 % \lstset{language=}
865 % \begin{lstlisting}
866 % Debug
867 % Release
868 % .settings/*
869 % \end{lstlisting}
870 %       \item Add new variable \texttt{RPP\_LIB\_ROOT} and point to this
871 % repository branch root.\newline{}
872 % \noindent\includegraphics[width=\linewidth]{images/base_posix_1.png}
873 %       \item Configure compiler to include local includes, CCS application
874 % includes, OS includes for POSIX and RPP includes, in that order.\newline{}
875 % \noindent\includegraphics[width=\linewidth]{images/base_posix_2.png}
876 % \newpage
877 %       \item Add \texttt{rpp} and \texttt{pthread} to linker libraries and add
878 % \texttt{RPP\_LIB\_ROOT} to the library search path.\newline{}
879 % \noindent\includegraphics[width=\linewidth]{images/base_posix_3.png}
880 % \end{compactenum}
881
882 \subsubsection{Content of the application}
883
884 \begin{enumerate}
885 \item Include RPP library header file. 
886   \lstset{language=c++}
887 \begin{lstlisting}
888 #include "rpp/rpp.h"
889 \end{lstlisting}
890
891   If you want to reduce the size of the final application, you can
892   include only the headers of the needed modules. In that case, you
893   need to include two additional headers: \texttt{base.h} and, in case
894   when SCI is used for printing, \texttt{rpp/sci.h}.
895 \begin{lstlisting}
896 #include "rpp/hbr.h" /* We want to use H-bridge */
897 #include <base.h>       /* This is the necessary base header file of the rpp library. */
898 #include "rpp/sci.h" /* This is needed, because we use rpp_sci_printf in following examples. */
899 \end{lstlisting}
900
901 \newpage
902 \item Create one or as many FreeRTOS task function definitions as
903   required. Those tasks can use functions from the RPP library. Beware
904   that currently not all RPP functions are
905   reentrant\footnote{Determining which functions are not reentrant and
906     marking them as such (or making them reentrant) is planned as
907     future work.}. \lstset{language=c++}
908 \begin{lstlisting}
909 void my_task(void* p)
910 {
911     static const portTickType freq_ticks = 1000 / portTICK_RATE_MS;
912     portTickType last_wake_time = xTaskGetTickCount();
913     while (TRUE) {
914         /* Wait until next step */
915         vTaskDelayUntil(&last_wake_time, freq_ticks);
916         rpp_sci_printf((const char*)"Hello RPP.\r\n");
917     }
918 }
919 \end{lstlisting}
920
921 \item Create the main function that will:
922  \begin{itemize}
923         \item Initialize the RPP board. If you have included only selected
924 modules in step 1, initialize only those modules by calling their init
925 functions, for
926 example \texttt{rpp\_hbr\_init\(\)}.
927         \item Spawn the tasks the application requires. Refer to FreeRTOS API
928 for details.
929 \item Start the FreeRTOS Scheduler. Refer to FreeRTOS API for details
930   \cite{freertosapi}.
931         \item Handle error when the FreeRTOS scheduler cannot be started.
932
933 \lstset{language=c++}
934 \begin{lstlisting}
935 void main(void)
936 {
937     /* In case whole library is included: */
938         /* Initialize RPP board */
939         rpp_init();
940     /* In case only selected modules are included: */
941         /* Initialize HBR */
942         rpp_hbr_init();
943         /* Initialize sci for printf */
944         rpp_sci_init();
945         /* Enable interrups */
946         _enable_IRQ();
947
948     /* Spawn tasks */
949     if (xTaskCreate(my_task, (const signed char*)"my_task",
950             512, NULL, 0, NULL) != pdPASS) {
951         #ifdef DEBUG
952         rpp_sci_printf((const char*)
953             "ERROR: Cannot spawn control task.\r\n"
954         );
955         #endif
956         while (TRUE) { ; }
957     }
958
959     /* Start the FreeRTOS Scheduler */
960     vTaskStartScheduler();
961
962     /* Catch scheduler start error */
963     #ifdef DEBUG
964     rpp_sci_printf((const char*)
965             "ERROR: Problem allocating memory for idle task.\r\n"
966         );
967     #endif
968     while (TRUE) { ; }
969 }
970 \end{lstlisting}
971
972  \end{itemize}
973 \item Create hook functions for FreeRTOS:
974  \begin{itemize}
975  \item \texttt{vApplicationMallocFailedHook()} allows to catch memory allocation
976 errors.
977 \item \texttt{vApplicationStackOverflowHook()} allows to catch stack
978   overflow errors.
979
980 \lstset{language=c++}
981 \begin{lstlisting}
982 #if configUSE_MALLOC_FAILED_HOOK == 1
983 /**
984  * FreeRTOS malloc() failed hook.
985  */
986 void vApplicationMallocFailedHook(void) {
987     #ifdef DEBUG
988     rpp_sci_printf((const char*)
989             "ERROR: manual memory allocation failed.\r\n"
990         );
991     #endif
992 }
993 #endif
994
995
996 #if configCHECK_FOR_STACK_OVERFLOW > 0
997 /**
998  * FreeRTOS stack overflow hook.
999  */
1000 void vApplicationStackOverflowHook(xTaskHandle xTask,
1001                                    signed portCHAR *pcTaskName) {
1002     #ifdef DEBUG
1003     rpp_sci_printf((const char*)
1004             "ERROR: Stack overflow : \"%s\".\r\n", pcTaskName
1005         );
1006     #endif
1007 }
1008 #endif
1009 \end{lstlisting}
1010
1011 \newpage
1012  \end{itemize}
1013 \end{enumerate}
1014
1015
1016 \subsection{Downloading and running the software}
1017 \label{sec-running-software-on-hw}
1018 \subsubsection{Code Composer Studio Project}
1019 \label{sec-ccs-run-project}
1020 When an application is distributed as a CCS project, you have to open the
1021 project in the CCS as described in the Section
1022 \ref{sec-openning-of-existing-project}. Once the project is opened and built, it
1023 can be easily downloaded to the target hardware with the following procedure:
1024
1025 \begin{enumerate}
1026 \ifx\tgtId\tgtIdTMSRPP
1027         \item Connect the Texas Instruments XDS100v2 USB emulator to the JTAG port.
1028         \item Connect a USB cable to the XDS100v2 USB emulator and the development computer.
1029 \else
1030         \item Connect the USB cable to the \tgtBoardName{} board.
1031 \fi
1032         \item Plug in the power supply.  
1033         \item In the Code Composer Studio click on the
1034 \textsc{Run$\rightarrow$Debug}. The project will  be optionally built and
1035 the download process will start. The Code Composer Studio will switch into the debug
1036 perspective, when the download is finished.
1037         \item Run the program by clicking on the \textsc{Run} button, with the
1038 green arrow.  
1039 \end{enumerate}
1040
1041 \subsubsection{Binary File}
1042 \label{sec-binary-file}
1043 If the application is distributed as a binary file, without source code and CCS
1044 project files, you can download and run just the binary file by creating a new
1045 empty CCS project and configuring the debug session according to the following
1046 procedure:
1047
1048 \begin{enumerate}
1049         \item In Code Composer Studio click on
1050 \textsc{File$\rightarrow$New$\rightarrow$CCS Project}.  
1051         \item In the dialog window, type in a project name, for example
1052 myBinaryLoad, Select \textsc{Device
1053 variant} (ARM, Cortex R, \mcuname, Texas Instruments XDS100v2 USB Emulator)
1054 and select project template to \textsc{Empty Project}. The filled dialog should
1055 look like in Figure~\ref{fig-new-empty-project}
1056 \item Click the \textsc{Finish} button and a new empty project will
1057   be created.
1058 \item In the \textsc{Project Explorer} right-click on the project and
1059   select \textsc{Debug as$\rightarrow$Debug configurations}.
1060         \item Click  \textsc{New launch configuration} button
1061         \item Rename the New\_configuration to, for example, myConfiguration.
1062         \item Select configuration target file by clicking the \textsc{File
1063 System} button, finding and selecting the \texttt{rpp-lib-XXX/build/\tgtId/\tgconfigfilename} file. The result
1064 should look like in Figure~\ref{fig-debug-conf-main-diag}.  
1065 \item In the \textsc{program} pane select the binary file you want to
1066   download to the board. Click on the \textsc{File System} button,
1067   find and select the binary file. Try, for example
1068   \texttt{rpp-test-sw.out}. The result should look like in
1069   Figure~\ref{fig-debug-conf-program-diag}.
1070 \item You may also tune the target configuration as described in
1071   Section \ref{sec-target-configuration}.
1072 \item Finish the configuration by clicking the \textsc{Apply} button
1073   and download the code by clicking the \textsc{Debug} button. You can
1074   later invoke the download also from the
1075   \textsc{Run$\rightarrow$Debug} CCS menu. It is not necessary to
1076   create more Debug configurations and CCS empty projects as you can
1077   easily change the binary file in the Debug configuration to load a
1078   different binary file.
1079 \end{enumerate}
1080
1081 \begin{figure}[H]\begin{center}
1082         \includegraphics[scale=.45]{images/new_empty_project.png}
1083         \caption{New empty project dialog}
1084         \label{fig-new-empty-project}
1085 \end{center}\end{figure}
1086
1087 \begin{figure}[H]\begin{center}
1088         \includegraphics[scale=.45]{images/debug_configuration_main.png}
1089         \caption{Debug Configuration Main dialog}
1090         \label{fig-debug-conf-main-diag}
1091 \end{center}\end{figure}
1092
1093 \subsection{Target configuration}
1094 \label{sec-target-configuration}
1095 Default target configuration erases the whole Flash memory, before
1096 downloading the code. This takes long time and in most cases it is
1097 not necessary. You may disable this feature by the following procedure:
1098 \begin{enumerate}
1099         \item Right click on the project name in the \textsc{Project Browser}
1100         \item Select \textsc{Debug as$\rightarrow$Debug Configurations}
1101         \item In the dialog window select \textsc{Target} pane.
1102         \item In the \textsc{Flash Settings}, \textsc{Erase Options} select
1103 \textsc{Necessary sectors only}.
1104         \item Save the configuration by clicking the \textsc{Apply} button
1105 and close the dialog.
1106 \end{enumerate}
1107
1108 \begin{figure}[H]\begin{center}
1109         \includegraphics[scale=.45]{images/debug_configuration_program.png}
1110         \caption{Configuration Program dialog}
1111         \label{fig-debug-conf-program-diag}
1112 \end{center}\end{figure}
1113
1114 \section{Matlab Simulink usage}
1115 \label{sec-matlab-simulink-usage}
1116 This section describes the basics of working with the RPP code
1117 generation target for Simulink. For a more detailed description of the
1118 code generation target refer to
1119 Chapter~\ref{chap-simulink-coder-target}.
1120
1121 \subsection{Configuring Simulink for RPP}
1122 \label{sec-configuration-simulink-for-rpp}
1123 Before any work or experiments with the RPP blocks and models, the RPP
1124 target has to be configured to be able to find the ARM cross-compiler,
1125 native C compiler and some other necessary files. Also the S-Functions
1126 of the blocks have to be compiled by the mex tool.
1127 \begin{enumerate}
1128 \item Download and install Code Composer Studio CCS (see
1129   Section~\ref{sec-ti-ccs}).
1130 \item Install a C compiler. On Windows follow Section~\ref{sec-c-compiler}.
1131 \item On Windows you have to tell the \texttt{mex} which C compiler to
1132   use. In the Matlab command window run the \texttt{mex -setup}
1133   command and select the native C compiler.
1134
1135 \begin{lstlisting}[basicstyle=\tt\footnotesize]
1136 >> mex -setup
1137
1138 Welcome to mex -setup.  This utility will help you set up
1139 a default compiler.  For a list of supported compilers, see
1140 http://www.mathworks.com/support/compilers/R2013b/win64.html
1141
1142 Please choose your compiler for building MEX-files:
1143
1144 Would you like mex to locate installed compilers [y]/n? y
1145
1146 Select a compiler:
1147 [1] Microsoft Software Development Kit (SDK) 7.1 in c:\Program Files (x86)\Microsoft Visual Studio 10.0
1148
1149 [0] None
1150
1151 Compiler: 1
1152
1153 Please verify your choices:
1154
1155 Compiler: Microsoft Software Development Kit (SDK) 7.1
1156 Location: c:\Program Files (x86)\Microsoft Visual Studio 10.0
1157
1158 Are these correct [y]/n? y
1159
1160 ***************************************************************************
1161   Warning: MEX-files generated using Microsoft Windows Software Development
1162            Kit (SDK) require that Microsoft Visual Studio 2010 run-time
1163            libraries be available on the computer they are run on.
1164            If you plan to redistribute your MEX-files to other MATLAB
1165            users, be sure that they have the run-time libraries.
1166 ***************************************************************************
1167
1168
1169 Trying to update options file: C:\Users\Michal\AppData\Roaming\MathWorks\MATLAB\R2013b\mexopts.bat
1170 From template:              C:\PROGRA~1\MATLAB\R2013b\bin\win64\mexopts\mssdk71opts.bat
1171
1172 Done . . .
1173
1174 **************************************************************************
1175   Warning: The MATLAB C and Fortran API has changed to support MATLAB
1176            variables with more than 2^32-1 elements.  In the near future
1177            you will be required to update your code to utilize the new
1178            API. You can find more information about this at:
1179            http://www.mathworks.com/help/matlab/matlab_external/upgrading-mex-files-to-use-64-bit-api.html
1180            Building with the -largeArrayDims option enables the new API.
1181 **************************************************************************
1182 \end{lstlisting}
1183
1184 \item Configure the RPP code generation target:
1185
1186 Open Matlab and in the command window run:
1187
1188 \lstset{language=Matlab}
1189 \begin{lstlisting}
1190 cd <rpp-simulink>/rpp/rpp/
1191 rpp_setup
1192 \end{lstlisting}
1193
1194 This will launch the RPP setup script. This script will ask the user to provide
1195 the path to the CCS compiler root directory (the directory where \texttt{armcl}
1196 binary is located), normally:
1197
1198 \begin{verbatim}
1199 <ccs>/tools/compiler/arm_5.X.X/
1200 \end{verbatim}
1201
1202 Then Matlab path will be updated and block S-Functions will be built.
1203
1204 \item Create new model or load a demo:
1205
1206   Demos are located in \texttt{\repo/rpp/demos}. Creation of new
1207   models is described in Section~\ref{sec-crating-new-model} below.
1208 \end{enumerate}
1209
1210
1211 \subsection{Working with demo models}
1212 \label{sec-openning-demo-models}
1213 The demo models are available from the directory
1214 \texttt{\repo/rpp/demos}. To access the demo models for reference or
1215 for downloading to the RPP board open them in Matlab. Use either the
1216 GUI or the following commands:
1217
1218 \begin{lstlisting}[language=Matlab]
1219 cd <rpp-simulink>/rpp/demos
1220 open cantransmit.slx
1221 \end{lstlisting}
1222
1223 The same procedure can be used to open any other models. To build the
1224 demo select \textsc{Code$\rightarrow$C/C++ Code $\rightarrow$Build
1225   Model}. This will generate the C code and build the binary firmware
1226 for the RPP board. To run the model on the target hardware see
1227 Section~\ref{sec-running-model-on-hw}.
1228
1229 \subsection{Creating new model}
1230 \label{sec-crating-new-model}
1231 \begin{enumerate}
1232         \item Create a model by clicking \textsc{New$\rightarrow$Simulink Model}.
1233         \item Open the configuration dialog by clicking \textsc{Simulation$\rightarrow$Model Configuration Parameters}.
1234         \item The new Simulink model needs to be configured in the following way:
1235         \begin{compactitem}
1236         \item Solver (Figure \ref{fig-solver}):
1237          \begin{compactitem}
1238          \item Solver type: \emph{Fixed-step}
1239      \item Solver: \emph{discrete}
1240      \item Fixed-step size: \emph{Sampling period in seconds. Minimum
1241          is 0.001.}
1242          \item Tasking mode -- choose between the following:
1243           \begin{compactitem}
1244           \item \textit{Auto} selects SingleTasking modes for
1245             single-rate model or MultiTasking mode for multi-rate
1246             models. See Section \ref{sec-singlet-multit-modes}
1247           \item \textit{SingleTasking} selects SingleTasking mode. See
1248             Section \ref{sec-singlet-mode} for details.
1249           \item \textit{MultiTasking} select MultiTasking mode. In
1250             this mode \textit{Higher priority value indicates higher
1251               task priority} should be checked. See Section
1252             \ref{sec-multit-mode} for details.
1253           \end{compactitem}
1254
1255            \begin{figure}
1256                  \centering
1257                  \includegraphics[scale=.45]{images/simulink_solver.png}
1258                  \caption{Solver settings}
1259                  \label{fig-solver}
1260         \end{figure}
1261          \end{compactitem}
1262 %       \item Diagnostics $\rightarrow$ Sample Time (Figure~\ref{fig-sample-time-settings}):
1263 %        \begin{compactitem}
1264 %        \item Disable warning ``Source block specifies -1 sampling
1265 %        time''. It's ok for the source blocks to run once per tick.
1266 %          \begin{figure}
1267 %                \centering
1268 %                \includegraphics[scale=.45]{images/simulink_diagnostics.png}
1269 %                \caption{Sample Time settings}
1270 %                \label{fig-sample-time-settings}
1271 %       \end{figure}
1272 %       \end{compactitem}
1273         \item Code generation (Figure~\ref{fig-code-gen-settings}):
1274          \begin{compactitem}
1275          \item Set ``System target file'' to \texttt{rpp.tlc}.
1276            \begin{figure}
1277                  \centering
1278                  \includegraphics[scale=.45]{images/simulink_code.png}
1279                  \caption{Code Generation settings}
1280                  \label{fig-code-gen-settings}
1281         \end{figure}
1282         \end{compactitem}
1283 \end{compactitem}
1284 \item Once the model is configured, you can open the Library Browser
1285   (\textsc{View $\rightarrow$ Library Browser}) and add the necessary
1286   blocks to create the model. The RPP-specific blocks are located in
1287   the RPP Block Library.
1288         \item From Matlab command window change the current directory to where
1289 you want your generated code to appear, e.g.:
1290 \begin{lstlisting}[language=Matlab]
1291 cd /tmp/my-code
1292 \end{lstlisting}
1293 The code will be generated in a subdirectory named
1294 \texttt{<model>\_rpp}, where \texttt{model} is the name of the
1295 Simulink model.
1296         \item Generate the code by choosing \textsc{Code $\rightarrow$ C/C++
1297 Code  $\rightarrow$ Build Model}.
1298 \end{enumerate}
1299
1300 To run the model on the \tgtBoardName{} board continue with Section
1301 \ref{sec-running-model-on-hw}.
1302
1303 \subsection{Running models on the RPP board}
1304 \label{sec-running-model-on-hw}
1305 To run the model on the \tgtBoardName{} hardware you have to enable the download
1306 feature and build the model by following this procedure:
1307  \begin{enumerate}
1308  \item Open the model you want to run (see
1309    Section~\ref{sec-openning-demo-models} for example with demo
1310    models).
1311  \item Click on \textsc{Simulation$\rightarrow$Model Configuration
1312      Parameters}.
1313  \item In the \textsc{Code Generation$\rightarrow$RPP Options} pane
1314    check the \textsc{Download compiled binary to RPP} checkbox. Click
1315    the \textsc{OK} button
1316  \item Connect the target hardware to the computer (see Section
1317    \ref{sec-ccs-run-project}) and build the model by \textsc{Code
1318      $\rightarrow$ C/C++ Code $\rightarrow$ Build Model}. If the build
1319    succeeds, the download process will start automatically and once
1320    the downloading is finished, the application will run immediately.
1321 \end{enumerate}
1322
1323 %%\subsubsection{Using OpenOCD for downloading}
1324 %%\label{sec:using-open-downl}
1325 %%
1326 %%On Linux systems, it is possible to use an alternative download
1327 %%mechanism based on the OpenOCD tool. This results in much shorter
1328 %%download times. Using OpenOCD is enabled by checking ``Use OpenOCD to
1329 %%download the compiled binary'' checkbox. For more information about
1330 %%the OpenOCD configuration refer to our
1331 %%wiki\footnote{\url{http://rtime.felk.cvut.cz/hw/index.php/TMS570LS3137\#OpenOCD_setup_and_Flashing}}.
1332 %%
1333 %%Note: You should close any ongoing Code Composer Studio debug sessions
1334 %%before downloading the generated code to the RPP board. Otherwise the
1335 %%download fails.
1336
1337 \section{Configuring serial interface}
1338 \label{sec-configuration-serial-interface}
1339 The main mean for communication with the RPP board is the serial line.
1340 Each application may define its own serial line settings, but the
1341 following settings are the default:
1342
1343 \begin{itemize}
1344         \item Baudrate: 115200
1345         \item Parity: none
1346         \item Bits: 8
1347         \item Stopbits: 1
1348         \item Flow control: none
1349 \end{itemize}
1350
1351 Use GtkTerm on Linux or Bray Terminal on Windows for accessing the
1352 serial interface. On \tgtBoardName{} board, the serial line is tunneled over
1353 the USB.
1354 % TODO: Conditional compilation
1355  % See Section \ref{sec-hardware-description} for reference about
1356 % the position of the serial interface connector on the RPP board.
1357
1358 \section{Bug reporting}
1359 \label{sec-bug-reporting}
1360
1361 Please report any problems to CTU's bug tracking system at
1362 \url{https://redmine.felk.cvut.cz/projects/eaton-rm48}. New users have
1363 to register in the system and notify Michal Sojka about their
1364 registration via $\langle{}sojkam1@fel.cvut.cz\rangle{}$ email
1365 address.
1366
1367 \chapter{C Support Library}
1368 \label{chap-c-support-library}
1369
1370 This chapter describes the implementation of the C support library
1371 (RPP Library), which is used both for Simulink code generation target
1372 and command line testing tool.
1373
1374 \section{Introduction}
1375 \label{sec-description}
1376 The RPP C Support Library (also called RPP library) defines the API for
1377 working with the board. It includes drivers and the operating system.
1378 The library is
1379 designed from the board user perspective and exposes a simplified high-level API
1380 to handle the board's peripheral modules in a safe manner. The library is
1381 compiled as static library named \texttt{rpp-lib.lib} and can be found in
1382 \texttt{\repo/rpp/lib}.
1383
1384 The RPP library can be used in any project, where the RPP hardware
1385 support is required and it is also used in two applications --
1386 Simulink Coder Target, described in Chapter
1387 \ref{chap-simulink-coder-target}, and the command line testing tool,
1388 described in Chapter \ref{chap-rpp-test-software}.
1389
1390 For details about the library architecture, refer to Section~\ref{sec-software-architecture}.
1391
1392 \section{API development guidelines}
1393 \label{sec-api-development-guidlines}
1394
1395 The following are the development guidelines used for developing the RPP API:
1396
1397 \begin{compactitem}
1398         \item User documentation should be placed in header files, not in source
1399 code, and should be Doxygen formatted using autobrief. Documentation for each
1400 function present is mandatory and must mention whether the function is
1401 thread safe or not.
1402         \item Function declarations in the headers files is for public functions
1403 only. Do not declare local/static/private functions in the header.
1404         \item Documentation in source code files should be non-doxygen formatted
1405 and intended for developers, not users. Documentation here is optional and at
1406 the discretion of the developer.
1407         \item Always use standard data types for IO when possible. Use custom
1408 structs as very last resort.  \item Use prefix based functions names to avoid
1409 clash. The prefix is of the form \texttt{$\langle$layer$\rangle$\_$\langle$module$\rangle$\_}, for example
1410 \texttt{rpp\_din\_update()} for the update function of the DIN module in the RPP
1411 Layer.  
1412         \item Be very careful about symbol export. Because it is used as a
1413 static library the modules should not export any symbol that is not intended to
1414 be used (function) or \texttt{extern}'ed (variable) from application. As a rule
1415 of thumb declare all global variables as static. 
1416         \item Only the RPP Layer symbols are available to user applications. All
1417 information related to lower layers is hidden for the application. This is
1418 accomplished by the inclusion of the rpp.h or rpp\_\{mnemonic\}.h file on the
1419 implementations files only and never on the interface files. Never expose any
1420 other layer to the application or to the whole system below the RPP layer. In
1421 other words, never \texttt{\#include "foo/bar.h"} in any RPP Layer header
1422 file.
1423 \end{compactitem}
1424
1425 \section{Coding style}
1426 \label{sec-coding-style}
1427 In order to keep the code as clean as possible, unified coding style
1428 should be followed by any contributor to the code. The used coding
1429 style is based on the default configuration of Code Composer Studio
1430 editor. Most notable rule is that the Tab character is 4 spaces.
1431
1432 The RPP library project is prepared for use of a tool named
1433 Uncrustify. The Uncrustify tool checks the code and fixes those lines
1434 that do not match the coding style. However, keep in mind that the
1435 program is not perfect and sometimes it can modify code where the
1436 suggested coding style has been followed. This does not causes
1437 problems as long as the contributor follows the committing procedure
1438 described in next paragraph.
1439
1440 When contributing to the code, the contributor should learn the
1441 current coding style from existing code. When a new feature is
1442 implemented and committed to the local repository, the following
1443 commands should be called in Linux terminal:
1444
1445 \begin{lstlisting}[language=bash]
1446 make uncrustify
1447 git diff
1448 \end{lstlisting}
1449 The first line command corrects many found coding style violations and
1450 the second command displays them. If the user agree with the
1451 modification, he/she should amend the last commit, for example by:
1452 \begin{lstlisting}[language=bash]
1453 git add --update
1454 git commit --amend
1455 \end{lstlisting}
1456
1457 \section{Subdirectory content description}
1458 \label{sec-rpp-lib-subdirectory-content-description}
1459
1460 The following files and directories are present in the library source
1461 code package:
1462
1463 \begin{description}
1464 \item[rpp-lib.lib] Compiled RPP library.
1465
1466   The library is needed for Simulink models and other ARM/\tgname{}
1467   applications. It is placed here by the Makefile, when the library is
1468   compiled.
1469
1470 \item[apps/] Various applications related to the RPP library.
1471
1472   This include the CCS studio project for generating of the static
1473   library and a test suite. The test suit in this directory has
1474   nothing common with the test suite described later in
1475   Chapter~\ref{chap-rpp-test-software} and those two suits are going
1476   to be merged in the future. Also other Hello World applications are
1477   included as a reference about how to create an \tgname{}
1478   application.
1479 \item[build] The library can be compiled for multiple targets. Each
1480   supported target has a subdirectory here, which stores configuration
1481   of how to compile the library and applications for different target.
1482   Each subdirectory contains a CCS project and Makefiles to build the
1483   library for the particular target.
1484 \item[build/$\langle$target$\rangle$/Makefile.config] Configuration
1485   for the particular target. This includes compiler and linker
1486   switches etc.
1487 \item[build/$\langle$target$\rangle$/*.cmd]
1488 CGT Linker command file.
1489
1490 This file is used by all applications that need to tun on the RPP
1491 board, including the Simulink models and test suite. It includes
1492 instructions for the CGT Linker about target memory layout and where
1493 to place various code sections.
1494
1495 \item[halcogen/] HalCoGen project files for the supported boards and
1496   scripts for automated conversion of HalCoGen-generated files for use
1497   in rpp-lib.
1498
1499   Note: This is work in progress. Currently only ``pinmux'' files for
1500   tms570\_hydctr board were produced by the scripts here.
1501
1502 \item[os/] OS layers directory. See
1503   Section~\ref{sec-operating-system-layer} for more information about
1504   currently available operating system versions and
1505   Section~\ref{sec-changing-os} for information how to replace the
1506   operating system.
1507 \item[rpp/] Main directory for the RPP library.
1508 \item[rpp/doc/] RPP Library API
1509   documentation.
1510 \item[rpp/include/\{layer\} and rpp/src/\{layer\}] Interface files and
1511   implementations files for given \texttt{\{layer\}}. See
1512   Section~\ref{sec-software-architecture} for details on the RPP
1513   Layer.
1514 \item[rpp/include/rpp/rpp.h] Main library header file.
1515
1516   To use this library with all its modules, just include this file
1517   only. Also, before using any library function call the
1518   \texttt{rpp\_init()} function for hardware initialization.
1519 \item[rpp/include/rpp/rpp\_\{mnemonic\}.h] Header file for
1520   \texttt{\{mnemonic\}} module.
1521
1522   These files includes function definitions, pin definitions, etc,
1523   specific to \{mnemonic\} module. See also
1524   Section~\ref{sec-api-development-guidlines}.
1525
1526   If you want to use only a subset of library functions and make the
1527   resulting binary smaller, you may include only selected
1528   \texttt{rpp\_\{mnemonic\}.h} header files and call the specific
1529   \texttt{rpp\_\{mnemonic\}\_init} functions, instead of the
1530   \texttt{rpp.h} and \texttt{rpp\_init} function.
1531         \item[rpp/src/rpp/rpp\_\{mnemonic\}.c] Module implementation.
1532
1533       Implementation of \texttt{rpp\_\{mnemonic\}.h}'s functions on
1534       top of the DRV library.
1535         \item[rpp/src/rpp/rpp.c] Implementation of library-wide functions.
1536 \end{description}
1537
1538 \section{Compilation}
1539 \label{sec-compilation}
1540
1541 To compile the library open the Code Composer studio project
1542 \texttt{rpp-lib} from appropriate \texttt{build/<target>} directory
1543 (see Section~\ref{sec-openning-of-existing-project}) and build the
1544 project (\textsc{Project $\rightarrow$ Build Project}). If the build
1545 process is successful, the \texttt{rpp-lib.lib} and
1546 \texttt{Makefile.config} files will appear in the library root
1547 directory.
1548
1549 It is also possible to compile the library using the included
1550 \texttt{Makefile}. From the Linux command line run:
1551 \begin{lstlisting}[language=bash]
1552 cd <library-root>/build/<target>/Debug   #or Release
1553 make
1554 \end{lstlisting}
1555 Note that this only works if Code Composer Studio is installed in
1556 \texttt{/opt/ti} directory. Otherwise, you have to set
1557 \texttt{CCS\_UTILS\_DIR} variable.
1558
1559 On Windows command line run:
1560 \begin{lstlisting}[language=bash]
1561 cd <library-root>\build\<target>\Debug
1562 set CCS_UTILS_DIR=C:\ti\ccsv5\utils
1563 C:\ti\ccsv5\utils\bin\gmake.exe lib
1564 \end{lstlisting}
1565
1566 You have to use \texttt{gmake.exe} instead of \texttt{make} and it is
1567 necessary to set variable \texttt{CCS\_UTILS\_DIR} manually. You can
1568 also edit \texttt{\repo/build/Makefile.rules.arm} and set the variable
1569 there.
1570
1571 Note that the Makefile still requires the Code Composer Studio (ARM
1572 compiler) to be installed because of the CGT.
1573
1574 \section{Compiling applications using the RPP library}
1575 \label{sec:comp-appl-using}
1576
1577 The relevant aspects for compiling and linking an application using
1578 the RPP library are summarized below.
1579
1580 % \subsection{ARM target (RPP board)}
1581 % \label{sec:arm-target-rpp}
1582
1583 The detailed instructions are presented in
1584 Section~\ref{sec:creating-new-project}. Here we briefly repeat the
1585 main steps.
1586
1587         \begin{compactitem}
1588     \item Configure include search path to contain the directory of
1589       used FreeRTOS version, e.g.
1590       \texttt{\repo/os/8.2.2/include}. See Section
1591       \ref{sec-software-architecture}.
1592     \item Include \texttt{rpp/rpp.h} header file or just the needed
1593       peripheral specific header files such as \texttt{rpp/can.h}.
1594     \item Add library \texttt{rpp-lib.lib} to the linker libraries.
1595       The RPP library must be placed before Texas Instruments
1596       support library \tgtRtlib.
1597     \item Use the provided linker command file
1598       \texttt{\ldscriptname}.
1599         \end{compactitem}
1600
1601 % \subsection{POSIX target}
1602 % \label{sec:posix-target}
1603
1604 %       \begin{compactitem}
1605 %     \item Include headers files of the OS for Simulation. At the time
1606 %       of this writing the OS is POSIX FreeRTOS 6.0.4.
1607 %     \item Include header files for the RPP library or for modules you
1608 %       want to use (rpp\_can.h for CAN module for example).
1609 %     \item Add library \texttt{librpp.a} to the linker libraries.
1610 %     \item Add \texttt{pthread} to the linker libraries.
1611 %       \end{compactitem}
1612
1613 \section{Compiling API documentation}
1614 \label{sec-compiling-api-documentation}
1615 The documentation of the RPP layer is formatted using Doxygen
1616 documentation generator. This allows to generate a high quality API
1617 reference. To generate the API reference run in a Linux terminal:
1618
1619 \lstset{language=bash}
1620 \begin{lstlisting}
1621 cd <repo>/rpp/doc/api
1622 make
1623 xdg-open html/index.html
1624 \end{lstlisting}
1625
1626 The files under \texttt{\repo/rpp/doc/api/content} are used for the API
1627 reference generation are their name is self-explanatory:
1628
1629 \begin{verbatim}
1630 blocks_map.html
1631 blocks.png
1632 cvut.png
1633 footer.html
1634 main_page.dox
1635 \end{verbatim}
1636
1637 \section{Changing operating system}
1638 \label{sec-changing-os}
1639 The C Support Library contains by default the FreeRTOS operating
1640 system in version 8.2.2. This section describes what is necessary to
1641 change in the library and other packages in order to replace the
1642 operating system.
1643
1644 \subsection{Operating system code and API}
1645
1646 The source and header files of the current operating system (OS) are
1647 stored in directory \texttt{\repo/rpp/lib/os}. The files of the new
1648 operating system should also be placed in this directory.
1649
1650 To make the methods and resources of the new OS available to the C Support
1651 Library, modify the \texttt{\repo/rpp/lib/rpp/include/base.h} file to include
1652 the operating system header files.
1653
1654 Current implementation for FreeRTOS includes a header file
1655 \texttt{\repo/rpp/lib/os/\-8.2.2\-include/os.h}, which
1656 contains all necessary declarations and definitions for the FreeRTOS.
1657 We suggest to provide a similar header file for your operating system as
1658 well.
1659
1660 In order to compile another operating system into the library, it is
1661 necessary to modify \texttt{\repo/rpp/lib/Makefile.var} file, which
1662 contains a list of files that are compiled into the library. All lines
1663 starting with \texttt{os/} should be updated. 
1664
1665 \subsection{Device drivers}
1666 Drivers for SCI and ADC depend on the FreeRTOS features. These
1667 features need to be replaced by equivalent features of the new
1668 operating system. Those files should be modified:
1669 \begin{description}
1670 \item[\repo/rpp/lib/rpp/include/sys/ti\_drv\_sci.h] Defines a data
1671   structure, referring to FreeRTOS queue and semaphore.
1672 \item[\repo/rpp/lib/rpp/src/sys/ti\_drv\_sci.c] Uses FreeRTOS queues
1673   and semaphores.
1674 \item[\repo/rpp/lib/rpp/include/drv/sci.h] Declaration of
1675   \texttt{drv\_sci\_receive()} contains \texttt{portTick\-Type}. We
1676   suggest replacing this with OS independent type, e.g. number of
1677   milliseconds to wait, with $-1$ meaning infinite waiting time.
1678 \item[\repo/rpp/lib/rpp/src/drv/sci.c] Uses the following FreeRTOS
1679   specific features: semaphores, queues, data types
1680   (\texttt{portBASE\_TYPE}) and
1681   critical sections (\texttt{taskENTER\_CRITICAL} and
1682   \texttt{task\-EXIT\_CRITICAL}). Inside FreeRTOS critical sections,
1683   task preemption is disabled. The same should be ensured by the other
1684   operating system or the driver should be rewritten to use other
1685   synchronization primitives.
1686 \item[\repo/rpp/lib/rpp/src/drv/adc.c] Uses FreeRTOS semaphores.
1687 \end{description}
1688
1689 \subsection{System start}
1690 The initialization of the MCU and the system is in the
1691 \texttt{\repo/rpp/lib/rpp/src/sys/sys\_startup.c} file. If the new
1692 operating system needs to handle interrupts generated by the Real-Time
1693 Interrupt module, the pointer to the Interrupt Service Routine (ISR)
1694 \texttt{vPreemptiveTick} has to be replaced.
1695
1696 \subsection{Simulink template for main function}
1697
1698 When the operating system in the library is replaced, the users of the
1699 library must be changed as well. In case of Simulink code generation
1700 target, described in Chapter~\ref{chap-simulink-coder-target}, the
1701 template for generation of the \texttt{ert\_main.c} file, containing
1702 the main function, has to be modified to use proper functions for task
1703 creation, task timing and semaphores. The template is stored in
1704 \texttt{\repo/rpp/rpp/rpp\_mrmain.tlc} file.
1705
1706 \chapter{Simulink Coder Target}
1707 \label{chap-simulink-coder-target}
1708
1709 The Simulink Coder Target allows to convert Simulink models to C code,
1710 compile it and download to the board.
1711
1712 \section{Introduction}
1713 \label{sec-introduction}
1714
1715 The Simulink RPP Target provides support for C source code generation from Simulink models and
1716 compilation of that code on top of the RPP library and the FreeRTOS operating system. This target
1717 uses Texas Instruments ARM compiler (\texttt{armcl}) included in the Code Generation Tools distributed with
1718 Code Composer Studio, and thus it depends on it for proper functioning.
1719
1720 This target also provides support for automatic download of the compiled binary to the RPP
1721 board.
1722
1723 \begin{figure}\begin{center}
1724 \noindent
1725 \includegraphics[scale=.45]{images/tlc_process.png}
1726 \caption{TLC code generation process. \cite[p. 1-6]{targetlanguagecompiler2013}}
1727 \end{center}\end{figure}
1728
1729 \section{Features and limitations}
1730 \label{sec-features}
1731
1732 \begin{itemize}
1733 \item Sampling frequencies up to 1\,kHz.
1734 \item Multi-rate models can be executed in a single or multiple OS
1735   tasks. Multi-tasking mode allows high-rate tasks to preempt low-rate
1736   tasks. See Section \ref{sec-singlet-multit-modes} for more details.
1737 \item No External mode support yet. We work on it.
1738 \item Custom compiler options, available via OPTS variable in
1739   \emph{Make command} at \emph{Code Generation} tab (see Figure
1740   \ref{fig-code-gen-settings}). For example \texttt{make\_rtw
1741     OPTS="-O0 -g"}.
1742 \end{itemize}
1743
1744 \section{RPP Options pane}
1745 \label{sec-rpp-target-options}
1746
1747 The RPP Target includes the following configuration options, all of them
1748 configurable per model under  \textsc{Code Generation} \noindent$\rightarrow$
1749 \textsc{RPP Options}:
1750
1751 \begin{itemize}
1752 \item \textbf{C system stack size}: this parameter is passed directly
1753   to the linker for the allocation of the stack. Note that this stack
1754   is used only for initializing the application and FreeRTOS. Once
1755   everything is initialized, another stack is used by the generated
1756   code. See below. Default value is 4096.
1757
1758 \item \textbf{C system heap size}:
1759   \label{sec-rpp-target-options-heap-size} this parameter is passed
1760   directly to the linker for the allocation of the heap. Currently,
1761   the heap is not used, but will be used by the external mode in the future.
1762 Note that FreeRTOS uses its own heap whose size is independent of this
1763 parameter. 
1764 \item \textbf{Model step task stack size}: this parameter will be
1765 passed to the \texttt{xTaskCreate()} that
1766   creates the task for the model to run. In a Simulink model there are always two tasks:
1767  \begin{itemize}
1768  \item The worker task. This task is the one that executes the model
1769    step. This task requires enough stack memory to execute the step.
1770    If your model does not run, it might be caused by too small stack.
1771    The memory needed for the stack depends on the size and structure
1772    of the model.
1773  \item The control task. This task controls when the worker task should execute and controls overruns.
1774
1775  \end{itemize}
1776 \item \textbf{Download compiled binary to RPP}: if set, this option will download the generated binary to
1777   the board after the model is successfully built. Note that this option is unaware of the option
1778   \textit{Generate code only} in the \textit{Code Generation} options panel, so it will try to download even if
1779   only source code has been generated, failing graciously or uploading an old binary laying around
1780   in the build directory. This option calls the \texttt{rpp\_download.m} script, which is in turn a
1781   wrapper on the \texttt{loadti.sh}, \texttt{loadti.bat} and \texttt{loadopenocd.sh} script. More information on the \texttt{loadti.sh}
1782   script can be found in:
1783 \begin{verbatim}
1784 <ccs>/ccs_base/scripting/examples/loadti/readme.txt
1785 http://processors.wiki.ti.com/index.php/Loadti
1786 \end{verbatim}
1787
1788   The \texttt{loadti.sh} and \texttt{loadti.bat} script will close after the
1789 download of the generated program, leaving the loaded program running.
1790
1791   The \texttt{loadopenocd.sh} script will close after the download of the
1792 generated program as well, but the program will be stopped.  In order to run
1793 the loaded program a manual reset of the board is required.
1794
1795 \item \textbf{Download compiled binary to SDRAM}: This feature is not yet
1796 implemented for the simulink target.
1797
1798 \item \textbf{Use OpenOCD to download the compiled binary}: This feature is not yet
1799 implemented for the \mcuname{} simulink target.
1800 % TODO Not true - use conditional compilation here.
1801
1802 \item \textbf{Print model metadata to SCI at start}: if set this option will
1803 print a message to the Serial Communication Interface when the model start
1804 execution on the board. This is very helpful to identify the model running on
1805 the board. The message is in the form: 
1806
1807 \begin{verbatim}
1808 `model_name' - generated_date (TLC tlc_version)
1809 \end{verbatim}
1810
1811   For example:
1812 \begin{verbatim}
1813 `hbridge_analog_control' - Wed Jun 19 14:10:44 2013 (TLC 8.3 (Jul 20 2012))
1814 \end{verbatim}
1815 \end{itemize}
1816
1817 \section{Subdirectory  content description}
1818 \label{sec-simulink-subdirectory-content-description}
1819 This section describes the directories of the Simulink Coder. If you are
1820 interested in particular file, refer the description at the beginning of the
1821 file.
1822
1823 \begin{description}
1824         \item[doc/] Contains the sources of the documentation, you are now
1825 reading.  
1826         \item[refs/] Contains third party references, which license allows the
1827 distribution.
1828 \item[rpp/blocks] Contains the Simulink blocks specific to the
1829   \tgtBoardName{} board and their sources (.c and .tlc files). When an
1830   user calls \texttt{rpp\_setup.m}, these files are processed and
1831   Simulink block library \texttt{rpp\_lib.slx} is created.
1832         \item[rpp/blocks/tlc\_c]Contains the templates for C code generation from the
1833 Matlab Simulink model.
1834         \item[rpp/demos] Contains demo models, which purpose is to serve as a
1835 reference for the usage and for testing.  
1836         \item[rpp/lib] Contains the C Support Library. See Chapter
1837 \ref{chap-c-support-library}.  \item[rpp/loadopenocd] Contains download scripts
1838 for Linux support of the OpenOCD, for code downloading to the target.
1839         \item[rpp/loadti] Contains download scripts for Linux and Windows
1840 support for code downloading to the target, using Texas Instruments CCS code
1841 downloader.  
1842         \item[rpp/rpp] Contains set of support script for the Code Generator.
1843 \end{description}
1844
1845 \section{Tasking modes}
1846 \label{sec-singlet-multit-modes}
1847
1848 This section describes two different modes (single- and multi-tasking)
1849 of how generated code of multi-rate models can be executed. Tasking
1850 mode can be selected for every model in the configuration dialog as
1851 described in Section \ref{sec-crating-new-model}.
1852
1853 For single-rate models, the mode selection does not matter. For
1854 multi-rate models, the mode selection becomes important as it may
1855 influence certain system properties such as safety or performance.
1856
1857 \subsection{SingleTasking mode}
1858 \label{sec-singlet-mode}
1859 In this mode all Simulink tasks, defined by their sampling rate, run
1860 in a single operating system task (thread). This means that the period
1861 of the highest rate Simulink task cannot be greater than the
1862 worst-case execution time of all Simulink tasks together. On the other
1863 hand, using this mode reduces the risk of failures caused by task
1864 synchronization errors, e.g. race conditions, deadlocks.
1865
1866 \subsection{MultiTasking mode}
1867 \label{sec-multit-mode}
1868
1869 In this mode every Simulink task, defined by its sampling rate, runs
1870 in its own operating system task (thread). Thread priorities are
1871 assigned based on task rates in such a way that tasks with higher
1872 rates can preempt tasks with lower rates. This means that the period
1873 of the fastest sampling rate is limited only by the execution time of
1874 this task and not of all the tasks in the system.
1875
1876 This mode offers more efficient use of system resources (CPU) but
1877 there is a possibility of failures caused by task synchronization
1878 errors.
1879
1880 \section{Block Library Overview}
1881 \label{sec-block-library-overview}
1882 The Simulink Block Library is a set of blocks that allows Simulink models to use
1883 board IO and communication peripherals. The available blocks are summarized in
1884 Table~\ref{tab:block-lib-status} and more detailed description is
1885 given in Section~\ref{sec-blocks-description}.
1886
1887 \begin{table}
1888 \begin{center}\begin{tabular}{|lp{5cm}lll|}
1889 \hline
1890 \textbf{Category} & \textbf{Name} & \textbf{Status} & \textbf{Mnemonic} & \textbf{Header} \\
1891 \hline
1892 \input{block_table.tex}
1893 \hline
1894 \end{tabular}\end{center}
1895
1896   \caption{Block library overview}
1897   \label{tab:block-lib-status}
1898 \end{table}
1899
1900 \label{sec-blocks-implementation}
1901 All of the blocks are implemented as manually created C Mex S-Function . In this section the 
1902 approach taken is briefly explained.
1903
1904 \subsection{C MEX S-Functions}
1905 \label{sec-c-mex-functions}
1906  \begin{compactitem}
1907  \item C : Implemented in C language. Other options are Fortran and Matlab language itself.
1908  \item MEX: Matlab Executable. They are compiled by Matlab - C compiler wrapper called MEX.
1909  \item S-Function: System Function, as opposed to standard functions, or user functions.
1910  \end{compactitem}
1911
1912 A C MEX S-Function is a structured C file that implements some mandatory and
1913 optional  callbacks for a specification of a number of inputs, outputs, data
1914 types, parameters, rate, validity checking, etc.  A complete list of callbacks
1915 can be found in:
1916         \begin{quotation}
1917 \htmladdnormallink{http://www.mathworks.com/help/simulink/create-cc-s-functions.html}{http://www.mathworks.com/help/simulink/create-cc-s-functions.html}
1918 \end{quotation}
1919
1920 The way a C MEX S-Function participates in a Simulink simulation is shown on the
1921 diagram \ref{fig-sfunctions-process}:
1922
1923 \begin{figure}[H]\begin{center}
1924 \noindent
1925 \includegraphics[scale=.45]{images/sfunctions_process.png}
1926 \caption{Simulation cycle of a S-Function. \cite[p. 57]{simulinkdevelopingsfunctions2013}}
1927 \label{fig-sfunctions-process}
1928 \end{center}\end{figure}
1929
1930 In general, the S-Function can perform calculations, inputs and outputs for simulation. Because 
1931 the RPP blocks are for hardware peripherals control and IO the blocks are 
1932 implemented as pure sink or pure source, the S-Function is just a descriptor of
1933 the block and does not perform any calculation and does not provide any input or
1934 output for simulations. 
1935
1936 The implementation of the S-Functions in the RPP project has following layout:
1937
1938 \begin{itemize}
1939   \item Define S-Function name \texttt{S\_FUNCTION\_NAME}.
1940   \item Include header file \texttt{header.c}, which in connection with
1941 \texttt{trailer.c} creates a miniframework for writing S-Functions.  
1942   \item In \texttt{mdlInitializeSizes} define:
1943   \begin{itemize}
1944         \item Number of \textit{dialog} parameter.
1945         \item Number of input ports.
1946         \begin{compactitem}
1947                 \item Data type of each input port.
1948         \end{compactitem}
1949         \item Number of output ports.
1950         \begin{compactitem}
1951                 \item Data type of each output port.
1952         \end{compactitem}
1953         \item Standard options for driver blocks.
1954   \end{itemize}
1955   \item In \texttt{mdlCheckParameters}:
1956   \begin{itemize}
1957         \item Check data type of each parameter.
1958         \item Check range, if applicable, of each parameter.
1959   \end{itemize}
1960   \item In \texttt{mdlSetWorkWidths}:
1961   \begin{compactitem}
1962         \item Map \textit{dialog} parameter to \textit{runtime} parameters.
1963         \begin{itemize}
1964                 \item Data type of each \textit{runtime} parameter.
1965         \end{itemize}
1966   \end{compactitem}
1967   \item Define symbols for unused functions.
1968   \item Include trailer file \texttt{trailer.c}.
1969 \end{itemize}
1970
1971 The C MEX S-Function implemented can be compiled with the following command:
1972
1973 \lstset{language=bash}
1974 \begin{lstlisting}
1975 <matlabroot>/bin/mex sfunction_{mnemonic}.c
1976 \end{lstlisting}
1977
1978 As noted the standard is to always prefix S-Function with \texttt{sfunction\_}
1979 and use lower case mnemonic of the block.
1980
1981 Also a script called \texttt{compile\_blocks.m} is included. The script that
1982 allows all \texttt{sfunctions\_*.c} to be fed to the \texttt{mex} compiler so
1983 all S-Functions are compiled at once. To use this script, in Matlab do:
1984
1985 \lstset{language=Matlab}
1986 \begin{lstlisting}
1987 cd <repo>/rpp/blocks/
1988 compile_blocks()
1989 \end{lstlisting}
1990
1991 \subsection{Target Language Compiler files}
1992 \label{sec-target-language-compiler-files}
1993
1994 In order to generate code for each one of the S-Functions, every S-Function implements a TLC file
1995 for \textit{inlining} the S-Function on the generated code. The TLC files describe how to 
1996 generate code for a specific C MEX S-Function block. They are programmed using TLC own language and 
1997 include C code within TLC instructions, just like LaTeX files include normal text in between LaTeX 
1998 macros.
1999
2000 The standard for a TLC file is to be located under the \texttt{tlc\_c} subfolder from where the 
2001 S-Function is located and to use the very exact file name as the S-Function but with the \texttt{.tlc}
2002 extension: \texttt{sfunction\_foo.c} \noindent$\rightarrow$ \texttt{tlc\_c/sfunction\_foo.tlc}
2003
2004 The TLC files implemented for this project use 3 hook functions in particular (other are available, 
2005 see TLC reference documentation):
2006 \begin{itemize}
2007 \item \texttt{BlockTypeSetup}: \newline{}
2008   BlockTypeSetup executes once per block type before code generation begins.
2009   This function can be used to include elements required by this block type, like includes or
2010   definitions.
2011 \item \texttt{Start}: \newline{}
2012   Code here will be placed in the \texttt{void
2013 $\langle$modelname$\rangle$\_initialize(void)}. Code placed here will execute
2014 only once.
2015 \item \texttt{Outputs}: \newline{}
2016   Code here will be placed in the \texttt{void
2017 $\langle$modelname$\rangle$\_step(void)} function. Should be used to get the
2018 inputs of a block and/or to set the outputs of that block.
2019 \end{itemize}
2020
2021 The general layout of the TLC files implemented for this project is:
2022 \begin{itemize}
2023 \item In \texttt{BlockTypeSetup}: \newline{}
2024   Call common function \texttt{\%$<$RppCommonBlockTypeSetup(block, system)$>$} that will include the 
2025   \texttt{rpp/rpp\i\_mnemonic.h} header file (can be called multiple times but header is included only once).
2026 \item \texttt{Start}: \newline{}
2027   Call setup routines from RPP Layer for the specific block type, like HBR enable, DIN pin setup, 
2028   DAC value initialization, SCI baud rate setup, among others.
2029 \item \texttt{Outputs}: \newline{}
2030   Call common IO routines from RPP Layer, like DIN read, DAC set, etc. Success of this functions
2031   is checked and in case of failure error is reported to the block using ErrFlag.
2032 \end{itemize}
2033
2034 C code generated from a Simulink model is placed on a file called
2035 \texttt{$\langle$modelname$\rangle$.c} along with other support files in a
2036 folder called \texttt{$\langle$modelname$\rangle$\_$\langle$target$\rangle$/}.
2037 For example, the source code generated for model \texttt{foobar} will be placed
2038 in current Matlab directory \texttt{foobar\_rpp/foobar.c}.
2039
2040 The file \texttt{$\langle$modelname$\rangle$.c} has 3 main functions:
2041 \begin{compactitem}
2042 \item \texttt{void $\langle$modelname$\rangle$\_step(void)}: \newline{}
2043   This function recalculates all the outputs of the blocks and should be called once per step. This
2044   is the main working function.
2045 \item \texttt{void $\langle$modelname$\rangle$\_initialize(void)}: \newline{}
2046   This function is called only once before the first step is issued. Default values for blocks IOs
2047   should be placed here.
2048 \item \texttt{void $\langle$modelname$\rangle$\_terminate(void)}: \newline{}
2049   This function is called when terminating the model. This should be used to free memory or revert 
2050   other operations made in the initialization function. With current implementation this function
2051   should never be called unless an error is detected and in most models it is empty.
2052 \end{compactitem}
2053
2054 \section{Block reference}
2055 \label{sec-blocks-description}
2056
2057 This section describes each one of the Simulink blocks present in the Simulink
2058 RPP block library, shown in Figure \ref{fig-block-library}.
2059
2060 \begin{figure}[h]
2061   \begin{center}
2062     \includegraphics[width=\textwidth]{images/block_library.png}
2063   \end{center}
2064 \caption{Simulink RPP Block Library.}
2065 \label{fig-block-library}
2066 \end{figure}
2067 \clearpage
2068 \input{block_desc.tex}
2069
2070 \section{Compilation}
2071 \label{sec-simulink-compilation}
2072 The first step, before any attempt to compile demo or other models, is to compile the S-Functions of the RPP blocks. The S-Functions are compiled during the Configuring Simulink for RPP, described in Section \ref{sec-configuration-simulink-for-rpp}. If you want to recompile the S-Functions without reconfiguring the Simulink, open the Matlab and run those commands in the Matlab commad line:
2073 \lstset{language=Matlab}
2074 \begin{lstlisting}
2075 cd <rpp-simulink>/rpp/blocks
2076 compile_blocks
2077 \end{lstlisting}
2078
2079 Once the S-Functions are compiled, the C code can be generated from the models. Demos can be compiled one by one with a procedure described in Section \ref{sec-openning-demo-models} or all at once with one of those procedures:
2080
2081 \begin{enumerate}
2082         \item Open Matlab and run those commands in the Matlab command line:
2083 \lstset{language=Matlab}
2084 \begin{lstlisting}
2085 cd <rpp-simulink>/rpp/demos
2086 rpp_build_demos
2087 \end{lstlisting}
2088         \item Run those commands in a Linux terminal:
2089 \begin{lstlisting}[language=bash]
2090 cd <rpp-simulink>/rpp/demos
2091 make
2092 \end{lstlisting}
2093
2094 or Windows command line:
2095
2096 \begin{lstlisting}[language=bash]
2097 cd <rpp-simulink>\rpp\demos
2098 "C:\ti\ccsv5\utils\bin\"gmake.exe lib
2099 \end{lstlisting}
2100
2101 Both commands will create a directory for each compiled demo, which will contain the generated C code and binary file with the firmware. To download the firmware to the board and run it, see Section \ref{sec-running-software-on-hw}.
2102 \end{enumerate}
2103
2104  \section{Adding new functionality}
2105 \label{sec:adding-new-funct}
2106 This section describes how to create new Simulink blocks and how to add them to the RPP
2107 blocks library. The new block creation process consists of several steps:
2108 \begin{enumerate}
2109         \item Addition of the new functionality to the RPP C support library.
2110         \item Definition of the block interface as a C MEX S-Function
2111           (Section~\ref{sec:block-definition-c})
2112         \item Compilation of the block definition to MEX file
2113           (Section~\ref{sec:c-mex-file})
2114         \item Creation of the code generator template (TLC) file
2115           (Section~\ref{sec:tlc-file-creation}).
2116         \item Creation of an S-Function block in the RPP block library
2117           and ``connecting'' this block with the C MEX and TLC files
2118           (Section~\ref{sec:creation-an-s})
2119         \item Optional: Creation of the mask for the new block. The mask
2120           specifies graphical representation of the block as well as
2121           the content of the block parameters dialog box.
2122 \end{enumerate}
2123 The following subsections demonstrate the procedure on an example of a simple user defined block.
2124
2125 \subsection{Block interface definition in a C MEX S-function}
2126 \label{sec:block-definition-c}
2127 In order to use a custom block in the Simulink model, Simulink must know
2128 a certain number of block attributes, such as the number and type of
2129 block inputs, outputs and parameters. These attributes are specified
2130 by a set of functions in a C file. This C file gets compiled by the MEX
2131 compiler into a MEX file and is then used in an S-Function block.
2132 Simulink calls the functions in the C MEX file to obtain the above
2133 mentioned block attributes. In case of RPP blocks, no other
2134 functionality is present in the C MEX file.
2135
2136 The C files are stored in \texttt{\repo/rpp/blocks} directory and are named as
2137 \texttt{sfunction\_$\langle$name$\rangle$.c}. Feel free to open any of
2138 the C files as a reference.
2139
2140 Every C file that will be used with the RPP library should begin with
2141 a comment in YAML\footnote{\url{http://yaml.org/},
2142   \url{https://en.wikipedia.org/wiki/YAML}} format. The information in
2143 this block is used to automatically generate both printed and on-line
2144 documentation. Although this block is not mandatory, it is highly
2145 recommended, as it helps keeping the documentation consistent and
2146 up-to-date.
2147
2148 The YAML documentation block may look like this:
2149 \begin{lstlisting}[language=c,basicstyle=\tt\footnotesize]
2150 /*
2151 %YAML 1.2
2152 ---
2153 Name: Name Of The Block
2154 Category: IO blocks
2155 Header: rpp/sci.h
2156 Mnemonic: MBLK
2157
2158 Inputs:
2159   - { name: "Some Input Signal", type: "bool" }
2160
2161 Outputs:
2162   - { name: "Some Output Signal", type: "bool"   }
2163
2164 Parameters:
2165
2166 # Description and Help is in Markdown mark-up
2167 Description: |
2168
2169   This is a stub of an example block.
2170
2171 Help: |
2172
2173   This block is a part of an example about how to create
2174   new Matlab Simulink blocks for RPP board.
2175
2176 Status: Unstable
2177
2178 RPP API functions used:
2179   - rpp_sci_print()
2180
2181 Relevant demos:
2182 ...
2183 */
2184 \end{lstlisting}
2185
2186 Following parts are obligatory and the block will not work without them. It starts with a
2187 definition of the block name and inclusion of a common source file:
2188
2189 \begin{lstlisting}[language=c]
2190 #define S_FUNCTION_NAME sfunction_myblock
2191 #include "header.c"
2192 \end{lstlisting}
2193
2194 To let Simulink know the type of the inputs, outputs and how many parameters
2195 will the block have, the \texttt{mdlInitializeSizes()} function has to be defined like this:
2196
2197 \begin{lstlisting}[language=c]
2198 static void mdlInitializeSizes(SimStruct *S)
2199 {
2200     /* The block will have no parameters. */
2201     if (!rppSetNumParams(S, 0)) {
2202         return;
2203     }
2204     /* The block will have one input signal. */
2205     if (!ssSetNumInputPorts(S, 1)) {
2206         return;
2207     }
2208     /* The input signal will be of type boolean */
2209     rppAddInputPort(S, 0, SS_BOOLEAN);
2210     /* The block will have one output signal */
2211     if (!ssSetNumOutputPorts(S, 1)) {
2212         return;
2213     }
2214     /* The output signal will be of type boolean */
2215     rppAddOutputPort(S, 0, SS_BOOLEAN);
2216     
2217     rppSetStandardOptions(S);
2218 }
2219 \end{lstlisting}
2220
2221 The C file may contain several other optional functions definitions for parameters check,
2222 run-time parameters definition and so on. For information about those functions refer the comments
2223 in the header.c file, trailer.c file and documentation of Simulink S-Functions.
2224
2225 The minimal C file compilable into C MEX has to contain following
2226 macros to avoid linker error messages about some of the optional
2227 functions not being defined:
2228 \begin{lstlisting}[language=c]
2229 #define COMMON_MDLINITIALIZESAMPLETIMES_INHERIT
2230 #define UNUSED_MDLCHECKPARAMETERS
2231 #define UNUSED_MDLOUTPUTS
2232 #define UNUSED_MDLTERMINATE
2233 \end{lstlisting}
2234
2235 Every C file should end by inclusion of a common trailer source file:
2236
2237 \begin{lstlisting}[language=c]
2238 #include "trailer.c"
2239 \end{lstlisting}
2240
2241 \subsection{C MEX file compilation}
2242 \label{sec:c-mex-file}
2243 In order to compile the created C file, the development environment
2244 has to be configured first as described in
2245 Section~\ref{sec-matlab-simulink-usage}.
2246
2247 All C files in the directory \texttt{\repo/rpp/blocks} can be compiled
2248 into C MEX by running script
2249 \texttt{\repo/rpp/blocks/compile\_blocks.m} from Matlab command
2250 prompt. If your block requires some special compiler options, edit the
2251 script and add a branch for your block.
2252
2253 To compile only one block run the \texttt{mex sfunction\_myblock.c}
2254 from Matlab command prompt.
2255
2256 \subsection{TLC file creation}
2257 \label{sec:tlc-file-creation}
2258 The TLC file is a template used by the code generator to generate the
2259 C code for the RPP board. The TLC files are stored in
2260 \texttt{\repo/rpp/blocks/tlc\_c} folder and their names must be the
2261 same (except for the extension) as the names of the corresponding
2262 S-Functions, i.e. \texttt{sfunction\_$\langle$name$\rangle$.tlc}. Feel
2263 free to open any of the TLC files as a reference.
2264
2265 TLC files for RPP blocks should contain a header:
2266 \begin{lstlisting}[language=c]
2267 %implements sfunction_myblock "C"
2268 %include "common.tlc"
2269 \end{lstlisting}
2270
2271 Code Generator expects several functions to be implemented in the TLC file. The functions are not obligatory, but most of the blocks will probably need them:
2272 \begin{enumerate}
2273         \item BlockTypeSetup
2274         \item BlockInstanceSetup
2275         \item Start
2276         \item Outputs
2277 \end{enumerate}
2278
2279 For detailed description about each one of those functions, refer to
2280 \cite{targetlanguagecompiler2013}. A simple TLC file, which generates
2281 some code may look like this:
2282 \begin{lstlisting}[language=c]
2283 %implements sfunction_myblock "C"
2284 %include "common.tlc"
2285
2286 %function BlockTypeSetup(block, system) void
2287         %% Ensure required header files are included
2288         %<RppCommonBlockTypeSetup(block, system)>
2289         %<LibAddToCommonIncludes("rpp/sci.h")>
2290 %endfunction
2291
2292 %function Outputs(block, system) Output
2293   %if !SLibCodeGenForSim()
2294     %assign in_signal = LibBlockInputSignal(0, "", "", 0)
2295     %assign out_signal = LibBlockOutputSignal(0, "", "", 0)
2296
2297     %<out_signal> = !%<in_signal>;
2298     rpp_sci_printf("Value: %d\r\n", %<in_signal>);
2299 %endif
2300 %endfunction
2301 %% [EOF]
2302 \end{lstlisting}
2303
2304 The above template causes the generated code to contain
2305 \texttt{\#include "rpp/sci.h"} line and whenever the block is
2306 executed, its output will be the negation of its input and the value
2307 of the input signal will be printed to the serial line.
2308
2309 \subsection{Creation of an S-Function block in the RPP block library}
2310 \label{sec:creation-an-s}
2311 User defined Simulink blocks can be included in the model as
2312 S-Function blocks. Follow this procedure to create a new block in the
2313 RPP block library:
2314 \begin{enumerate}
2315 \item Create a new Simulink library by selecting
2316   \textsc{File$\rightarrow$New$\rightarrow$Library} and save it as
2317   \texttt{\repo\-/rpp/blocks/rpp\_$\langle$name$\rangle$.slx}.
2318   Alternatively, open an existing library.
2319 \item In case of opening an existing library, unlock it for editing by
2320   choosing \textsc{Diagram$\rightarrow$Unlock Library}.
2321 \item Open a Simulink Library Browser
2322   (\textsc{View$\rightarrow$Library Browser}) open
2323   \textsc{Simulink$\rightarrow$User-Defined Functions} and drag the
2324   \textsc{S-Function} block into the newly created library.
2325 \item Double click on the just created \textsc{S-Function} block and
2326   fill in the \textsc{S-function name} field. Put there the name
2327   (without the extension) of the created C MEX S-Function, e.g.
2328   sfunction\_myblock. The result should like like in
2329   Figure~\ref{fig-simulink_s_fun_cfg}.
2330   \begin{figure}[h]\begin{center}
2331       \noindent
2332       \includegraphics[scale=.45]{images/simulink_s_fun_config.png}
2333       \caption{Configuration dialog for user defined S-function.}
2334       \label{fig-simulink_s_fun_cfg}
2335     \end{center}\end{figure}
2336 \item If your block has some parameters, write their names (you can
2337   choose them arbitrarily) in the \textsc{S-function parameters}
2338   field, separated by commas. \label{item:1}
2339 \item Now you should see the new Simulink block with the right number
2340   of inputs and outputs.
2341 \item Optional: Every user-defined block can have a \emph{mask}, which
2342   provides some useful information about the name of the block,
2343   configuration dialog for parameters and names of the IO signals. The
2344   block can be used even without the mask, but it is not as user
2345   friendly as with proper mask. Right-click the block and select
2346   \textsc{Mask$\rightarrow$Create Mask...}. In the definition of
2347   parameters, use the same names as in step~\ref{item:1}. See
2348   \cite[Section ``Block Masks'']{mathworks13:simul_2013b} for more
2349   information.
2350 \item Save the library and run \texttt{rpp\_setup} (or just
2351   \texttt{rpp\_generate\_lib}) from Matlab command line to add the newly
2352   created block to RPP block library (\texttt{rpp\_lib.slx}).
2353 \end{enumerate}
2354
2355 Now, you can start using the new block in Simulink models as described
2356 in Section~\ref{sec-crating-new-model}.
2357
2358
2359 \section{Demos reference}
2360 The Simulink RPP Demo Library is a set of Simulink models that use blocks from
2361 the Simulink RPP Block Library and generates code using the Simulink RPP Target.
2362
2363 This demos library is used as a test suite for the Simulink RPP Block Library
2364 but they are also intended to show basic programs built using it. Because of
2365 this, the demos try to use more than one
2366 type of block and more than one block per block type.
2367
2368 In the reference below you can find a complete description for each of the demos.
2369
2370 \subsection{ADC demo}
2371 \begin{figure}[H]\begin{center}
2372 \noindent
2373 \includegraphics[scale=.45]{images/demo_adc.png}
2374 \caption{Example of the usage of the Analog Input blocks for RPP.}
2375 \end{center}\end{figure}
2376
2377 \textbf{Description:}
2378
2379 Demostrates how to use Analog Input blocks in order to measure voltage. This demo
2380 measures voltage on every available Analog Input and prints the values on the
2381 Serial Interface.
2382
2383 \subsection{Simple CAN demo}
2384 \begin{figure}[H]\begin{center}
2385 \noindent
2386 \includegraphics[scale=.45]{images/demo_simple_can.png}
2387 \caption{The simplest CAN demonstration.}
2388 \end{center}\end{figure}
2389
2390 \textbf{Description:}
2391
2392 The simplest possible usage of the CAN bus. This demo is above all designed for
2393 testing the CAN configuration and transmission.
2394
2395 \subsection{CAN transmit}
2396 \begin{figure}[H]\begin{center}
2397 \noindent
2398 \includegraphics[scale=.45]{images/demo_cantransmit.png}
2399 \caption{Example of the usage of the CAN blocks for RPP.}
2400 \end{center}\end{figure}
2401
2402 \textbf{Description:}
2403
2404 Demostrates how to use CAN Transmit blocks in order to:
2405
2406 \begin{compactenum}
2407 \item Send unpacked data with data type uint8, uint16 and uint32.
2408 \item Send single and multiple signals packed into CAN\_MESSAGE by CAN Pack block.
2409 \item Send a message as extended frame type to be received by CAN Receive
2410 configured to receive both, standard and extended frame types.
2411 \end{compactenum}
2412
2413 Demostrates how to use CAN Receive blocks in order to:
2414
2415 \begin{compactenum}
2416 \item Receive unpacked data of data types uint8, uint16 and uint32.
2417 \item Receive and unpack received CAN\_MESSAGE by CAN Unpack block.
2418 \item Configure CAN Receive block to receive Standard, Extended and both frame types.
2419 \item Use function-call mechanism to process received messages
2420 \end{compactenum}
2421
2422 \subsection{Continuous time demo}
2423 \begin{figure}[H]\begin{center}
2424 \noindent
2425 \includegraphics[scale=.45]{images/demo_continuous.png}
2426 \caption{The demonstration of contiuous time.}
2427 \end{center}\end{figure}
2428
2429 \textbf{Description:}
2430
2431 This demo contains two integrators, which are running at continuous time. The main goal
2432 of this demo is to verify that the generated code is compilable and is working even when
2433 discrete and continuous time blocks are combined together.
2434
2435 \subsection{Simulink Demo model}
2436 \begin{figure}[H]\begin{center}
2437 \noindent
2438 \includegraphics[scale=.45]{images/demo_board.png}
2439 \caption{Model of the complex demonstration of the boards peripherals.}
2440 \end{center}\end{figure}
2441
2442 \textbf{Description:}
2443
2444 This model demonstrates the usage of RPP Simulink blocks in a complex and interactive
2445 application. The TI HDK kit has eight LEDs placed around the MCU. The application
2446 rotates the light around the MCU in one direction. Every time the user presses the button
2447 on the HDK, the direction is switched.
2448
2449 The state of the LEDs is sent on the CAN bus as a message with ID 0x1. The button can
2450 be emulated by CAN messages with ID 0x0. The message 0x00000000 simulates button release
2451 and the message 0xFFFFFFFF simulates the button press.
2452
2453 Information about the state of the application are printed on the Serial Interface. 
2454
2455 \subsection{Echo char}
2456 \begin{figure}[H]\begin{center}
2457 \noindent
2458 \includegraphics[scale=.45]{images/demo_echo_char.png}
2459 \caption{Echo Character Simulink demo for RPP.}
2460 \end{center}\end{figure}
2461
2462 \textbf{Description:}
2463
2464 This demo will echo (print back) any character received through the Serial Communication
2465 Interface (115200-8-N-1).
2466
2467 Note that the send subsystem is implemented a as \textit{triggered} subsystem and will execute only
2468 if data is received, that is, Serial Receive output is non-negative. Negative values are errors.
2469
2470 \subsection{GIO demo}
2471 \begin{figure}[H]\begin{center}
2472 \noindent
2473 \includegraphics[scale=.45]{images/demo_gio.png}
2474 \caption{Demonstration of DIN and DOUT blocks}
2475 \end{center}\end{figure}
2476
2477 \textbf{Description:}
2478
2479 The model demonstrates how to use the DIN blocks and DOUT blocks, configured in every mode. The DOUTs
2480 are pushed high and low with period 1 second. The DINs are reading inputs and printing the values
2481 on the Serial Interface with the same period.
2482
2483 \subsection{Hello world}
2484 \begin{figure}[H]\begin{center}
2485 \noindent
2486 \includegraphics[scale=.45]{images/demo_hello_world.png}
2487 \caption{Hello World Simulink demo for RPP.}
2488 \end{center}\end{figure}
2489
2490 \textbf{Description:}
2491
2492 This demo will print \texttt{Hello Simulink} to the Serial Communication Interface (115200-8-N-1) one
2493 character per second. The output speed is driven by the Simulink model step which is set to one
2494 second.
2495
2496 \subsection{Multi-rate SingleTasking demo}
2497 \label{sec:mult-single-thre}
2498
2499 \begin{figure}[H]\begin{center}
2500 \noindent
2501 \includegraphics[scale=.45]{images/demo_multirate_st.png}
2502 \caption{Multi-rate SingleTasking Simulink demo for RPP.}
2503 \end{center}\end{figure}
2504
2505 \textbf{Description:}
2506
2507 This demo will toggle LEDs on the Hercules Development Kit with
2508 different rate. This is implemented with multiple Simulink tasks, each
2509 running at different rate. In the generated code, these tasks are
2510 called from a singe thread and therefore no task can preempt another
2511 one. See Section \ref{sec-singlet-mode} for more details.
2512
2513 The state of each LED is printed to the Serial Communication Interface
2514 (115200-8-N-1) when toggled.
2515
2516 \begin{center}
2517         \begin{tabular}{lll}
2518     \rowcolor[gray]{0.9}
2519                 LED & pin & rate [s] \\
2520                 1 & NHET1\_25 & 0.3 \\
2521                 2 & NHET1\_05 & 0.5 \\
2522                 3 & NHET1\_00 & 1.0 \\
2523         \end{tabular}
2524         \captionof{table}{LEDs connection and rate}
2525         \label{tab:multirate_st_led_desc}
2526 \end{center}
2527
2528 \subsection{Multi-rate MultiTasking demo}
2529 \label{sec:mult-multi-thre}
2530
2531 \begin{figure}[H]\begin{center}
2532 \noindent
2533 \includegraphics[scale=.45]{images/demo_multirate_mt.png}
2534 \caption{Multi-rate MultiTasking Simulink demo for RPP.}
2535 \label{fig:multitasking-demo}
2536 \end{center}\end{figure}
2537
2538 \textbf{Description:}
2539
2540 This demo toggles LEDs on the Hercules Development Kit with different
2541 rate (different colors in Figure~\ref{fig:multitasking-demo}). This is
2542 implemented with multiple Simulink tasks, each running at different
2543 rate. In the generated code, every subrate task runs in its own
2544 operating system thread. See Section \ref{sec-multit-mode} for more
2545 details.
2546
2547 The state of each LED is also printed to the Serial Communication
2548 Interface (115200-8-N-1) when toggled.
2549
2550 \begin{center}
2551         \begin{tabular}{lll}
2552     \rowcolor[gray]{0.9}
2553                 LED & pin & rate [s] \\
2554                 1 & NHET1\_25 & 0.3 \\
2555                 2 & NHET1\_05 & 0.5 \\
2556                 3 & NHET1\_00 & 1.0 \\
2557         \end{tabular}
2558         \captionof{table}{LEDs connection and rate}
2559         \label{tab:multirate_mt_led_desc}
2560 \end{center}
2561
2562 \subsection{Hydraulics controller initialization demo}
2563 \label{sec:board-init-hydctr}
2564 \begin{figure}[H]
2565   \centering
2566   \includegraphics[scale=0.45]{images/demo_board_init_hydctr.png}
2567   \caption{board\_init\_hydctr demo}
2568   \label{fig:board_init_hydctr}
2569 \end{figure}
2570
2571 \paragraph{Description}
2572
2573 This demo shows how to use the \emph{Board Init} block to initialize
2574 SPI devices on the Hydraulics Controller board. Additionally, it shows
2575 how to use unused SPI pins on the MCU as general-purpose IOs. If both
2576 Board Init and GIO SPI blocks are used together, care must be taken
2577 about the order in which the blocks are initialized. GIO blocks that
2578 represent SPI pins must be initialized \emph{after} the Board Init
2579 block. This can be ensured by giving the GIO blocks higher priority
2580 than the Board Init block.
2581
2582 \chapter{Command line testing tool}
2583 \label{chap-rpp-test-software}
2584 \section{Introduction}
2585 \label{sec-rpp-test-sw-intro}
2586 The \texttt{rpp-test-suite} is a RPP application developed testing and direct
2587 control of the RPP hardware. The test suite implements a command processor,
2588 which is listening for commands and prints some output related to the commands
2589 on the serial interface. The command processor is modular and each peripheral
2590 has its commands in a separate module.
2591
2592 The command processor is implemented in \texttt{$\langle$rpp-test-sw$\rangle$/cmdproc} and commands
2593 modules are implemented in \texttt{$\langle$rpp-test-sw$\rangle$/commands} directory.
2594
2595 The application enables a command processor using the SCI at
2596 \textbf{115200-8-N-1}. When the software starts, the received welcome message
2597 and prompt should look like:
2598
2599
2600 \ifx\tgtId\tgtIdTMSRPP
2601 \begin{verbatim}
2602 Rapid Prototyping Platform v00.01-001
2603 Test Software version v0.2-261-gb6361ca
2604 CTU in Prague 2014
2605 --> 
2606 \end{verbatim}
2607 \else
2608 \begin{verbatim}
2609 Ti HDK \mcuname, FreeRTOS 7.0.2
2610 Test Software version eaton-0.1-beta-8-g91419f5
2611 CTU in Prague 10/2014
2612 --> 
2613 \end{verbatim}
2614 \fi
2615
2616 Type in command help for a complete list of available command, or help command
2617 for a description of concrete command.
2618
2619 \section{Compilation}
2620 \label{sec-rpp-test-sw-compilation}
2621 Before the Testing tool can be compiled, the RPP Library has to be built and the binary file \texttt{rpp-lib.lib} has to be present in the \texttt{\repo/rpp-lib/} directory. Once this requirement is fulfilled, there are two ways how to compile the Testing tool.
2622 \begin{enumerate}
2623         \item Using a Code Composer Studio, which is described in Section \ref{sec-project-installation}. The procedure of downloading the firmware right from the CCS and running it on the hardware is described in Section \ref{sec-running-software-on-hw}.
2624         \item Using a make from a Linux terminal or gmake from a Windows command line. The procedure of how to download and run the binary on the hardware is described in Section \ref{sec-binary-file}.
2625
2626 To build the Testing tool from Linux terminal run:
2627 \begin{lstlisting}[language=bash]
2628 cd <rpp-test-sw>
2629 make
2630 \end{lstlisting}
2631
2632 or from Windows command line:
2633
2634 \begin{lstlisting}[language=bash]
2635 cd <rpp-test-sw>
2636 "C:\ti\ccsv5\utils\bin\"gmake.exe
2637 \end{lstlisting}
2638
2639 On Windows \texttt{gmake.exe} supplied with CCS is used instead of
2640 \texttt{make}.
2641 \end{enumerate}
2642
2643 \section{Commands description}
2644
2645 This section contains the description of the available commands. The
2646 same description is also available in the program itself via the
2647 \texttt{help} command.
2648
2649 \input{rpp-test-sw-cmds.tex}
2650
2651 \chapter{Glossary}
2652
2653 \begin{description}
2654 \item[ADC]
2655   \textit{Analog to Digital Converter.} \newline{}
2656   Hardware circuitry that converts a continuous physical quantity (usually voltage) to a
2657   digital number that represents the quantity's amplitude.
2658
2659 \item[AIN]
2660   \textit{Analog Input.} \newline{}
2661   Mnemonic to refer to or something related to the analog input (ADC) hardware module.
2662
2663 \item[AOUT]
2664   \textit{Analog Output.} \newline{}
2665   Mnemonic to refer to or something related to the analog output (DAC) hardware module.
2666
2667 \item[API] \textit{Application Programming Interface}
2668
2669 \item[CAN]
2670   \textit{Controller Area Network.} \newline{}
2671   The CAN Bus is a vehicle bus standard designed to allow microcontrollers and devices to
2672   communicate with each other within a vehicle without a host computer.
2673   In this project it is also used as mnemonic to refer to or something related to the CAN
2674   hardware module.
2675
2676 \item[CCS] \textit{Code Composer Studio} \\
2677   Eclipse-based IDE provided by Texas Instruments.
2678
2679 \item[CGT]
2680   \textit{Code Generation Tools.} \newline{}
2681   Name given to the tool set produced by Texas Instruments used to compile, link, optimize,
2682   assemble, archive, among others. In this project is normally used as synonym for
2683   ``Texas Instruments ARM compiler and linker."
2684
2685 \item[DAC]
2686   \textit{Digital to Analog Converter.} \newline{}
2687   Hardware circuitry that converts a digital (usually binary) code to an analog signal
2688   (current, voltage, or electric charge).
2689
2690 \item[DIN]
2691   \textit{Digital Input.} \newline{}
2692   Mnemonic to refer to or something related to the digital input hardware module.
2693
2694 \item[ECU]
2695   \textit{Engine Control Unit.} \newline{}
2696   A type of electronic control unit that controls a series of actuators on an internal combustion
2697   engine to ensure the optimum running.
2698
2699 \item[ETH]
2700   \textit{Ethernet.} \newline{}
2701   Mnemonic to refer to or something related to the Ethernet hardware module.
2702
2703 \item[FR]
2704   \textit{FlexRay.} \newline{}
2705   FlexRay is an automotive network communications protocol developed to govern on-board automotive
2706   computing.
2707   In this project it is also used as mnemonic to refer to or something related to the FlexRay
2708   hardware module.
2709
2710 \item[GPIO]
2711   \textit{General Purpose Input/Output.} \newline{}
2712   Generic pin on a chip whose behavior (including whether it is an input or output pin) can be
2713   controlled (programmed) by the user at run time.
2714
2715 \item[HBR]
2716   \textit{H-Bridge.} \newline{}
2717   Mnemonic to refer to or something related to the H-Bridge hardware module. A H-Bridge is
2718   an electronic circuit that enables a voltage to be applied across a load in either direction.
2719
2720 \item[HOUT]
2721   \textit{High-Power Output.} \newline{}
2722   Mnemonic to refer to or something related to the 10A, PWM, with current sensing, high-power
2723   output hardware module.
2724
2725 \item[IDE]
2726   \textit{Integrated Development Environment.} \newline{}
2727   An IDE is a Software application that provides comprehensive facilities to computer programmers
2728   for software development.
2729
2730 \item[LCT]
2731   \textit{Legacy Code Tool.} \newline{}
2732   Matlab tool that allows to generate source code for S-Functions given the descriptor of a C 
2733   function call.
2734
2735 \item[MBD]
2736   \textit{Model-Based Design.} \newline{}
2737   Model-Based Design (MBD) is a mathematical and visual method of addressing problems associated
2738   with designing complex control, signal processing and communication systems. \cite{modelbasedwiki2013}
2739
2740 \item[MEX]
2741   \textit{Matlab Executable.} \newline{}
2742   Type of binary executable that can be called within Matlab. In this document the common term
2743   used is `C MEX S-Function", which means Matlab executable written in C that implements a system
2744   function.
2745
2746 \item[PWM]
2747   \textit{Pulse-width modulation.} \newline{}
2748   Technique for getting analog results with digital means. Digital control is used to create a
2749   square wave, a signal switched between on and off. This on-off pattern can simulate voltages
2750   in between full on and off by changing the portion of the time the signal spends on versus
2751   the time that the signal spends off. The duration of ``on time" is called the pulse width or
2752   \textit{duty cycle}.
2753
2754 \item[RPP] \textit{Rapid Prototyping Platform.} \newline{} Name of the
2755   developed platform, that includes both hardware and software.
2756
2757 \item[SCI]
2758   \textit{Serial Communication Interface.} \newline{}
2759   Serial Interface for communication through hardware's UART using communication standard RS-232.
2760   In this project it is also used as mnemonic to refer to or something related to the Serial
2761   Communication Interface hardware module.
2762
2763 \item[SDC]
2764   \textit{SD-Card.} \newline{}
2765   Mnemonic to refer to or something related to the SD-Card hardware module.
2766
2767 \item[SDR]
2768   \textit{SD-RAM.} \newline{}
2769   Mnemonic to refer to or something related to the SD-RAM hardware module for logging.
2770
2771 \item[TLC]
2772   \textit{Target Language Compiler.} \newline{}
2773   Technology and language used to generate code in Matlab/Simulink.
2774
2775 \item[UART]
2776   \textit{Universal Asynchronous Receiver/Transmitter.} \newline{}
2777   Hardware circuitry that translates data between parallel and serial forms.
2778 \end{description}
2779
2780 \printbibliography
2781
2782 \end{document}
2783
2784 %  LocalWords:  FreeRTOS RPP POSIX microcontroller HalCoGen selftests
2785 %  LocalWords:  MCU UART microcontrollers DAC CCS simulink SPI GPIO
2786 %  LocalWords:  IOs HDK TMDSRM