\documentclass{scrreprt}

\usepackage{graphicx} % images and graphics
\usepackage{paralist} % needed for compact lists
\usepackage[normalem]{ulem} % needed by strike
\usepackage{listings} % required for code blocks
\usepackage[urlcolor=blue,colorlinks=true,hyperfootnotes=false]{hyperref} % links
\usepackage[utf8]{inputenc}  % char encoding
\usepackage[bottom]{footmisc} % footnotes
\usepackage{todonotes}
\usepackage[backend=biber,style=alphabetic,sortcites=true]{biblatex}
\usepackage{tabularx}
\usepackage{textcomp}
\addbibresource{rpp_simulink.bib}

% header
\usepackage[top=2.5cm, bottom=2.5cm, left=2.5cm, right=2.5cm]{geometry}
\usepackage{float} % To fix images position

% Prettify code documentation
\usepackage{color}
\usepackage{colortbl}
% \usepackage[table]{xcolor}

\definecolor{gray97}{gray}{.97}
\definecolor{gray75}{gray}{.75}
\definecolor{gray45}{gray}{.45}
\lstset{ frame=Ltb,
     framerule=0pt,
     aboveskip=0.5cm,
     framextopmargin=3pt,
     framexbottommargin=3pt,
     framexleftmargin=0.4cm,
     framesep=0pt,
     rulesep=.4pt,
     backgroundcolor=\color{gray97},
     rulesepcolor=\color{black},
     %
     stringstyle=\ttfamily,
     showstringspaces = false,
     basicstyle=\small\ttfamily,
     commentstyle=\color{gray45},
     keywordstyle=\bfseries,
     %
     numbers=left,
     numbersep=15pt,
     numberstyle=\tiny,
     numberfirstline = false,
     breaklines=true,
     xleftmargin=20px,
   }

\usepackage{lastpage}
\usepackage{fancyhdr}

% Spacing
\linespread{1.15} % Lines spacing
\setlength{\plitemsep}{0.5\baselineskip} % List items spacing
\definecolor{deepblue}{RGB}{0,0,61}
\definecolor{deepgreen}{RGB}{0,80,0}
\hypersetup{linkcolor=deepblue,citecolor=deepgreen,}

% Table of content depth
\setcounter{tocdepth}{2}

% Landscape pages
\usepackage{lscape}
\usepackage{pdflscape}

% Change page
\usepackage{changepage}

% Font options
% Sans-serif
% \renewcommand{\familydefault}{\sfdefault}
% Better PDF font
\usepackage{lmodern}

% Multiple columns
\usepackage{multicol}
\usepackage{caption}

\newcommand{\repo}{$\langle$repo$\rangle$}
\newcommand{\superscript}[1]{\ensuremath{^{\textrm{\small#1}}}}
\newcommand{\subscript}[1]{\ensuremath{_{\textrm{\small#1}}}}

% Supported targets - to be used with \ifx\tgtId\tgtIdXXX
\def\tgtIdTMSHDK{tms570\_hdk}
\def\tgtIdRMHDK{rm48\_hdk}
\def\tgtIdTMSRPP{tms570\_rpp}
\def\tgtIdHydCtr{tms570\_hydctr}

% Include target specific macros etc.
\input{target_def}

\begin{document}

% Title
\newcommand{\HRule}{\rule{\linewidth}{0.5mm}}

\begin{titlepage}
\begin{center}

% Upper part of the page
\vspace{3cm}

\includegraphics[width=0.35\textwidth]{images/cvut.pdf}\\[1cm]
\textsc{\LARGE Czech Technical University in Prague}\\[1.5cm]


% Document title
\HRule
\vspace{0.4cm}
{\huge \bfseries Simulink code generation target for Texas~Instruments
  \tgname{} platform\par}
\vspace{0.8cm}
{\Large Version for \tgtBoardName{} board\par}
\vspace{0.4cm}
\HRule \\[1.5cm]


% Author
\emph{Authors:}\\
Carlos \textsc{Jenkins}\\
Michal \textsc{Horn}\\
Michal \textsc{Sojka}\\[\baselineskip]

\vfill
\emph{Version:}
\input{version.tex}

% Bottom of the page
{\large \today}

\end{center}
\end{titlepage}
% Title end

\section*{Revision history}

{\small
\noindent\begin{tabularx}{\linewidth}{|l|l|l|X|}
  \rowcolor[gray]{0.9}\hline
  Revision     & Date      & Author(s) & Comments \\ \hline

  0.1 beta & 2014-12-04 & Sojka, Horn & Initial version \\ \hline

  0.2 & 2015-02-16 & Sojka, Horn & Improvements, clarifications,
  cleanup \\ \hline

  0.3 & 2015-03-31 & Sojka, Horn & Added sections
                                   \ref{sec-changing-os}, \ref{sec:adding-new-funct} and
                                   \ref{sec:mult-single-thre}. Minor
                                   updates. \\ \hline

           0.4 & 2015-04-30 & Sojka, Horn & Added support for TMS570 HDK
                                            platform. All RPP software
                                            supports multiple
                                            platforms by
                                            recompilation. \\ \hline

           0.5 beta & 2015-07-03 & Sojka & Updated section \ref{sec:adding-new-funct}.
                                           Added support for Eaton Hydraulics
                                           Controller board (TMS570LS1227).
           \\\hline

           0.5.5 & 2015-08-27 & Sojka, Horn & rpp-lib: HAL merged into DRV
                                              layer, FreeRTOS upgraded to version 8.2.2.
           \\\hline

           0.6 & 2015-09-03 & Sojka & Multi-rate models can be
                                      compiled in multi-tasking mode
                                      (see
                                      sec.~\ref{sec-singlet-multit-modes}
                                      and \ref{sec:mult-multi-thre}).
                                      Added board init block (sec.
                                      \ref{sec:block:sfunction_hydctr_init.c}).
                                      Documented halcogen directory in
                                      sec.~\ref{sec-rpp-lib-subdirectory-content-description}.
           \\\hline

           0.6a & 2015-09-11 & Sojka & Removed reference of
                                       Simulink blocks that are not
                                       part of Eaton distribution.
           \\\hline

           0.7 & 2015-10-05 & Sojka & Simulink GIO blocks
                                      (sec.
                                      \ref{sec:block:sfunction_gio_in.c},
                                      \ref{sec:block:sfunction_gio_out.c})
                                      have different parameters and
                                      support certain SPI5 pins on the
                                      tms570\_hydctr board. Parameters
                                      of old GIO blocks are
                                      automatically transformed to the
                                      new ones.

                                      Added section \ref{sec:board-init-hydctr}: ``Hydraulics controller
                                      initialization demo''.
           \\\hline
\end{tabularx}
}
\tableofcontents

\newpage

\listoffigures

\newpage

\fancypagestyle{plain}{%
\fancyhf{} % clear all header and footer fields
\renewcommand{\footrulewidth}{0.4pt} 
\renewcommand{\headrulewidth}{0pt}
	\fancyfoot[L]{Version \input{version.tex}}
	\fancyfoot[C]{}
	\fancyfoot[R]{Page {\thepage} of \pageref{LastPage}}
}
\renewcommand{\headrulewidth}{0.4pt} 
\renewcommand{\footrulewidth}{0.4pt} 
\pagestyle{fancy} {
	\fancyhead[R]{\includegraphics[width=1cm]{images/cvut.pdf}}
	\fancyhead[C]{}
	\fancyhead[L]{\nouppercase \leftmark}
	\fancyfoot[L]{Version \input{version.tex}}
	\fancyfoot[C]{}
	\fancyfoot[R]{Page {\thepage} of \pageref{LastPage}}
}
\headheight=26pt
%\addtolength{\parskip}{\baselineskip} % Paragraph spacing

\chapter{Introduction}
\label{chap-introduction}

This text documents software part of Rapid Prototyping Platform (RPP)
project for Texas Instruments \tgname{} safety microcontroller
developed by Czech Technical University in Prague (CTU). The software
consists of code generation target for Simulink Embedded Coder, a
low-level run-time C library and a tool for interactive testing of
hardware and software functionality.

Originally, the RPP project was created for a custom TMS570-based
board. Subsequently, it was ported to other board such as RM48 HDK and
TMS570 HDK development kits under a contract from Eaton Corporation.

The document contains step-by-step instructions for installation of
development tools, information about Simulink Coder configuration,
describes how to create new models as well as how to download the
resulting firmware to the hardware. It can also be used as a reference
for the testing tool, Matlab Simulink blocks and RPP Matlab Simulink
Code generator. Additionally, an overall description of the used
hardware platform and the architecture of included software is
provided.

\section{Background}
\label{sec-background}

In this document, the term \emph{Rapid Prototyping Platform} denotes a
hardware board and accompanying software. The hardware board is
\tgtBoardName{} based on ARM Cortex R4 safety microcontroller
\mcuname{}. This MCU contains several protective mechanisms (two cores
in lockstep, error correction mechanisms for SRAM and Flash memory,
voltage monitoring, etc.) to fulfill the requirements for safety
critical applications. See~\cite{\tgrefman} for details.

In order to develop non-trivial applications for the RPP, an operating
system is necessary. The RPP is based on FreeRTOS -- a simple
opensource real-time operating system kernel. The FreeRTOS provides an
API for creating and managing and scheduling multiple tasks, memory
manager, semaphores, queues, mutexes, timers and a few of other
features which can be used in the applications.
See~\cite{usingthefreertos2009} for more details.

Even with the operating system it is quite hard and non-intuitive to
manipulate the hardware directly. That is the point when abstraction
comes into the play. The RPP software is made of several layers
implementing, from the bottom to the top, low-level device drivers,
hardware abstraction for common functionality on different hardware
and an API which is easy to use in applications. The operating system
and the basic software layers, can be compiled as a library and easily
used in any project. More details about the library can be found in
Chapter~\ref{chap-c-support-library} and in~\cite{michalhorn2013}.

Because human beings make mistakes and in safety critical applications
any mistake can cause damage, loos of money or in the worst case even
death of other people, the area for making mistakes has to be as small
as possible. An approach called Model-based development
\cite{modelbasedwiki2013} has been introduced to reduce the
probability of making mistakes. In model-based development, the
applications are designed at higher level from models and the
functionality of the models can be simulated in a computer before the
final application/hardware is finished. This allows to discover
potential errors earlier in the development process.

One commonly used tool-chain for model-based development is
Matlab/Simulink. In Simulink the application is developed as a model
made of interconnected blocks. Every block implements some
functionality. For example one block reads a value from an
analog-to-digital converter and provides the value as an input to
another block. This block can implement some clever algorithm and its
output is passed to another block, which sends the computed value as a
message over CAN bus to some other MCU. Such a model can be simulated
and tested even before the real hardware is available by replacing the
input and output blocks with simulated ones. Once the hardware is
ready, C code is automatically generated from the model by a Simulink
Coder. The code is then compiled by the MCU compatible compiler and
downloaded to the MCU Flash memory on the device. Because every block
and code generated from the block has to pass a series of tests during
their development, the area for making mistakes during the application
development has been significantly reduced and developers can focus on
the application instead of the hardware and control software
implementation. More information about code generation can be found in
Chapter \ref{chap-simulink-coder-target}. For information about Matlab
Simulink, Embedded Coder and Simulink Coder, refer to
\cite{embeddedcoderreference2013, ebmeddedcoderusersguide2013,
  simulinkcoderreference2013, targetlanguagecompiler2013,
  simulinkcoderusersguide2013, simulinkdevelopingsfunctions2013}.

\section{Hardware description}
\label{sec-hardware-description}

\input{hwdesc}

\section{Software architecture}
\label{sec-software-architecture}

The core of the RPP software is the so called RPP Library. This
library is conceptualy structured into 5 layers, depicted in
Figure~\ref{fig-layers}. The architecture design was driven by the
following guidelines:

\begin{compactitem}
	\item Top-down dependency only. No lower layer depends on anything from
upper layers.
% 	\item 1-1 layer dependency only. The top layer depends
% exclusively on the bottom layer, not on any lower level layer (except for a
% couple of exceptions).
\item Each layer should provide a unified layer interface
  (\texttt{rpp.h}, \texttt{drv.h}, \texttt{sys.h} and
  \texttt{os.h}), so that higher layers depend on the lower layer's interface
  and not on individual elements from that layer.
\end{compactitem}

\begin{figure}
\begin{center}
\noindent
\includegraphics[width=250px]{images/layers.pdf}
\caption{The RPP library layers.}
\label{fig-layers}
\end{center}
\end{figure}

As a consequence of this division the source code files and interface files are
placed in private directories like \texttt{drv/din.h}. With this organization
user applications only needs to include the top layer interface files (for
example \texttt{rpp/rpp.h}) to be able to use the selected library API.

The rest of the section provides basic description of each layer.

\subsection{Operating System layer}
\label{sec-operating-system-layer}
This is an interchangeable operating system (OS) layer containing the
FreeRTOS source files. The system can be easily replaced by another
version. For example it is possible to compile the RPP library for
Linux (using POSIX version of the FreeRTOS), which can be desirable
for some testing. The source files can be found in the
\texttt{$\langle$rpp\_lib$\rangle$/os} folder.

The following FreeRTOS versions are distributed:
\begin{description}
\item[6.0.4\_posix] POSIX version, usable for compilation of the
  library for Linux system.
\item[8.2.2] Currently used FreeRTOS version. This is the version
  downloaded from FreeRTOS.org with changes in directory structure.
  Namely, include files have added the \emph{os/} prefix and platform
  dependent code (portable) for \tgname{} is copied to the same
  directory as platform independent code.
\end{description}

\subsection{System Layer} 
\label{sec-system-layer}
This layer contains system files with data types definitions, clock definitions,
interrupts mapping, MCU start-up sequence, MCU selftests, and other low level
code for controlling some of the MCU peripherals. The source files can be found
in \texttt{$\langle$rpp\_lib$\rangle$/rpp/src/sys}, the header files can
be found in \texttt{$\langle$rpp\_lib$\rangle$/rpp/include/sys}
folder.

Large part of this layer was generated by the HalCoGen tool (see
Section~\ref{sec-halcogen}). Some files were then modified by hand.

\subsection{Drivers layer} 
\label{sec-drivers-layer}
The Drivers layer contains code for controlling the RPP peripherals.
Typically, it contains code implementing IRQ handling, software
queues, management threads, etc. The layer benefits from the lower
layer thus it is not too low level, but still there are some
peripherals like ADC, which need some special procedure for
initialization and running, that would not be very intuitive for the
typical end user.

The source files can be found in
\texttt{$\langle$rpp\_lib$\rangle$/rpp/src/drv} and the header files can
be found in \texttt{$\langle$rpp\_lib$\rangle$/rpp/include/drv} folder.

\subsection{RPP Layer}
\label{sec-rpp-layer} 
The RPP Layer is the highest layer of the library. It provides an easy
to use set of functions for every peripheral and requires only basic
knowledge about them. For example, to use the ADC, the user can just
call \texttt{rpp\_adc\_init()} function and it calls a sequence of
Driver layer functions to initialize the hardware and software.

The source files can be found in
\texttt{$\langle$rpp\_lib$\rangle$/rpp/src/rpp} and the header files can
be found in \texttt{$\langle$rpp\_lib$\rangle$/rpp/include/rpp}.

\section{Document structure}
\label{sec-document-structure}
The structure of this document is as follows:
Chapter~\ref{chap-getting-started} gets you started using the RPP
software. Chapter~\ref{chap-c-support-library} describes the RPP
library. Chapter~\ref{chap-simulink-coder-target} covers the Simulink
code generation target and finally
Chapter~\ref{chap-rpp-test-software} documents a tool for interactive
testing of the RPP functionality.

\chapter{Getting started}
\label{chap-getting-started}

\section{Software requirements}
\label{sec-software-requirements}
The RPP software stack can be used on Windows and Linux platforms. The
following subsections mention the recommended versions of the required
software tools/packages.

\subsection{Linux environment} 
\label{sec-linux-environment}
\begin{itemize}
	\item Debian based 64b Linux distribution (Debian 7.0 or Ubuntu 14.4 for
example).
	\item Kernel version 3.11.0-12.
	\item GCC version 4.8.1
	\item GtkTerm 0.99.7-rc1
	\item TI Code Composer Studio 5.5.0.00077
	\item Matlab 2013b 64b with Embedded Coder
	\item HalCoGen 4.00 (optional)
	\item Uncrustify 0.59 (optional, see Section \ref{sec-compilation})
	\item Doxygen 1.8.4 (optional, see Section \ref{sec-compiling-api-documentation})
    \item Git 1.7.10.4 (optional)
\end{itemize}

\subsection{Windows environment}
\label{sec-windows-environment}
\begin{itemize}
	\item Windows 7 Enterprise 64b Service Pack 1.
	\item Microsoft Windows SDK v7.1
	\item Bray Terminal v1.9b
	\item TI Code Composer Studio 5.5.0.00077
	\item Matlab 2013b 64b with Embedded Coder
	\item HalCoGen 4.00 (optional)
	\item Doxygen 1.8.4 (optional, see Section \ref{sec-compiling-api-documentation}) 
	\item Uncrustify 0.59 (optional, see Section \ref{sec-compilation})
    \item Git 1.9.4.msysgit.2 (optional)
\end{itemize}

\section{Software tools}
\label{sec-software-and-tools}

This section covers tool which are needed or recommended for work with
the RPP project.

\subsection{TI Code Composer Studio}
\label{sec-ti-ccs}
Code Composer Studio (CCS) is the official Integrated Development Environment
(IDE) for developing applications for Texas Instruments embedded processors. CCS
is multiplatform software based on
Eclipse open source IDE.

CCS includes Texas Instruments Code Generation Tools (CGT)
\cite{armoptimizingccppcompiler2012, armassemblylanguagetools2012}
(compiler, linker, etc). Simulink code generation target requires the
CGT to be available in the system, and thus, even if no library
development will be done or the IDE is not going to be used CCS is
still required.

You can find documentation for CGT compiler in \cite{armoptimizingccppcompiler2012} and
for CGT archiver in \cite{armassemblylanguagetools2012}.

\subsubsection{Installation on Linux} 
\label{sec-installation-on-linux}
Download CCS for Linux from:\\
\url{http://processors.wiki.ti.com/index.php/Category:Code\_Composer\_Studio\_v5}

Once downloaded, add executable permission to the installation file
and launch the installation by executing it. Installation must be done
by the root user in order to install a driver set.

\lstset{language=bash}
\begin{lstlisting}
chmod +x ccs_setup_5.5.0.00077.bin
sudo ./ccs_setup_5.5.0.00077.bin
\end{lstlisting}

After installation the application can be executed with:

\lstset{language=bash}
\begin{lstlisting}
cd <ccs>/ccsv5/eclipse/
./ccstudio
\end{lstlisting}

The first launch on 64bits systems might fail. This can happen because CCS5 is
a 32 bit application and thus requires 32 bit libraries. They can be
installed by:

\lstset{language=bash}
\begin{lstlisting}
sudo apt-get install libgtk2.0-0:i386 libxtst6:i386
\end{lstlisting}

If the application crashes with a segmentation fault edit file:

\lstset{language=bash}
\begin{lstlisting}
nano <ccs>/ccsv5/eclipse/plugins/com.ti.ccstudio.branding_<version>/plugin_customization.ini
\end{lstlisting}

And change key \texttt{org.eclipse.ui/showIntro} to \texttt{false}.

\subsubsection{Installation on Windows}
\label{sec-installation-on-windows}
Installation for Windows is more straightforward than the installation
procedure for Linux. Download CCS for Windows from:\\
\url{http://processors.wiki.ti.com/index.php/Category:Code\_Composer\_Studio\_v5}

Once downloaded run the ccs\_setup\_5.5.0.00077.exe and install the CCS.

\subsubsection{First launch} 
\label{sec-first-launch}
If no other licence is available, choose ``FREE License -- for use
with XDS100 JTAG Emulators'' from the licensing options. Code download
for the board uses the XDS100 hardware.

\subsection{Matlab/Simulink}
\label{sec-matlab-simulink}
Matlab Simulink is a set of tools, runtime environment and development
environment for Model--Based \cite{modelbasedwiki2013} applications development,
simulations and code generation for target platforms.  Supported Matlab Simulink
version is R2013b for 64 bits Linux and Windows. A licence for an Embedded Coder is
necessary to be able to generate code from Simulink models, containing RPP blocks.

\subsection{HalCoGen}
\label{sec-halcogen}
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.

The tool is available for Windows at 
\begin{quotation}
\url{http://www.ti.com/tool/halcogen}
\end{quotation}

The HalCoGen has been used in early development stage of the RPP
project to generate the base code for some of the peripheral. The
trend is to not to use the HalCoGen any more, because the generated
code is not reliable enough for safety critical applications. Anyway it is
sometimes helpful to use it as a reference.

The HalCoGen is distributed for Windows only, but can be run on Linux
under Wine (tested with Wine version 1.6.2).

\subsection{GtkTerm and Bray Terminal}
\label{sec-gtkterm-bray-terminal}
Most of the interaction with the board is done through a RS-232 serial
connection. The terminal software used for communication is called GtkTerm for
Linux and Bray terminal for Windows.

To install GtkTerm execute:

\lstset{language=bash}
\begin{lstlisting}
sudo apt-get install gtkterm
\end{lstlisting}

The Bray Terminal does not require any installation and the executable file is
available at\\
\url{https://sites.google.com/site/terminalbpp/}

\subsection{C Compiler}
\label{sec-c-compiler}
A C language compiler has to be available on the development system to be able to
compile Matlab Simulink blocks S-functions.

For Linux a GCC 4.8.1 compiler is recommended and can be installed with a
command

\lstset{language=bash}
\begin{lstlisting}
sudo apt-get install gcc
\end{lstlisting}

For Windows, the C/C++ compiler is a part of Windows SDK, which is available from\\
\url{http://www.microsoft.com/en-us/download/details.aspx?id=8279}

\section{Project installation}
\label{sec-project-installation}
The RPP software is distributed in three packages and a standalone pdf
file containing this documentation. Every package is named like
\emph{$\langle$package\_name$\rangle$-version.zip}. The three packages
are:

\begin{description}
\item[rpp-simulink] Contains the source code of Matlab Simulink
  blocks, demo models and scripts for downloading the generated
  firmware to the target board from Matlab/Simulink. Details can be
  found in Chapter \ref{chap-simulink-coder-target}.

  The package also contains the binary of the RPP Library and all its
  headers and other files necessary for building and downloading
  Simulink models.
\item[rpp-test-sw] Contains an application for interactive testing and
  control of the \tgtBoardName{} board over the serial interface. Details can be
  found in Chapter~\ref{chap-rpp-test-software}.

  The package also contains the binary of the RPP Library and all
  headers and other files necessary for building and downloading the
  application.
\item[rpp-lib] Contains the source code of the RPP library, described
  in Chapter \ref{chap-c-support-library}. If you want to make any
  changes in the drivers or the RPP API, this library has to be
  compiled and linked with applications in the other two packages.
  Library compilation is described in Section \ref{sec-compilation}.
\end{description}

The following sections describe how to start working with individual
packages.

\ifx\tgtId\tgtIdTMSRPP
\subsection{Getting sources from git repository}
\begin{verbatim}
git clone --recursive git@rtime.felk.cvut.cz:jenkicar/rpp-simulink
\end{verbatim}
If you get release packages, follow the instructions in the next sections.
\fi 

\subsection{rpp-simulink}
\label{sec-rpp-simulink-installation}
This section describes how to install the rpp-simulink project, which
is needed to try the demo models or to build your own models that use
the RPP blocks.

\begin{enumerate}
\item Unzip the \texttt{rpp-simulink-version.zip} file.
\item Follow the procedure  from Section
  \ref{sec-configuration-simulink-for-rpp} for configuring Matlab
  Simulink for the RPP project.
\item Follow the procedure from Section \ref{sec-crating-new-model}
  for instructions about creating your own model which will use the
  RPP Simulink blocks or follow the instructions in
  Section~\ref{sec-running-model-on-hw} for downloading the firmware to the RPP hardware.
\end{enumerate}

\subsection{rpp-test-sw}
\label{sec-test-sw-installation}
This section describes how to install and run the application that
allows you to interactively control the RPP hardware. This can be
useful, for example, to test your modifications of the RPP library.

\begin{enumerate}
	\item Unzip the \texttt{rpp-test-sw-version.zip} file.
	\item Open the Code Composer Studio (see Section \ref{sec-ti-ccs}).
	\item Import the \texttt{rpp-test-sw} project as described in
          Section \ref{sec-openning-of-existing-project}.
	\item Right click on the \texttt{rpp-test-sw} project in the
      \textsc{Project Explorer} and select \textsc{Build Project}.
	\item Follow the instructions in
      Section~\ref{sec-running-software-on-hw} to download, debug and
      run the software on the target hardware.
\end{enumerate}

\subsection{rpp-lib}
\label{sec-rpp-lib-installation}

This section describes how to open the rpp-lib project in Code
Composer Studio and how to use the resulting static library in an
application. This is only necessary if you need to modify the library
for some reason.

\begin{enumerate}
	\item Unzip the \texttt{rpp-lib-version.zip} file.
	\item Open the Code Composer Studio (see Section \ref{sec-ti-ccs}).
	\item Import the rpp-lib project from directory
          \texttt{rpp-lib-XXX/build/\tgtId} as described in
          Section~\ref{sec-openning-of-existing-project}.
        \item Compile the static library by selecting \textsc{Project
            $\rightarrow$ Build Project} (see Section
          \ref{sec-compilation} for more information). The compiled
          library \texttt{rpp-lib.lib} and file
          \texttt{Makefile.config} will appear in the
          \texttt{rpp-lib-XXX} directory.
    \item Either copy the compiled library and the content of the
      \texttt{rpp/include} directory to the application, where you
      want to use it or use the library in place, as described in
      Section~\ref{sec:creating-new-project}.
      \begin{itemize}
      \item In the rpp-simulink application the library is located in
        the \texttt{rpp/lib} folder.
      \item In the rpp-test-sw application the library is located in
        the \texttt{rpp-lib} folder.
      \end{itemize}
\end{enumerate}

\section{Code Composer Studio usage}
\label{sec-code-composerpstudio-usage}

\subsection{Opening an existing project}
\label{sec-openning-of-existing-project}
The procedure for opening a project is similar to opening a project in
the standard Eclipse IDE.

\begin{enumerate}
	\item Launch Code Composer Studio
	\item Select \textsc{File$\rightarrow$Import}
	\item In the dialog window select \textsc{Code Composer
        Studio$\rightarrow$Existing CCS Eclipse project} as an import
      source (see Figure \ref{fig-import-project}).
	\item In the next dialog window click on \textsc{Browse} button
      and find the root directory of the project.
    \item Select the requested project in the \textsc{Discovered
        project} section so that the result looks like in Figure
      \ref{fig-select-project}.
    \item Click the \textsc{Finish} button.
\end{enumerate}

\begin{figure}[H]\begin{center}
	\includegraphics[width=350px]{images/import_project.png}
	\caption{Import project dialog}
	\label{fig-import-project}
\end{center}\end{figure}

\begin{figure}[H]\begin{center}
	\includegraphics[width=350px]{images/select_project.png}
	\caption{Select project dialog}
	\label{fig-select-project}
\end{center}\end{figure}

\newpage
\subsection{Creating new project}
\label{sec:creating-new-project}
Follow these steps to create an application for \tgname{} MCU compiled with
CGT.

\begin{compactenum}
\item Create a new empty CCS project. Select \mcuname{} device, XDS100v2
  connection and set Linker command file to
  \texttt{rpp-lib/build/\tgtId/\ldscriptname}.

  \noindent\includegraphics[scale=0.45]{images/base_1.png}

\item In \textsc{Project Explorer}, create normal folders
  named \texttt{include} and \texttt{src}.

\item If you use Git version control system, add \texttt{.gitignore}
  file with the following content to the root of that project:
  \lstset{language=}
\begin{lstlisting}
Debug
Release
.settings/*
\end{lstlisting}

  \newpage
\item In project \textsc{Properties}, add new variable of type
  \texttt{Directory} named \texttt{RPP\_LIB\_ROOT} and set it to the
  rpp-lib directory
  root.

  \noindent\includegraphics[scale=.45]{images/base_2.png}

\item Configure the compiler \#include search path to contain
  project's \texttt{include} directory, \penalty-100
  \texttt{\$\{RPP\_LIB\_ROOT\}/os/8.2.2/include} and
  \texttt{\$\{RPP\_LIB\_ROOT\}/rpp/include}, in that order.

  \includegraphics[scale=.43]{images/base_5.png}

  \newpage
\item Add \texttt{\$\{RPP\_LIB\_ROOT\}/rpp-lib.lib} to the list of
  linked libraries before the runtime support library
  (\texttt{\tgtRtlib}).

  \noindent\includegraphics[scale=.45]{images/base_3.png}

\item Configure the compiler to allow GCC extensions.

  \noindent\includegraphics[scale=.45]{images/base_6.png}

\newpage
\item Create \texttt{main.c} file with the following content:
\begin{lstlisting}[language=C]
#include <rpp/rpp.h>

int main(void)
{
	rpp_init();
	rpp_sci_printf("Hello world\n");
	vTaskStartScheduler();
	return 0; /* not reached */
}

void vApplicationMallocFailedHook()
{}
void vApplicationStackOverflowHook()
{}
\end{lstlisting}

\item Compile the application by e.g. \textsc{Project $\rightarrow$
    Build All}.
\item Select \textsc{Run} $\rightarrow$ \textsc{Debug}. The
  application will be downloaded to the processor and run. A
  breakpoint is automatically placed at \texttt{main()} entry. To
  continue executing the application select \textsc{Run} $\rightarrow$
  \textsc{Resume}.
\item If your application fails to run with a \texttt{\_dabort} interrupt, check
that the linker script selected in step 1 is not excluded from the build.
You can do this by right clicking the \texttt{\ldscriptname}  file
in the \textsc{Project Explorer} and unchecking the \textsc{Exclude from build}
item. The Code Composer Studio sometimes automaticaly excludes this file from
the build process when creating a new project.

% \item If not already created for another project, create new target
%   configuration. Select \textsc{Windows $\rightarrow$ Show View
%     $\rightarrow$ Target Configurations}. In the shown window, click
%   on \textsc{New Target Configuration} icon and configure XDS100v2
%   connection and \mcuname{} device as shown below. Click \textsc{Save},
%   connect your board and click \textsc{Test Connection}.

%   \medskip
%   \includegraphics[width=\linewidth]{images/target_conf.png}

% \newpage
\item Optionally, you can change debugger configuration by selecting
  \textsc{Run $\rightarrow$ Debug Configurations}. In the
  \textsc{Target} tab, you can configure not to break at \texttt{main}
  or not to erase the whole flash, but necessary sectors only (see the
  figure below).

  \includegraphics[width=\linewidth]{images/debug_conf_flash.png}


\end{compactenum}

%% Comment this out for Eaton
% \subsubsection{Steps to configure new POSIX application:}
% Such an application can be used to test certain FreeRTOS features on
% Linux and can be compiled with a native GCC compiler.

% \begin{compactenum}
% 	\item Create a new managed C project that uses Linux GCC toolchain.
% 	\item Create a source folder \texttt{src}. Link all files from original
% CCS application to this folder.
% 	\item Create a normal folder \texttt{include}. Create a folder
% \texttt{rpp} inside of it.  
% 	\item Add common \texttt{.gitignore} to the root of that project:
% \lstset{language=}
% \begin{lstlisting}
% Debug
% Release
% .settings/*
% \end{lstlisting}
% 	\item Add new variable \texttt{RPP\_LIB\_ROOT} and point to this
% repository branch root.\newline{}
% \noindent\includegraphics[width=\linewidth]{images/base_posix_1.png}
% 	\item Configure compiler to include local includes, CCS application
% includes, OS includes for POSIX and RPP includes, in that order.\newline{}
% \noindent\includegraphics[width=\linewidth]{images/base_posix_2.png}
% \newpage
% 	\item Add \texttt{rpp} and \texttt{pthread} to linker libraries and add
% \texttt{RPP\_LIB\_ROOT} to the library search path.\newline{}
% \noindent\includegraphics[width=\linewidth]{images/base_posix_3.png}
% \end{compactenum}

\subsubsection{Content of the application}

\begin{enumerate}
\item Include RPP library header file. 
  \lstset{language=c++}
\begin{lstlisting}
#include "rpp/rpp.h"
\end{lstlisting}

  If you want to reduce the size of the final application, you can
  include only the headers of the needed modules. In that case, you
  need to include two additional headers: \texttt{base.h} and, in case
  when SCI is used for printing, \texttt{rpp/sci.h}.
\begin{lstlisting}
#include "rpp/hbr.h" /* We want to use H-bridge */
#include <base.h>	/* This is the necessary base header file of the rpp library. */
#include "rpp/sci.h" /* This is needed, because we use rpp_sci_printf in following examples. */
\end{lstlisting}

\newpage
\item Create one or as many FreeRTOS task function definitions as
  required. Those tasks can use functions from the RPP library. Beware
  that currently not all RPP functions are
  reentrant\footnote{Determining which functions are not reentrant and
    marking them as such (or making them reentrant) is planned as
    future work.}. \lstset{language=c++}
\begin{lstlisting}
void my_task(void* p)
{
    static const portTickType freq_ticks = 1000 / portTICK_RATE_MS;
    portTickType last_wake_time = xTaskGetTickCount();
    while (TRUE) {
        /* Wait until next step */
        vTaskDelayUntil(&last_wake_time, freq_ticks);
        rpp_sci_printf((const char*)"Hello RPP.\r\n");
    }
}
\end{lstlisting}

\item Create the main function that will:
 \begin{itemize}
	\item Initialize the RPP board. If you have included only selected
modules in step 1, initialize only those modules by calling their init
functions, for
example \texttt{rpp\_hbr\_init\(\)}.
	\item Spawn the tasks the application requires. Refer to FreeRTOS API
for details.
\item Start the FreeRTOS Scheduler. Refer to FreeRTOS API for details
  \cite{freertosapi}.
	\item Handle error when the FreeRTOS scheduler cannot be started.

\lstset{language=c++}
\begin{lstlisting}
void main(void)
{
    /* In case whole library is included: */
        /* Initialize RPP board */
        rpp_init();
    /* In case only selected modules are included: */
        /* Initialize HBR */
        rpp_hbr_init();
        /* Initialize sci for printf */
        rpp_sci_init();
        /* Enable interrups */
        _enable_IRQ();

    /* Spawn tasks */
    if (xTaskCreate(my_task, (const signed char*)"my_task",
            512, NULL, 0, NULL) != pdPASS) {
        #ifdef DEBUG
        rpp_sci_printf((const char*)
            "ERROR: Cannot spawn control task.\r\n"
        );
        #endif
        while (TRUE) { ; }
    }

    /* Start the FreeRTOS Scheduler */
    vTaskStartScheduler();

    /* Catch scheduler start error */
    #ifdef DEBUG
    rpp_sci_printf((const char*)
            "ERROR: Problem allocating memory for idle task.\r\n"
        );
    #endif
    while (TRUE) { ; }
}
\end{lstlisting}

 \end{itemize}
\item Create hook functions for FreeRTOS:
 \begin{itemize}
 \item \texttt{vApplicationMallocFailedHook()} allows to catch memory allocation
errors.
\item \texttt{vApplicationStackOverflowHook()} allows to catch stack
  overflow errors.

\lstset{language=c++}
\begin{lstlisting}
#if configUSE_MALLOC_FAILED_HOOK == 1
/**
 * FreeRTOS malloc() failed hook.
 */
void vApplicationMallocFailedHook(void) {
    #ifdef DEBUG
    rpp_sci_printf((const char*)
            "ERROR: manual memory allocation failed.\r\n"
        );
    #endif
}
#endif


#if configCHECK_FOR_STACK_OVERFLOW > 0
/**
 * FreeRTOS stack overflow hook.
 */
void vApplicationStackOverflowHook(xTaskHandle xTask,
                                   signed portCHAR *pcTaskName) {
    #ifdef DEBUG
    rpp_sci_printf((const char*)
            "ERROR: Stack overflow : \"%s\".\r\n", pcTaskName
        );
    #endif
}
#endif
\end{lstlisting}

\newpage
 \end{itemize}
\end{enumerate}


\subsection{Downloading and running the software}
\label{sec-running-software-on-hw}
\subsubsection{Code Composer Studio Project}
\label{sec-ccs-run-project}
When an application is distributed as a CCS project, you have to open the
project in the CCS as described in the Section
\ref{sec-openning-of-existing-project}. Once the project is opened and built, it
can be easily downloaded to the target hardware with the following procedure:

\begin{enumerate}
\ifx\tgtId\tgtIdTMSRPP
	\item Connect the Texas Instruments XDS100v2 USB emulator to the JTAG port.
	\item Connect a USB cable to the XDS100v2 USB emulator and the development computer.
\else
	\item Connect the USB cable to the \tgtBoardName{} board.
\fi
	\item Plug in the power supply.  
	\item In the Code Composer Studio click on the
\textsc{Run$\rightarrow$Debug}. The project will  be optionally built and
the download process will start. The Code Composer Studio will switch into the debug
perspective, when the download is finished.
	\item Run the program by clicking on the \textsc{Run} button, with the
green arrow.  
\end{enumerate}

\subsubsection{Binary File}
\label{sec-binary-file}
If the application is distributed as a binary file, without source code and CCS
project files, you can download and run just the binary file by creating a new
empty CCS project and configuring the debug session according to the following
procedure:

\begin{enumerate}
	\item In Code Composer Studio click on
\textsc{File$\rightarrow$New$\rightarrow$CCS Project}.  
	\item In the dialog window, type in a project name, for example
myBinaryLoad, Select \textsc{Device
variant} (ARM, Cortex R, \mcuname, Texas Instruments XDS100v2 USB Emulator)
and select project template to \textsc{Empty Project}. The filled dialog should
look like in Figure~\ref{fig-new-empty-project}
\item Click the \textsc{Finish} button and a new empty project will
  be created.
\item In the \textsc{Project Explorer} right-click on the project and
  select \textsc{Debug as$\rightarrow$Debug configurations}.
	\item Click  \textsc{New launch configuration} button
	\item Rename the New\_configuration to, for example, myConfiguration.
	\item Select configuration target file by clicking the \textsc{File
System} button, finding and selecting the \texttt{rpp-lib-XXX/build/\tgtId/\tgconfigfilename} file. The result
should look like in Figure~\ref{fig-debug-conf-main-diag}.  
\item In the \textsc{program} pane select the binary file you want to
  download to the board. Click on the \textsc{File System} button,
  find and select the binary file. Try, for example
  \texttt{rpp-test-sw.out}. The result should look like in
  Figure~\ref{fig-debug-conf-program-diag}.
\item You may also tune the target configuration as described in
  Section \ref{sec-target-configuration}.
\item Finish the configuration by clicking the \textsc{Apply} button
  and download the code by clicking the \textsc{Debug} button. You can
  later invoke the download also from the
  \textsc{Run$\rightarrow$Debug} CCS menu. It is not necessary to
  create more Debug configurations and CCS empty projects as you can
  easily change the binary file in the Debug configuration to load a
  different binary file.
\end{enumerate}

\begin{figure}[H]\begin{center}
	\includegraphics[scale=.45]{images/new_empty_project.png}
	\caption{New empty project dialog}
	\label{fig-new-empty-project}
\end{center}\end{figure}

\begin{figure}[H]\begin{center}
	\includegraphics[scale=.45]{images/debug_configuration_main.png}
	\caption{Debug Configuration Main dialog}
	\label{fig-debug-conf-main-diag}
\end{center}\end{figure}

\subsection{Target configuration}
\label{sec-target-configuration}
Default target configuration erases the whole Flash memory, before
downloading the code. This takes long time and in most cases it is
not necessary. You may disable this feature by the following procedure:
\begin{enumerate}
	\item Right click on the project name in the \textsc{Project Browser}
	\item Select \textsc{Debug as$\rightarrow$Debug Configurations}
	\item In the dialog window select \textsc{Target} pane.
	\item In the \textsc{Flash Settings}, \textsc{Erase Options} select
\textsc{Necessary sectors only}.
	\item Save the configuration by clicking the \textsc{Apply} button
and close the dialog.
\end{enumerate}

\begin{figure}[H]\begin{center}
	\includegraphics[scale=.45]{images/debug_configuration_program.png}
	\caption{Configuration Program dialog}
	\label{fig-debug-conf-program-diag}
\end{center}\end{figure}

\section{Matlab Simulink usage}
\label{sec-matlab-simulink-usage}
This section describes the basics of working with the RPP code
generation target for Simulink. For a more detailed description of the
code generation target refer to
Chapter~\ref{chap-simulink-coder-target}.

\subsection{Configuring Simulink for RPP}
\label{sec-configuration-simulink-for-rpp}
Before any work or experiments with the RPP blocks and models, the RPP
target has to be configured to be able to find the ARM cross-compiler,
native C compiler and some other necessary files. Also the S-Functions
of the blocks have to be compiled by the mex tool.
\begin{enumerate}
\item Download and install Code Composer Studio CCS (see
  Section~\ref{sec-ti-ccs}).
\item Install a C compiler. On Windows follow Section~\ref{sec-c-compiler}.
\item On Windows you have to tell the \texttt{mex} which C compiler to
  use. In the Matlab command window run the \texttt{mex -setup}
  command and select the native C compiler.

\begin{lstlisting}[basicstyle=\tt\footnotesize]
>> mex -setup

Welcome to mex -setup.  This utility will help you set up
a default compiler.  For a list of supported compilers, see
http://www.mathworks.com/support/compilers/R2013b/win64.html

Please choose your compiler for building MEX-files:

Would you like mex to locate installed compilers [y]/n? y

Select a compiler:
[1] Microsoft Software Development Kit (SDK) 7.1 in c:\Program Files (x86)\Microsoft Visual Studio 10.0

[0] None

Compiler: 1

Please verify your choices:

Compiler: Microsoft Software Development Kit (SDK) 7.1
Location: c:\Program Files (x86)\Microsoft Visual Studio 10.0

Are these correct [y]/n? y

***************************************************************************
  Warning: MEX-files generated using Microsoft Windows Software Development
           Kit (SDK) require that Microsoft Visual Studio 2010 run-time
           libraries be available on the computer they are run on.
           If you plan to redistribute your MEX-files to other MATLAB
           users, be sure that they have the run-time libraries.
***************************************************************************


Trying to update options file: C:\Users\Michal\AppData\Roaming\MathWorks\MATLAB\R2013b\mexopts.bat
From template:              C:\PROGRA~1\MATLAB\R2013b\bin\win64\mexopts\mssdk71opts.bat

Done . . .

**************************************************************************
  Warning: The MATLAB C and Fortran API has changed to support MATLAB
           variables with more than 2^32-1 elements.  In the near future
           you will be required to update your code to utilize the new
           API. You can find more information about this at:
           http://www.mathworks.com/help/matlab/matlab_external/upgrading-mex-files-to-use-64-bit-api.html
           Building with the -largeArrayDims option enables the new API.
**************************************************************************
\end{lstlisting}

\item Configure the RPP code generation target:

Open Matlab and in the command window run:

\lstset{language=Matlab}
\begin{lstlisting}
cd <rpp-simulink>/rpp/rpp/
rpp_setup
\end{lstlisting}

This will launch the RPP setup script. This script will ask the user to provide
the path to the CCS compiler root directory (the directory where \texttt{armcl}
binary is located), normally:

\begin{verbatim}
<ccs>/tools/compiler/arm_5.X.X/
\end{verbatim}

Then Matlab path will be updated and block S-Functions will be built.

\item Create new model or load a demo:

  Demos are located in \texttt{\repo/rpp/demos}. Creation of new
  models is described in Section~\ref{sec-crating-new-model} below.
\end{enumerate}


\subsection{Working with demo models}
\label{sec-openning-demo-models}
The demo models are available from the directory
\texttt{\repo/rpp/demos}. To access the demo models for reference or
for downloading to the RPP board open them in Matlab. Use either the
GUI or the following commands:

\begin{lstlisting}[language=Matlab]
cd <rpp-simulink>/rpp/demos
open cantransmit.slx
\end{lstlisting}

The same procedure can be used to open any other models. To build the
demo select \textsc{Code$\rightarrow$C/C++ Code $\rightarrow$Build
  Model}. This will generate the C code and build the binary firmware
for the RPP board. To run the model on the target hardware see
Section~\ref{sec-running-model-on-hw}.

\subsection{Creating new model}
\label{sec-crating-new-model}
\begin{enumerate}
	\item Create a model by clicking \textsc{New$\rightarrow$Simulink Model}.
	\item Open the configuration dialog by clicking \textsc{Simulation$\rightarrow$Model Configuration Parameters}.
	\item The new Simulink model needs to be configured in the following way:
	\begin{compactitem}
	\item Solver (Figure \ref{fig-solver}):
	 \begin{compactitem}
	 \item Solver type: \emph{Fixed-step}
     \item Solver: \emph{discrete}
     \item Fixed-step size: \emph{Sampling period in seconds. Minimum
         is 0.001.}
	 \item Tasking mode -- choose between the following:
	  \begin{compactitem}
	  \item \textit{Auto} selects SingleTasking modes for
            single-rate model or MultiTasking mode for multi-rate
            models. See Section \ref{sec-singlet-multit-modes}
	  \item \textit{SingleTasking} selects SingleTasking mode. See
            Section \ref{sec-singlet-mode} for details.
	  \item \textit{MultiTasking} select MultiTasking mode. In
            this mode \textit{Higher priority value indicates higher
              task priority} should be checked. See Section
            \ref{sec-multit-mode} for details.
	  \end{compactitem}

	   \begin{figure}
		 \centering
		 \includegraphics[scale=.45]{images/simulink_solver.png}
		 \caption{Solver settings}
	 	 \label{fig-solver}
	\end{figure}
	 \end{compactitem}
% 	\item Diagnostics $\rightarrow$ Sample Time (Figure~\ref{fig-sample-time-settings}):
% 	 \begin{compactitem}
% 	 \item Disable warning ``Source block specifies -1 sampling
%        time''. It's ok for the source blocks to run once per tick.
% 	   \begin{figure}
% 		 \centering
% 		 \includegraphics[scale=.45]{images/simulink_diagnostics.png}
% 		 \caption{Sample Time settings}
% 	 	 \label{fig-sample-time-settings}
% 	\end{figure}
% 	\end{compactitem}
	\item Code generation (Figure~\ref{fig-code-gen-settings}):
	 \begin{compactitem}
	 \item Set ``System target file'' to \texttt{rpp.tlc}.
	   \begin{figure}
		 \centering
		 \includegraphics[scale=.45]{images/simulink_code.png}
		 \caption{Code Generation settings}
	 	 \label{fig-code-gen-settings}
	\end{figure}
	\end{compactitem}
\end{compactitem}
\item Once the model is configured, you can open the Library Browser
  (\textsc{View $\rightarrow$ Library Browser}) and add the necessary
  blocks to create the model. The RPP-specific blocks are located in
  the RPP Block Library.
	\item From Matlab command window change the current directory to where
you want your generated code to appear, e.g.:
\begin{lstlisting}[language=Matlab]
cd /tmp/my-code
\end{lstlisting}
The code will be generated in a subdirectory named
\texttt{<model>\_rpp}, where \texttt{model} is the name of the
Simulink model.
	\item Generate the code by choosing \textsc{Code $\rightarrow$ C/C++
Code  $\rightarrow$ Build Model}.
\end{enumerate}

To run the model on the \tgtBoardName{} board continue with Section
\ref{sec-running-model-on-hw}.

\subsection{Running models on the RPP board}
\label{sec-running-model-on-hw}
To run the model on the \tgtBoardName{} hardware you have to enable the download
feature and build the model by following this procedure:
 \begin{enumerate}
 \item Open the model you want to run (see
   Section~\ref{sec-openning-demo-models} for example with demo
   models).
 \item Click on \textsc{Simulation$\rightarrow$Model Configuration
     Parameters}.
 \item In the \textsc{Code Generation$\rightarrow$RPP Options} pane
   check the \textsc{Download compiled binary to RPP} checkbox. Click
   the \textsc{OK} button
 \item Connect the target hardware to the computer (see Section
   \ref{sec-ccs-run-project}) and build the model by \textsc{Code
     $\rightarrow$ C/C++ Code $\rightarrow$ Build Model}. If the build
   succeeds, the download process will start automatically and once
   the downloading is finished, the application will run immediately.
\end{enumerate}

%%\subsubsection{Using OpenOCD for downloading}
%%\label{sec:using-open-downl}
%%
%%On Linux systems, it is possible to use an alternative download
%%mechanism based on the OpenOCD tool. This results in much shorter
%%download times. Using OpenOCD is enabled by checking ``Use OpenOCD to
%%download the compiled binary'' checkbox. For more information about
%%the OpenOCD configuration refer to our
%%wiki\footnote{\url{http://rtime.felk.cvut.cz/hw/index.php/TMS570LS3137\#OpenOCD_setup_and_Flashing}}.
%%
%%Note: You should close any ongoing Code Composer Studio debug sessions
%%before downloading the generated code to the RPP board. Otherwise the
%%download fails.

\section{Configuring serial interface}
\label{sec-configuration-serial-interface}
The main mean for communication with the RPP board is the serial line.
Each application may define its own serial line settings, but the
following settings are the default:

\begin{itemize}
	\item Baudrate: 115200
	\item Parity: none
	\item Bits: 8
	\item Stopbits: 1
	\item Flow control: none
\end{itemize}

Use GtkTerm on Linux or Bray Terminal on Windows for accessing the
serial interface. On \tgtBoardName{} board, the serial line is tunneled over
the USB.
% TODO: Conditional compilation
 % See Section \ref{sec-hardware-description} for reference about
% the position of the serial interface connector on the RPP board.

\section{Bug reporting}
\label{sec-bug-reporting}

Please report any problems to CTU's bug tracking system at
\url{https://redmine.felk.cvut.cz/projects/eaton-rm48}. New users have
to register in the system and notify Michal Sojka about their
registration via $\langle{}sojkam1@fel.cvut.cz\rangle{}$ email
address.

\chapter{C Support Library}
\label{chap-c-support-library}

This chapter describes the implementation of the C support library
(RPP Library), which is used both for Simulink code generation target
and command line testing tool.

\section{Introduction}
\label{sec-description}
The RPP C Support Library (also called RPP library) defines the API for
working with the board. It includes drivers and the operating system.
The library is
designed from the board user perspective and exposes a simplified high-level API
to handle the board's peripheral modules in a safe manner. The library is
compiled as static library named \texttt{rpp-lib.lib} and can be found in
\texttt{\repo/rpp/lib}.

The RPP library can be used in any project, where the RPP hardware
support is required and it is also used in two applications --
Simulink Coder Target, described in Chapter
\ref{chap-simulink-coder-target}, and the command line testing tool,
described in Chapter \ref{chap-rpp-test-software}.

For details about the library architecture, refer to Section~\ref{sec-software-architecture}.

\section{API development guidelines}
\label{sec-api-development-guidlines}

The following are the development guidelines used for developing the RPP API:

\begin{compactitem}
	\item User documentation should be placed in header files, not in source
code, and should be Doxygen formatted using autobrief. Documentation for each
function present is mandatory and must mention whether the function is
thread safe or not.
	\item Function declarations in the headers files is for public functions
only. Do not declare local/static/private functions in the header.
	\item Documentation in source code files should be non-doxygen formatted
and intended for developers, not users. Documentation here is optional and at
the discretion of the developer.
	\item Always use standard data types for IO when possible. Use custom
structs as very last resort.  \item Use prefix based functions names to avoid
clash. The prefix is of the form \texttt{$\langle$layer$\rangle$\_$\langle$module$\rangle$\_}, for example
\texttt{rpp\_din\_update()} for the update function of the DIN module in the RPP
Layer.  
	\item Be very careful about symbol export. Because it is used as a
static library the modules should not export any symbol that is not intended to
be used (function) or \texttt{extern}'ed (variable) from application. As a rule
of thumb declare all global variables as static. 
	\item Only the RPP Layer symbols are available to user applications. All
information related to lower layers is hidden for the application. This is
accomplished by the inclusion of the rpp.h or rpp\_\{mnemonic\}.h file on the
implementations files only and never on the interface files. Never expose any
other layer to the application or to the whole system below the RPP layer. In
other words, never \texttt{\#include "foo/bar.h"} in any RPP Layer header
file.
\end{compactitem}

\section{Coding style}
\label{sec-coding-style}
In order to keep the code as clean as possible, unified coding style
should be followed by any contributor to the code. The used coding
style is based on the default configuration of Code Composer Studio
editor. Most notable rule is that the Tab character is 4 spaces.

The RPP library project is prepared for use of a tool named
Uncrustify. The Uncrustify tool checks the code and fixes those lines
that do not match the coding style. However, keep in mind that the
program is not perfect and sometimes it can modify code where the
suggested coding style has been followed. This does not causes
problems as long as the contributor follows the committing procedure
described in next paragraph.

When contributing to the code, the contributor should learn the
current coding style from existing code. When a new feature is
implemented and committed to the local repository, the following
commands should be called in Linux terminal:

\begin{lstlisting}[language=bash]
make uncrustify
git diff
\end{lstlisting}
The first line command corrects many found coding style violations and
the second command displays them. If the user agree with the
modification, he/she should amend the last commit, for example by:
\begin{lstlisting}[language=bash]
git add --update
git commit --amend
\end{lstlisting}

\section{Subdirectory content description}
\label{sec-rpp-lib-subdirectory-content-description}

The following files and directories are present in the library source
code package:

\begin{description}
\item[rpp-lib.lib] Compiled RPP library.

  The library is needed for Simulink models and other ARM/\tgname{}
  applications. It is placed here by the Makefile, when the library is
  compiled.

\item[apps/] Various applications related to the RPP library.

  This include the CCS studio project for generating of the static
  library and a test suite. The test suit in this directory has
  nothing common with the test suite described later in
  Chapter~\ref{chap-rpp-test-software} and those two suits are going
  to be merged in the future. Also other Hello World applications are
  included as a reference about how to create an \tgname{}
  application.
\item[build] The library can be compiled for multiple targets. Each
  supported target has a subdirectory here, which stores configuration
  of how to compile the library and applications for different target.
  Each subdirectory contains a CCS project and Makefiles to build the
  library for the particular target.
\item[build/$\langle$target$\rangle$/Makefile.config] Configuration
  for the particular target. This includes compiler and linker
  switches etc.
\item[build/$\langle$target$\rangle$/*.cmd]
CGT Linker command file.

This file is used by all applications that need to tun on the RPP
board, including the Simulink models and test suite. It includes
instructions for the CGT Linker about target memory layout and where
to place various code sections.

\item[halcogen/] HalCoGen project files for the supported boards and
  scripts for automated conversion of HalCoGen-generated files for use
  in rpp-lib.

  Note: This is work in progress. Currently only ``pinmux'' files for
  tms570\_hydctr board were produced by the scripts here.

\item[os/] OS layers directory. See
  Section~\ref{sec-operating-system-layer} for more information about
  currently available operating system versions and
  Section~\ref{sec-changing-os} for information how to replace the
  operating system.
\item[rpp/] Main directory for the RPP library.
\item[rpp/doc/] RPP Library API
  documentation.
\item[rpp/include/\{layer\} and rpp/src/\{layer\}] Interface files and
  implementations files for given \texttt{\{layer\}}. See
  Section~\ref{sec-software-architecture} for details on the RPP
  Layer.
\item[rpp/include/rpp/rpp.h] Main library header file.

  To use this library with all its modules, just include this file
  only. Also, before using any library function call the
  \texttt{rpp\_init()} function for hardware initialization.
\item[rpp/include/rpp/rpp\_\{mnemonic\}.h] Header file for
  \texttt{\{mnemonic\}} module.

  These files includes function definitions, pin definitions, etc,
  specific to \{mnemonic\} module. See also
  Section~\ref{sec-api-development-guidlines}.

  If you want to use only a subset of library functions and make the
  resulting binary smaller, you may include only selected
  \texttt{rpp\_\{mnemonic\}.h} header files and call the specific
  \texttt{rpp\_\{mnemonic\}\_init} functions, instead of the
  \texttt{rpp.h} and \texttt{rpp\_init} function.
	\item[rpp/src/rpp/rpp\_\{mnemonic\}.c] Module implementation.

      Implementation of \texttt{rpp\_\{mnemonic\}.h}'s functions on
      top of the DRV library.
	\item[rpp/src/rpp/rpp.c] Implementation of library-wide functions.
\end{description}

\section{Compilation}
\label{sec-compilation}

To compile the library open the Code Composer studio project
\texttt{rpp-lib} from appropriate \texttt{build/<target>} directory
(see Section~\ref{sec-openning-of-existing-project}) and build the
project (\textsc{Project $\rightarrow$ Build Project}). If the build
process is successful, the \texttt{rpp-lib.lib} and
\texttt{Makefile.config} files will appear in the library root
directory.

It is also possible to compile the library using the included
\texttt{Makefile}. From the Linux command line run:
\begin{lstlisting}[language=bash]
cd <library-root>/build/<target>/Debug   #or Release
make
\end{lstlisting}
Note that this only works if Code Composer Studio is installed in
\texttt{/opt/ti} directory. Otherwise, you have to set
\texttt{CCS\_UTILS\_DIR} variable.

On Windows command line run:
\begin{lstlisting}[language=bash]
cd <library-root>\build\<target>\Debug
set CCS_UTILS_DIR=C:\ti\ccsv5\utils
C:\ti\ccsv5\utils\bin\gmake.exe lib
\end{lstlisting}

You have to use \texttt{gmake.exe} instead of \texttt{make} and it is
necessary to set variable \texttt{CCS\_UTILS\_DIR} manually. You can
also edit \texttt{\repo/build/Makefile.rules.arm} and set the variable
there.

Note that the Makefile still requires the Code Composer Studio (ARM
compiler) to be installed because of the CGT.

\section{Compiling applications using the RPP library}
\label{sec:comp-appl-using}

The relevant aspects for compiling and linking an application using
the RPP library are summarized below.

% \subsection{ARM target (RPP board)}
% \label{sec:arm-target-rpp}

The detailed instructions are presented in
Section~\ref{sec:creating-new-project}. Here we briefly repeat the
main steps.

	\begin{compactitem}
    \item Configure include search path to contain the directory of
      used FreeRTOS version, e.g.
      \texttt{\repo/os/8.2.2/include}. See Section
      \ref{sec-software-architecture}.
    \item Include \texttt{rpp/rpp.h} header file or just the needed
      peripheral specific header files such as \texttt{rpp/can.h}.
    \item Add library \texttt{rpp-lib.lib} to the linker libraries.
      The RPP library must be placed before Texas Instruments
      support library \tgtRtlib.
    \item Use the provided linker command file
      \texttt{\ldscriptname}.
	\end{compactitem}

% \subsection{POSIX target}
% \label{sec:posix-target}

% 	\begin{compactitem}
%     \item Include headers files of the OS for Simulation. At the time
%       of this writing the OS is POSIX FreeRTOS 6.0.4.
%     \item Include header files for the RPP library or for modules you
%       want to use (rpp\_can.h for CAN module for example).
%     \item Add library \texttt{librpp.a} to the linker libraries.
%     \item Add \texttt{pthread} to the linker libraries.
% 	\end{compactitem}

\section{Compiling API documentation}
\label{sec-compiling-api-documentation}
The documentation of the RPP layer is formatted using Doxygen
documentation generator. This allows to generate a high quality API
reference. To generate the API reference run in a Linux terminal:

\lstset{language=bash}
\begin{lstlisting}
cd <repo>/rpp/doc/api
make
xdg-open html/index.html
\end{lstlisting}

The files under \texttt{\repo/rpp/doc/api/content} are used for the API
reference generation are their name is self-explanatory:

\begin{verbatim}
blocks_map.html
blocks.png
cvut.png
footer.html
main_page.dox
\end{verbatim}

\section{Changing operating system}
\label{sec-changing-os}
The C Support Library contains by default the FreeRTOS operating
system in version 8.2.2. This section describes what is necessary to
change in the library and other packages in order to replace the
operating system.

\subsection{Operating system code and API}

The source and header files of the current operating system (OS) are
stored in directory \texttt{\repo/rpp/lib/os}. The files of the new
operating system should also be placed in this directory.

To make the methods and resources of the new OS available to the C Support
Library, modify the \texttt{\repo/rpp/lib/rpp/include/base.h} file to include
the operating system header files.

Current implementation for FreeRTOS includes a header file
\texttt{\repo/rpp/lib/os/\-8.2.2\-include/os.h}, which
contains all necessary declarations and definitions for the FreeRTOS.
We suggest to provide a similar header file for your operating system as
well.

In order to compile another operating system into the library, it is
necessary to modify \texttt{\repo/rpp/lib/Makefile.var} file, which
contains a list of files that are compiled into the library. All lines
starting with \texttt{os/} should be updated. 

\subsection{Device drivers}
Drivers for SCI and ADC depend on the FreeRTOS features. These
features need to be replaced by equivalent features of the new
operating system. Those files should be modified:
\begin{description}
\item[\repo/rpp/lib/rpp/include/sys/ti\_drv\_sci.h] Defines a data
  structure, referring to FreeRTOS queue and semaphore.
\item[\repo/rpp/lib/rpp/src/sys/ti\_drv\_sci.c] Uses FreeRTOS queues
  and semaphores.
\item[\repo/rpp/lib/rpp/include/drv/sci.h] Declaration of
  \texttt{drv\_sci\_receive()} contains \texttt{portTick\-Type}. We
  suggest replacing this with OS independent type, e.g. number of
  milliseconds to wait, with $-1$ meaning infinite waiting time.
\item[\repo/rpp/lib/rpp/src/drv/sci.c] Uses the following FreeRTOS
  specific features: semaphores, queues, data types
  (\texttt{portBASE\_TYPE}) and
  critical sections (\texttt{taskENTER\_CRITICAL} and
  \texttt{task\-EXIT\_CRITICAL}). Inside FreeRTOS critical sections,
  task preemption is disabled. The same should be ensured by the other
  operating system or the driver should be rewritten to use other
  synchronization primitives.
\item[\repo/rpp/lib/rpp/src/drv/adc.c] Uses FreeRTOS semaphores.
\end{description}

\subsection{System start}
The initialization of the MCU and the system is in the
\texttt{\repo/rpp/lib/rpp/src/sys/sys\_startup.c} file. If the new
operating system needs to handle interrupts generated by the Real-Time
Interrupt module, the pointer to the Interrupt Service Routine (ISR)
\texttt{vPreemptiveTick} has to be replaced.

\subsection{Simulink template for main function}

When the operating system in the library is replaced, the users of the
library must be changed as well. In case of Simulink code generation
target, described in Chapter~\ref{chap-simulink-coder-target}, the
template for generation of the \texttt{ert\_main.c} file, containing
the main function, has to be modified to use proper functions for task
creation, task timing and semaphores. The template is stored in
\texttt{\repo/rpp/rpp/rpp\_mrmain.tlc} file.

\chapter{Simulink Coder Target}
\label{chap-simulink-coder-target}

The Simulink Coder Target allows to convert Simulink models to C code,
compile it and download to the board.

\section{Introduction}
\label{sec-introduction}

The Simulink RPP Target provides support for C source code generation from Simulink models and
compilation of that code on top of the RPP library and the FreeRTOS operating system. This target
uses Texas Instruments ARM compiler (\texttt{armcl}) included in the Code Generation Tools distributed with
Code Composer Studio, and thus it depends on it for proper functioning.

This target also provides support for automatic download of the compiled binary to the RPP
board.

\begin{figure}\begin{center}
\noindent
\includegraphics[scale=.45]{images/tlc_process.png}
\caption{TLC code generation process. \cite[p. 1-6]{targetlanguagecompiler2013}}
\end{center}\end{figure}

\section{Features and limitations}
\label{sec-features}

\begin{itemize}
\item Sampling frequencies up to 1\,kHz.
\item Multi-rate models can be executed in a single or multiple OS
  tasks. Multi-tasking mode allows high-rate tasks to preempt low-rate
  tasks. See Section \ref{sec-singlet-multit-modes} for more details.
\item No External mode support yet. We work on it.
\item Custom compiler options, available via OPTS variable in
  \emph{Make command} at \emph{Code Generation} tab (see Figure
  \ref{fig-code-gen-settings}). For example \texttt{make\_rtw
    OPTS="-O0 -g"}.
\end{itemize}

\section{RPP Options pane}
\label{sec-rpp-target-options}

The RPP Target includes the following configuration options, all of them
configurable per model under  \textsc{Code Generation} \noindent$\rightarrow$
\textsc{RPP Options}:

\begin{itemize}
\item \textbf{C system stack size}: this parameter is passed directly
  to the linker for the allocation of the stack. Note that this stack
  is used only for initializing the application and FreeRTOS. Once
  everything is initialized, another stack is used by the generated
  code. See below. Default value is 4096.

\item \textbf{C system heap size}:
  \label{sec-rpp-target-options-heap-size} this parameter is passed
  directly to the linker for the allocation of the heap. Currently,
  the heap is not used, but will be used by the external mode in the future.
Note that FreeRTOS uses its own heap whose size is independent of this
parameter. 
\item \textbf{Model step task stack size}: this parameter will be
passed to the \texttt{xTaskCreate()} that
  creates the task for the model to run. In a Simulink model there are always two tasks:
 \begin{itemize}
 \item The worker task. This task is the one that executes the model
   step. This task requires enough stack memory to execute the step.
   If your model does not run, it might be caused by too small stack.
   The memory needed for the stack depends on the size and structure
   of the model.
 \item The control task. This task controls when the worker task should execute and controls overruns.

 \end{itemize}
\item \textbf{Download compiled binary to RPP}: if set, this option will download the generated binary to
  the board after the model is successfully built. Note that this option is unaware of the option
  \textit{Generate code only} in the \textit{Code Generation} options panel, so it will try to download even if
  only source code has been generated, failing graciously or uploading an old binary laying around
  in the build directory. This option calls the \texttt{rpp\_download.m} script, which is in turn a
  wrapper on the \texttt{loadti.sh}, \texttt{loadti.bat} and \texttt{loadopenocd.sh} script. More information on the \texttt{loadti.sh}
  script can be found in:
\begin{verbatim}
<ccs>/ccs_base/scripting/examples/loadti/readme.txt
http://processors.wiki.ti.com/index.php/Loadti
\end{verbatim}

  The \texttt{loadti.sh} and \texttt{loadti.bat} script will close after the
download of the generated program, leaving the loaded program running.

  The \texttt{loadopenocd.sh} script will close after the download of the
generated program as well, but the program will be stopped.  In order to run
the loaded program a manual reset of the board is required.

\item \textbf{Download compiled binary to SDRAM}: This feature is not yet
implemented for the simulink target.

\item \textbf{Use OpenOCD to download the compiled binary}: This feature is not yet
implemented for the \mcuname{} simulink target.
% TODO Not true - use conditional compilation here.

\item \textbf{Print model metadata to SCI at start}: if set this option will
print a message to the Serial Communication Interface when the model start
execution on the board. This is very helpful to identify the model running on
the board. The message is in the form: 

\begin{verbatim}
`model_name' - generated_date (TLC tlc_version)
\end{verbatim}

  For example:
\begin{verbatim}
`hbridge_analog_control' - Wed Jun 19 14:10:44 2013 (TLC 8.3 (Jul 20 2012))
\end{verbatim}
\end{itemize}

\section{Subdirectory  content description}
\label{sec-simulink-subdirectory-content-description}
This section describes the directories of the Simulink Coder. If you are
interested in particular file, refer the description at the beginning of the
file.

\begin{description}
	\item[doc/] Contains the sources of the documentation, you are now
reading.  
	\item[refs/] Contains third party references, which license allows the
distribution.
\item[rpp/blocks] Contains the Simulink blocks specific to the
  \tgtBoardName{} board and their sources (.c and .tlc files). When an
  user calls \texttt{rpp\_setup.m}, these files are processed and
  Simulink block library \texttt{rpp\_lib.slx} is created.
	\item[rpp/blocks/tlc\_c]Contains the templates for C code generation from the
Matlab Simulink model.
	\item[rpp/demos] Contains demo models, which purpose is to serve as a
reference for the usage and for testing.  
	\item[rpp/lib] Contains the C Support Library. See Chapter
\ref{chap-c-support-library}.  \item[rpp/loadopenocd] Contains download scripts
for Linux support of the OpenOCD, for code downloading to the target.
	\item[rpp/loadti] Contains download scripts for Linux and Windows
support for code downloading to the target, using Texas Instruments CCS code
downloader.  
	\item[rpp/rpp] Contains set of support script for the Code Generator.
\end{description}

\section{Tasking modes}
\label{sec-singlet-multit-modes}

This section describes two different modes (single- and multi-tasking)
of how generated code of multi-rate models can be executed. Tasking
mode can be selected for every model in the configuration dialog as
described in Section \ref{sec-crating-new-model}.

For single-rate models, the mode selection does not matter. For
multi-rate models, the mode selection becomes important as it may
influence certain system properties such as safety or performance.

\subsection{SingleTasking mode}
\label{sec-singlet-mode}
In this mode all Simulink tasks, defined by their sampling rate, run
in a single operating system task (thread). This means that the period
of the highest rate Simulink task cannot be greater than the
worst-case execution time of all Simulink tasks together. On the other
hand, using this mode reduces the risk of failures caused by task
synchronization errors, e.g. race conditions, deadlocks.

\subsection{MultiTasking mode}
\label{sec-multit-mode}

In this mode every Simulink task, defined by its sampling rate, runs
in its own operating system task (thread). Thread priorities are
assigned based on task rates in such a way that tasks with higher
rates can preempt tasks with lower rates. This means that the period
of the fastest sampling rate is limited only by the execution time of
this task and not of all the tasks in the system.

This mode offers more efficient use of system resources (CPU) but
there is a possibility of failures caused by task synchronization
errors.

\section{Block Library Overview}
\label{sec-block-library-overview}
The Simulink Block Library is a set of blocks that allows Simulink models to use
board IO and communication peripherals. The available blocks are summarized in
Table~\ref{tab:block-lib-status} and more detailed description is
given in Section~\ref{sec-blocks-description}.

\begin{table}
\begin{center}\begin{tabular}{|lp{5cm}lll|}
\hline
\textbf{Category} & \textbf{Name} & \textbf{Status} & \textbf{Mnemonic} & \textbf{Header} \\
\hline
\input{block_table.tex}
\hline
\end{tabular}\end{center}

  \caption{Block library overview}
  \label{tab:block-lib-status}
\end{table}

\label{sec-blocks-implementation}
All of the blocks are implemented as manually created C Mex S-Function . In this section the 
approach taken is briefly explained.

\subsection{C MEX S-Functions}
\label{sec-c-mex-functions}
 \begin{compactitem}
 \item C : Implemented in C language. Other options are Fortran and Matlab language itself.
 \item MEX: Matlab Executable. They are compiled by Matlab - C compiler wrapper called MEX.
 \item S-Function: System Function, as opposed to standard functions, or user functions.
 \end{compactitem}

A C MEX S-Function is a structured C file that implements some mandatory and
optional  callbacks for a specification of a number of inputs, outputs, data
types, parameters, rate, validity checking, etc.  A complete list of callbacks
can be found in:
	\begin{quotation}
\htmladdnormallink{http://www.mathworks.com/help/simulink/create-cc-s-functions.html}{http://www.mathworks.com/help/simulink/create-cc-s-functions.html}
\end{quotation}

The way a C MEX S-Function participates in a Simulink simulation is shown on the
diagram \ref{fig-sfunctions-process}:

\begin{figure}[H]\begin{center}
\noindent
\includegraphics[scale=.45]{images/sfunctions_process.png}
\caption{Simulation cycle of a S-Function. \cite[p. 57]{simulinkdevelopingsfunctions2013}}
\label{fig-sfunctions-process}
\end{center}\end{figure}

In general, the S-Function can perform calculations, inputs and outputs for simulation. Because 
the RPP blocks are for hardware peripherals control and IO the blocks are 
implemented as pure sink or pure source, the S-Function is just a descriptor of
the block and does not perform any calculation and does not provide any input or
output for simulations. 

The implementation of the S-Functions in the RPP project has following layout:

\begin{itemize}
  \item Define S-Function name \texttt{S\_FUNCTION\_NAME}.
  \item Include header file \texttt{header.c}, which in connection with
\texttt{trailer.c} creates a miniframework for writing S-Functions.  
  \item In \texttt{mdlInitializeSizes} define:
  \begin{itemize}
	\item Number of \textit{dialog} parameter.
	\item Number of input ports.
 	\begin{compactitem}
		\item Data type of each input port.
	\end{compactitem}
	\item Number of output ports.
	\begin{compactitem}
		\item Data type of each output port.
	\end{compactitem}
	\item Standard options for driver blocks.
  \end{itemize}
  \item In \texttt{mdlCheckParameters}:
  \begin{itemize}
	\item Check data type of each parameter.
	\item Check range, if applicable, of each parameter.
  \end{itemize}
  \item In \texttt{mdlSetWorkWidths}:
  \begin{compactitem}
	\item Map \textit{dialog} parameter to \textit{runtime} parameters.
 	\begin{itemize}
		\item Data type of each \textit{runtime} parameter.
	\end{itemize}
  \end{compactitem}
  \item Define symbols for unused functions.
  \item Include trailer file \texttt{trailer.c}.
\end{itemize}

The C MEX S-Function implemented can be compiled with the following command:

\lstset{language=bash}
\begin{lstlisting}
<matlabroot>/bin/mex sfunction_{mnemonic}.c
\end{lstlisting}

As noted the standard is to always prefix S-Function with \texttt{sfunction\_}
and use lower case mnemonic of the block.

Also a script called \texttt{compile\_blocks.m} is included. The script that
allows all \texttt{sfunctions\_*.c} to be fed to the \texttt{mex} compiler so
all S-Functions are compiled at once. To use this script, in Matlab do:

\lstset{language=Matlab}
\begin{lstlisting}
cd <repo>/rpp/blocks/
compile_blocks()
\end{lstlisting}

\subsection{Target Language Compiler files}
\label{sec-target-language-compiler-files}

In order to generate code for each one of the S-Functions, every S-Function implements a TLC file
for \textit{inlining} the S-Function on the generated code. The TLC files describe how to 
generate code for a specific C MEX S-Function block. They are programmed using TLC own language and 
include C code within TLC instructions, just like LaTeX files include normal text in between LaTeX 
macros.

The standard for a TLC file is to be located under the \texttt{tlc\_c} subfolder from where the 
S-Function is located and to use the very exact file name as the S-Function but with the \texttt{.tlc}
extension: \texttt{sfunction\_foo.c} \noindent$\rightarrow$ \texttt{tlc\_c/sfunction\_foo.tlc}

The TLC files implemented for this project use 3 hook functions in particular (other are available, 
see TLC reference documentation):
\begin{itemize}
\item \texttt{BlockTypeSetup}: \newline{}
  BlockTypeSetup executes once per block type before code generation begins.
  This function can be used to include elements required by this block type, like includes or
  definitions.
\item \texttt{Start}: \newline{}
  Code here will be placed in the \texttt{void
$\langle$modelname$\rangle$\_initialize(void)}. Code placed here will execute
only once.
\item \texttt{Outputs}: \newline{}
  Code here will be placed in the \texttt{void
$\langle$modelname$\rangle$\_step(void)} function. Should be used to get the
inputs of a block and/or to set the outputs of that block.
\end{itemize}

The general layout of the TLC files implemented for this project is:
\begin{itemize}
\item In \texttt{BlockTypeSetup}: \newline{}
  Call common function \texttt{\%$<$RppCommonBlockTypeSetup(block, system)$>$} that will include the 
  \texttt{rpp/rpp\i\_mnemonic.h} header file (can be called multiple times but header is included only once).
\item \texttt{Start}: \newline{}
  Call setup routines from RPP Layer for the specific block type, like HBR enable, DIN pin setup, 
  DAC value initialization, SCI baud rate setup, among others.
\item \texttt{Outputs}: \newline{}
  Call common IO routines from RPP Layer, like DIN read, DAC set, etc. Success of this functions
  is checked and in case of failure error is reported to the block using ErrFlag.
\end{itemize}

C code generated from a Simulink model is placed on a file called
\texttt{$\langle$modelname$\rangle$.c} along with other support files in a
folder called \texttt{$\langle$modelname$\rangle$\_$\langle$target$\rangle$/}.
For example, the source code generated for model \texttt{foobar} will be placed
in current Matlab directory \texttt{foobar\_rpp/foobar.c}.

The file \texttt{$\langle$modelname$\rangle$.c} has 3 main functions:
\begin{compactitem}
\item \texttt{void $\langle$modelname$\rangle$\_step(void)}: \newline{}
  This function recalculates all the outputs of the blocks and should be called once per step. This
  is the main working function.
\item \texttt{void $\langle$modelname$\rangle$\_initialize(void)}: \newline{}
  This function is called only once before the first step is issued. Default values for blocks IOs
  should be placed here.
\item \texttt{void $\langle$modelname$\rangle$\_terminate(void)}: \newline{}
  This function is called when terminating the model. This should be used to free memory or revert 
  other operations made in the initialization function. With current implementation this function
  should never be called unless an error is detected and in most models it is empty.
\end{compactitem}

\section{Block reference}
\label{sec-blocks-description}

This section describes each one of the Simulink blocks present in the Simulink
RPP block library, shown in Figure \ref{fig-block-library}.

\begin{figure}[h]
  \begin{center}
    \includegraphics[width=\textwidth]{images/block_library.png}
  \end{center}
\caption{Simulink RPP Block Library.}
\label{fig-block-library}
\end{figure}
\clearpage
\input{block_desc.tex}

\newpage
\section{Compilation}
\label{sec-simulink-compilation}
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:
\lstset{language=Matlab}
\begin{lstlisting}
cd <rpp-simulink>/rpp/blocks
compile_blocks
\end{lstlisting}

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:

\begin{enumerate}
	\item Open Matlab and run those commands in the Matlab command line:
\lstset{language=Matlab}
\begin{lstlisting}
cd <rpp-simulink>/rpp/demos
rpp_build_demos
\end{lstlisting}
	\item Run those commands in a Linux terminal:
\begin{lstlisting}[language=bash]
cd <rpp-simulink>/rpp/demos
make
\end{lstlisting}

or Windows command line:

\begin{lstlisting}[language=bash]
cd <rpp-simulink>\rpp\demos
"C:\ti\ccsv5\utils\bin\"gmake.exe lib
\end{lstlisting}

Both commands will create a directory for each compiled demo, which will contain the generated C code and binary file with the firmware. To download the firmware to the board and run it, see Section \ref{sec-running-software-on-hw}.
\end{enumerate}

 \section{Adding new functionality}
\label{sec:adding-new-funct}
This section describes how to create new Simulink blocks and how to add them to the RPP
blocks library. The new block creation process consists of several steps:
\begin{enumerate}
	\item Addition of the new functionality to the RPP C support library.
	\item Definition of the block interface as a C MEX S-Function
          (Section~\ref{sec:block-definition-c})
	\item Compilation of the block definition to MEX file
          (Section~\ref{sec:c-mex-file})
	\item Creation of the code generator template (TLC) file
          (Section~\ref{sec:tlc-file-creation}).
	\item Creation of an S-Function block in the RPP block library
          and ``connecting'' this block with the C MEX and TLC files
          (Section~\ref{sec:creation-an-s})
        \item Optional: Creation of the mask for the new block. The mask
          specifies graphical representation of the block as well as
          the content of the block parameters dialog box.
\end{enumerate}
The following subsections demonstrate the procedure on an example of a simple user defined block.

\subsection{Block interface definition in a C MEX S-function}
\label{sec:block-definition-c}
In order to use a custom block in the Simulink model, Simulink must know
a certain number of block attributes, such as the number and type of
block inputs, outputs and parameters. These attributes are specified
by a set of functions in a C file. This C file gets compiled by the MEX
compiler into a MEX file and is then used in an S-Function block.
Simulink calls the functions in the C MEX file to obtain the above
mentioned block attributes. In case of RPP blocks, no other
functionality is present in the C MEX file.

The C files are stored in \texttt{\repo/rpp/blocks} directory and are named as
\texttt{sfunction\_$\langle$name$\rangle$.c}. Feel free to open any of
the C files as a reference.

Every C file that will be used with the RPP library should begin with
a comment in YAML\footnote{\url{http://yaml.org/},
  \url{https://en.wikipedia.org/wiki/YAML}} format. The information in
this block is used to automatically generate both printed and on-line
documentation. Although this block is not mandatory, it is highly
recommended, as it helps keeping the documentation consistent and
up-to-date.

The YAML documentation block may look like this:
\begin{lstlisting}[language=c,basicstyle=\tt\footnotesize]
/*
%YAML 1.2
---
Name: Name Of The Block
Category: IO blocks
Header: rpp/sci.h
Mnemonic: MBLK

Inputs:
  - { name: "Some Input Signal", type: "bool" }

Outputs:
  - { name: "Some Output Signal", type: "bool"   }

Parameters:

# Description and Help is in Markdown mark-up
Description: |

  This is a stub of an example block.

Help: |

  This block is a part of an example about how to create
  new Matlab Simulink blocks for RPP board.

Status: Unstable

RPP API functions used:
  - rpp_sci_print()

Relevant demos:
...
*/
\end{lstlisting}

Following parts are obligatory and the block will not work without them. It starts with a
definition of the block name and inclusion of a common source file:

\begin{lstlisting}[language=c]
#define S_FUNCTION_NAME sfunction_myblock
#include "header.c"
\end{lstlisting}

To let Simulink know the type of the inputs, outputs and how many parameters
will the block have, the \texttt{mdlInitializeSizes()} function has to be defined like this:

\begin{lstlisting}[language=c]
static void mdlInitializeSizes(SimStruct *S)
{
    /* The block will have no parameters. */
    if (!rppSetNumParams(S, 0)) {
        return;
    }
    /* The block will have one input signal. */
    if (!ssSetNumInputPorts(S, 1)) {
        return;
    }
    /* The input signal will be of type boolean */
    rppAddInputPort(S, 0, SS_BOOLEAN);
    /* The block will have one output signal */
    if (!ssSetNumOutputPorts(S, 1)) {
        return;
    }
    /* The output signal will be of type boolean */
    rppAddOutputPort(S, 0, SS_BOOLEAN);
    
    rppSetStandardOptions(S);
}
\end{lstlisting}

The C file may contain several other optional functions definitions for parameters check,
run-time parameters definition and so on. For information about those functions refer the comments
in the header.c file, trailer.c file and documentation of Simulink S-Functions.

The minimal C file compilable into C MEX has to contain following
macros to avoid linker error messages about some of the optional
functions not being defined:
\begin{lstlisting}[language=c]
#define COMMON_MDLINITIALIZESAMPLETIMES_INHERIT
#define UNUSED_MDLCHECKPARAMETERS
#define UNUSED_MDLOUTPUTS
#define UNUSED_MDLTERMINATE
\end{lstlisting}

Every C file should end by inclusion of a common trailer source file:

\begin{lstlisting}[language=c]
#include "trailer.c"
\end{lstlisting}

\subsection{C MEX file compilation}
\label{sec:c-mex-file}
In order to compile the created C file, the development environment
has to be configured first as described in
Section~\ref{sec-matlab-simulink-usage}.

All C files in the directory \texttt{\repo/rpp/blocks} can be compiled
into C MEX by running script
\texttt{\repo/rpp/blocks/compile\_blocks.m} from Matlab command
prompt. If your block requires some special compiler options, edit the
script and add a branch for your block.

To compile only one block run the \texttt{mex sfunction\_myblock.c}
from Matlab command prompt.

\subsection{TLC file creation}
\label{sec:tlc-file-creation}
The TLC file is a template used by the code generator to generate the
C code for the RPP board. The TLC files are stored in
\texttt{\repo/rpp/blocks/tlc\_c} folder and their names must be the
same (except for the extension) as the names of the corresponding
S-Functions, i.e. \texttt{sfunction\_$\langle$name$\rangle$.tlc}. Feel
free to open any of the TLC files as a reference.

TLC files for RPP blocks should contain a header:
\begin{lstlisting}[language=c]
%implements sfunction_myblock "C"
%include "common.tlc"
\end{lstlisting}

Code Generator expects several functions to be implemented in the TLC file. The functions are not obligatory, but most of the blocks will probably need them:
\begin{enumerate}
	\item BlockTypeSetup
	\item BlockInstanceSetup
	\item Start
	\item Outputs
\end{enumerate}

For detailed description about each one of those functions, refer to
\cite{targetlanguagecompiler2013}. A simple TLC file, which generates
some code may look like this:
\begin{lstlisting}[language=c]
%implements sfunction_myblock "C"
%include "common.tlc"

%function BlockTypeSetup(block, system) void
	%% Ensure required header files are included
	%<RppCommonBlockTypeSetup(block, system)>
	%<LibAddToCommonIncludes("rpp/sci.h")>
%endfunction

%function Outputs(block, system) Output
  %if !SLibCodeGenForSim()
    %assign in_signal = LibBlockInputSignal(0, "", "", 0)
    %assign out_signal = LibBlockOutputSignal(0, "", "", 0)

    %<out_signal> = !%<in_signal>;
    rpp_sci_printf("Value: %d\r\n", %<in_signal>);
%endif
%endfunction
%% [EOF]
\end{lstlisting}

The above template causes the generated code to contain
\texttt{\#include "rpp/sci.h"} line and whenever the block is
executed, its output will be the negation of its input and the value
of the input signal will be printed to the serial line.

\subsection{Creation of an S-Function block in the RPP block library}
\label{sec:creation-an-s}
User defined Simulink blocks can be included in the model as
S-Function blocks. Follow this procedure to create a new block in the
RPP block library:
\begin{enumerate}
\item Create a new Simulink library by selecting
  \textsc{File$\rightarrow$New$\rightarrow$Library} and save it as
  \texttt{\repo\-/rpp/blocks/rpp\_$\langle$name$\rangle$.slx}.
  Alternatively, open an existing library.
\item In case of opening an existing library, unlock it for editing by
  choosing \textsc{Diagram$\rightarrow$Unlock Library}.
\item Open a Simulink Library Browser
  (\textsc{View$\rightarrow$Library Browser}) open
  \textsc{Simulink$\rightarrow$User-Defined Functions} and drag the
  \textsc{S-Function} block into the newly created library.
\item Double click on the just created \textsc{S-Function} block and
  fill in the \textsc{S-function name} field. Put there the name
  (without the extension) of the created C MEX S-Function, e.g.
  sfunction\_myblock. The result should like like in
  Figure~\ref{fig-simulink_s_fun_cfg}.
  \begin{figure}[h]\begin{center}
      \noindent
      \includegraphics[scale=.45]{images/simulink_s_fun_config.png}
      \caption{Configuration dialog for user defined S-function.}
      \label{fig-simulink_s_fun_cfg}
    \end{center}\end{figure}
\item If your block has some parameters, write their names (you can
  choose them arbitrarily) in the \textsc{S-function parameters}
  field, separated by commas. \label{item:1}
\item Now you should see the new Simulink block with the right number
  of inputs and outputs.
\item Optional: Every user-defined block can have a \emph{mask}, which
  provides some useful information about the name of the block,
  configuration dialog for parameters and names of the IO signals. The
  block can be used even without the mask, but it is not as user
  friendly as with proper mask. Right-click the block and select
  \textsc{Mask$\rightarrow$Create Mask...}. In the definition of
  parameters, use the same names as in step~\ref{item:1}. See
  \cite[Section ``Block Masks'']{mathworks13:simul_2013b} for more
  information.
\item Save the library and run \texttt{rpp\_setup} (or just
  \texttt{rpp\_generate\_lib}) from Matlab command line to add the newly
  created block to RPP block library (\texttt{rpp\_lib.slx}).
\end{enumerate}

Now, you can start using the new block in Simulink models as described
in Section~\ref{sec-crating-new-model}.


\section{Demos reference}
The Simulink RPP Demo Library is a set of Simulink models that use blocks from
the Simulink RPP Block Library and generates code using the Simulink RPP Target.

This demos library is used as a test suite for the Simulink RPP Block Library
but they are also intended to show basic programs built using it. Because of
this, the demos try to use more than one
type of block and more than one block per block type.

In the reference below you can find a complete description for each of the demos.

\subsection{ADC demo}
\begin{figure}[H]\begin{center}
\noindent
\includegraphics[scale=.45]{images/demo_adc.png}
\caption{Example of the usage of the Analog Input blocks for RPP.}
\end{center}\end{figure}

\textbf{Description:}

Demostrates how to use Analog Input blocks in order to measure voltage. This demo
measures voltage on every available Analog Input and prints the values on the
Serial Interface.

\subsection{Simple CAN demo}
\begin{figure}[H]\begin{center}
\noindent
\includegraphics[scale=.45]{images/demo_simple_can.png}
\caption{The simplest CAN demonstration.}
\end{center}\end{figure}

\textbf{Description:}

The simplest possible usage of the CAN bus. This demo is above all designed for
testing the CAN configuration and transmission.

\subsection{CAN transmit}
\begin{figure}[H]\begin{center}
\noindent
\includegraphics[scale=.45]{images/demo_cantransmit.png}
\caption{Example of the usage of the CAN blocks for RPP.}
\end{center}\end{figure}

\textbf{Description:}

Demostrates how to use CAN Transmit blocks in order to:

\begin{compactenum}
\item Send unpacked data with data type uint8, uint16 and uint32.
\item Send single and multiple signals packed into CAN\_MESSAGE by CAN Pack block.
\item Send a message as extended frame type to be received by CAN Receive
configured to receive both, standard and extended frame types.
\end{compactenum}

Demostrates how to use CAN Receive blocks in order to:

\begin{compactenum}
\item Receive unpacked data of data types uint8, uint16 and uint32.
\item Receive and unpack received CAN\_MESSAGE by CAN Unpack block.
\item Configure CAN Receive block to receive Standard, Extended and both frame types.
\item Use function-call mechanism to process received messages
\end{compactenum}

\subsection{Continuous time demo}
\begin{figure}[H]\begin{center}
\noindent
\includegraphics[scale=.45]{images/demo_continuous.png}
\caption{The demonstration of contiuous time.}
\end{center}\end{figure}

\textbf{Description:}

This demo contains two integrators, which are running at continuous time. The main goal
of this demo is to verify that the generated code is compilable and is working even when
discrete and continuous time blocks are combined together.

\subsection{Simulink Demo model}
\begin{figure}[H]\begin{center}
\noindent
\includegraphics[scale=.45]{images/demo_board.png}
\caption{Model of the complex demonstration of the boards peripherals.}
\end{center}\end{figure}

\textbf{Description:}

This model demonstrates the usage of RPP Simulink blocks in a complex and interactive
application. The TI HDK kit has eight LEDs placed around the MCU. The application
rotates the light around the MCU in one direction. Every time the user presses the button
on the HDK, the direction is switched.

The state of the LEDs is sent on the CAN bus as a message with ID 0x1. The button can
be emulated by CAN messages with ID 0x0. The message 0x00000000 simulates button release
and the message 0xFFFFFFFF simulates the button press.

Information about the state of the application are printed on the Serial Interface. 

\subsection{Echo char}
\begin{figure}[H]\begin{center}
\noindent
\includegraphics[scale=.45]{images/demo_echo_char.png}
\caption{Echo Character Simulink demo for RPP.}
\end{center}\end{figure}

\textbf{Description:}

This demo will echo (print back) any character received through the Serial Communication
Interface (115200-8-N-1).

Note that the send subsystem is implemented a as \textit{triggered} subsystem and will execute only
if data is received, that is, Serial Receive output is non-negative. Negative values are errors.

\subsection{GIO demo}
\begin{figure}[H]\begin{center}
\noindent
\includegraphics[scale=.45]{images/demo_gio.png}
\caption{Demonstration of DIN and DOUT blocks}
\end{center}\end{figure}

\textbf{Description:}

The model demonstrates how to use the DIN blocks and DOUT blocks, configured in every mode. The DOUTs
are pushed high and low with period 1 second. The DINs are reading inputs and printing the values
on the Serial Interface with the same period.

\subsection{Hello world}
\begin{figure}[H]\begin{center}
\noindent
\includegraphics[scale=.45]{images/demo_hello_world.png}
\caption{Hello World Simulink demo for RPP.}
\end{center}\end{figure}

\textbf{Description:}

This demo will print \texttt{Hello Simulink} to the Serial Communication Interface (115200-8-N-1) one
character per second. The output speed is driven by the Simulink model step which is set to one
second.

\subsection{Multi-rate SingleTasking demo}
\label{sec:mult-single-thre}

\begin{figure}[H]\begin{center}
\noindent
\includegraphics[scale=.45]{images/demo_multirate_st.png}
\caption{Multi-rate SingleTasking Simulink demo for RPP.}
\end{center}\end{figure}

\textbf{Description:}

This demo will toggle LEDs on the Hercules Development Kit with
different rate. This is implemented with multiple Simulink tasks, each
running at different rate. In the generated code, these tasks are
called from a singe thread and therefore no task can preempt another
one. See Section \ref{sec-singlet-mode} for more details.

The state of each LED is printed to the Serial Communication Interface
(115200-8-N-1) when toggled.

\begin{center}
	\begin{tabular}{lll}
    \rowcolor[gray]{0.9}
		LED & pin & rate [s] \\
		1 & NHET1\_25 & 0.3 \\
		2 & NHET1\_05 & 0.5 \\
		3 & NHET1\_00 & 1.0 \\
	\end{tabular}
	\captionof{table}{LEDs connection and rate}
	\label{tab:multirate_st_led_desc}
\end{center}

\subsection{Multi-rate MultiTasking demo}
\label{sec:mult-multi-thre}

\begin{figure}[H]\begin{center}
\noindent
\includegraphics[scale=.45]{images/demo_multirate_mt.png}
\caption{Multi-rate MultiTasking Simulink demo for RPP.}
\label{fig:multitasking-demo}
\end{center}\end{figure}

\textbf{Description:}

This demo toggles LEDs on the Hercules Development Kit with different
rate (different colors in Figure~\ref{fig:multitasking-demo}). This is
implemented with multiple Simulink tasks, each running at different
rate. In the generated code, every subrate task runs in its own
operating system thread. See Section \ref{sec-multit-mode} for more
details.

The state of each LED is also printed to the Serial Communication
Interface (115200-8-N-1) when toggled.

\begin{center}
	\begin{tabular}{lll}
    \rowcolor[gray]{0.9}
		LED & pin & rate [s] \\
		1 & NHET1\_25 & 0.3 \\
		2 & NHET1\_05 & 0.5 \\
		3 & NHET1\_00 & 1.0 \\
	\end{tabular}
	\captionof{table}{LEDs connection and rate}
	\label{tab:multirate_mt_led_desc}
\end{center}

\subsection{Hydraulics controller initialization demo}
\label{sec:board-init-hydctr}
\begin{figure}[H]
  \centering
  \includegraphics[scale=0.45]{images/demo_board_init_hydctr.png}
  \caption{board\_init\_hydctr demo}
  \label{fig:board_init_hydctr}
\end{figure}

\paragraph{Description}

This demo shows how to use the \emph{Board Init} block to initialize
SPI devices on the Hydraulics Controller board. Additionally, it shows
how to use unused SPI pins on the MCU as general-purpose IOs. If both
Board Init and GIO SPI blocks are used together, care must be taken
about the order in which the blocks are initialized. GIO blocks that
represent SPI pins must be initialized \emph{after} the Board Init
block. This can be ensured by giving the GIO blocks higher priority
than the Board Init block.

\chapter{Command line testing tool}
\label{chap-rpp-test-software}
\section{Introduction}
\label{sec-rpp-test-sw-intro}
The \texttt{rpp-test-suite} is a RPP application developed testing and direct
control of the RPP hardware. The test suite implements a command processor,
which is listening for commands and prints some output related to the commands
on the serial interface. The command processor is modular and each peripheral
has its commands in a separate module.

The command processor is implemented in \texttt{$\langle$rpp-test-sw$\rangle$/cmdproc} and commands
modules are implemented in \texttt{$\langle$rpp-test-sw$\rangle$/commands} directory.

The application enables a command processor using the SCI at
\textbf{115200-8-N-1}. When the software starts, the received welcome message
and prompt should look like:

\bigskip
\ifx\tgtId\tgtIdTMSRPP
\noindent\texttt{Rapid Prototyping Platform v00.01-001\\
Test Software version \input{version.tex}\\
CTU in Prague 2014\\
-->
}
\else
\noindent\texttt{Ti HDK \mcuname, FreeRTOS 7.0.2\\
Test Software version \input{version.tex}\\
CTU in Prague 10/2014\\
-->
}
\fi

\bigskip

Type in command help for a complete list of available command, or help command
for a description of concrete command.

\section{Compilation}
\label{sec-rpp-test-sw-compilation}
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.
\begin{enumerate}
	\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}.
	\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}.

To build the Testing tool from Linux terminal run:
\begin{lstlisting}[language=bash]
cd <rpp-test-sw>
make
\end{lstlisting}

or from Windows command line:

\begin{lstlisting}[language=bash]
cd <rpp-test-sw>
"C:\ti\ccsv5\utils\bin\"gmake.exe
\end{lstlisting}

On Windows \texttt{gmake.exe} supplied with CCS is used instead of
\texttt{make}.
\end{enumerate}

\section{Commands description}

This section contains the description of the available commands. The
same description is also available in the program itself via the
\texttt{help} command.

% Pandoc generates \tightlist in its output. Since we don't use pandoc
% template, we have put its definition here.
\providecommand{\tightlist}{%
  \setlength{\itemsep}{0pt}\setlength{\parskip}{0pt}}

\input{rpp-test-sw-cmds.tex}

\chapter{Glossary}

\begin{description}
\item[ADC]
  \textit{Analog to Digital Converter.} \newline{}
  Hardware circuitry that converts a continuous physical quantity (usually voltage) to a
  digital number that represents the quantity's amplitude.

\item[AIN]
  \textit{Analog Input.} \newline{}
  Mnemonic to refer to or something related to the analog input (ADC) hardware module.

\item[AOUT]
  \textit{Analog Output.} \newline{}
  Mnemonic to refer to or something related to the analog output (DAC) hardware module.

\item[API] \textit{Application Programming Interface}

\item[CAN]
  \textit{Controller Area Network.} \newline{}
  The CAN Bus is a vehicle bus standard designed to allow microcontrollers and devices to
  communicate with each other within a vehicle without a host computer.
  In this project it is also used as mnemonic to refer to or something related to the CAN
  hardware module.

\item[CCS] \textit{Code Composer Studio} \\
  Eclipse-based IDE provided by Texas Instruments.

\item[CGT]
  \textit{Code Generation Tools.} \newline{}
  Name given to the tool set produced by Texas Instruments used to compile, link, optimize,
  assemble, archive, among others. In this project is normally used as synonym for
  ``Texas Instruments ARM compiler and linker."

\item[DAC]
  \textit{Digital to Analog Converter.} \newline{}
  Hardware circuitry that converts a digital (usually binary) code to an analog signal
  (current, voltage, or electric charge).

\item[DIN]
  \textit{Digital Input.} \newline{}
  Mnemonic to refer to or something related to the digital input hardware module.

\item[ECU]
  \textit{Engine Control Unit.} \newline{}
  A type of electronic control unit that controls a series of actuators on an internal combustion
  engine to ensure the optimum running.

\item[ETH]
  \textit{Ethernet.} \newline{}
  Mnemonic to refer to or something related to the Ethernet hardware module.

\item[FR]
  \textit{FlexRay.} \newline{}
  FlexRay is an automotive network communications protocol developed to govern on-board automotive
  computing.
  In this project it is also used as mnemonic to refer to or something related to the FlexRay
  hardware module.

\item[GPIO]
  \textit{General Purpose Input/Output.} \newline{}
  Generic pin on a chip whose behavior (including whether it is an input or output pin) can be
  controlled (programmed) by the user at run time.

\item[HBR]
  \textit{H-Bridge.} \newline{}
  Mnemonic to refer to or something related to the H-Bridge hardware module. A H-Bridge is
  an electronic circuit that enables a voltage to be applied across a load in either direction.

\item[HOUT]
  \textit{High-Power Output.} \newline{}
  Mnemonic to refer to or something related to the 10A, PWM, with current sensing, high-power
  output hardware module.

\item[IDE]
  \textit{Integrated Development Environment.} \newline{}
  An IDE is a Software application that provides comprehensive facilities to computer programmers
  for software development.

\item[LCT]
  \textit{Legacy Code Tool.} \newline{}
  Matlab tool that allows to generate source code for S-Functions given the descriptor of a C 
  function call.

\item[MBD]
  \textit{Model-Based Design.} \newline{}
  Model-Based Design (MBD) is a mathematical and visual method of addressing problems associated
  with designing complex control, signal processing and communication systems. \cite{modelbasedwiki2013}

\item[MEX]
  \textit{Matlab Executable.} \newline{}
  Type of binary executable that can be called within Matlab. In this document the common term
  used is `C MEX S-Function", which means Matlab executable written in C that implements a system
  function.

\item[PWM]
  \textit{Pulse-width modulation.} \newline{}
  Technique for getting analog results with digital means. Digital control is used to create a
  square wave, a signal switched between on and off. This on-off pattern can simulate voltages
  in between full on and off by changing the portion of the time the signal spends on versus
  the time that the signal spends off. The duration of ``on time" is called the pulse width or
  \textit{duty cycle}.

\item[RPP] \textit{Rapid Prototyping Platform.} \newline{} Name of the
  developed platform, that includes both hardware and software.

\item[SCI]
  \textit{Serial Communication Interface.} \newline{}
  Serial Interface for communication through hardware's UART using communication standard RS-232.
  In this project it is also used as mnemonic to refer to or something related to the Serial
  Communication Interface hardware module.

\item[SDC]
  \textit{SD-Card.} \newline{}
  Mnemonic to refer to or something related to the SD-Card hardware module.

\item[SDR]
  \textit{SD-RAM.} \newline{}
  Mnemonic to refer to or something related to the SD-RAM hardware module for logging.

\item[TLC]
  \textit{Target Language Compiler.} \newline{}
  Technology and language used to generate code in Matlab/Simulink.

\item[UART]
  \textit{Universal Asynchronous Receiver/Transmitter.} \newline{}
  Hardware circuitry that translates data between parallel and serial forms.
\end{description}

\printbibliography

\end{document}

%  LocalWords:  FreeRTOS RPP POSIX microcontroller HalCoGen selftests
%  LocalWords:  MCU UART microcontrollers DAC CCS simulink SPI GPIO
%  LocalWords:  IOs HDK TMDSRM
