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