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