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