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