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