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