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