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