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