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