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