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