\newcommand{\superscript}[1]{\ensuremath{^{\textrm{\small#1}}}}
\newcommand{\subscript}[1]{\ensuremath{_{\textrm{\small#1}}}}

\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[utf8x]{inputenc}  % char encoding
\usepackage[bottom]{footmisc} % footnotes
\usepackage{todonotes}

% 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}
\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,
   }

% 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$}

\begin{document}

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

\begin{titlepage}
\begin{center}

% Upper part of the page
\includegraphics[width=0.70\textwidth]{images/logos.png}\\[1cm]
\textsc{\LARGE Costa Rica Institute of Technology}\\[0.5cm]
\textsc{\LARGE Czech Technical University in Prague}\\[1.5cm]


% Document title
\HRule \\[0.4cm]
{ \huge \bfseries Code generation for automotive rapid prototyping platform using Matlab/Simulink}\\[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

\tableofcontents

\newpage

\listoffigures

\newpage

%\addtolength{\parskip}{\baselineskip} % Paragraph spacing

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

This text is a documentation for a Rapid Prototyping Platform (RPP) project. It
may serve as a guideline for development tools installation, Simulink Coder
configuration, creation of new models as well as downloading the resulting
firmware to the hardware. It can also be used as a reference for a testing tool,
Matlab Simulink blocks and RPP Matlab Simulink Code generator. The document also
provides an overall description of the hardware design and architecture of its
control software.

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

The Rapid Prototyping Platform is an ECU (Electronic Control Unit) designed for
use in Automotive, thus requirements for Automotive communication interfaces,
durable IO ports and analog-digital converters were applied.

The ECU is controlled by TMS570LS5137ZWT MCU, which is an ARM Cortex R4 based
microcontroller developed by Texas Instruments. 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{tms570ls31xtechnicalreferencemanual2012}
for details.

In order to develop non-trivial applications for the RPP, an operating
system is necessary. The RPP is based on FreeRTOS -- an opensource operating
system real-time kernel, aimed not only at embedded systems. The FreeRTOS
provides an API for creation and managing multiple tasks, scheduler, memory
manager, semaphores, queues, mutexes, timers and lots of other features wich 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
control 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 for the use in applications. The operating
system and the control software, 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 humans make mistakes and in safety critical applications any mistake can
cause damage, looses of money or in the worst case even death of other people,
the room for making mistakes has to be as small as possible. An approach called
Model-based \cite{modelbasedwiki2013} development has been introduced. In
Simulink  the application is developed as a model made of blocks connected
together. Every block implements some functionality. For example one block
receives a voltage from an analog-digital converter, provides the value as an
input to another block which implements some clever algorithm and the product is
passed as an input to another block, which sends the value as a CAN message to
some other MCU. The final model can be simulated and tested even before the real
hardware exists. Finally a C code is generated from the model by a Simulink Code
Generator. The code can be 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 room for making mistakes during the application development has
significantly decreased and developers can focus on the functionality instead of
the hardware and control software implementation. More information about Code
generation can be found in Chapter \ref{chap-simulink-coder-target}. For a
reference about Matlab Simulink, Embedded Coder and Simulink Coder,
refer to
\cite{embeddedcoderreference2013, ebmeddedcoderusersguide2013,
  simulinkcoderreference2013, targetlanguagecompiler2013,
  simulinkcoderusersguide2013, simulinkdevelopingsfunctions2013}.

\section{Software architecture}
\label{sec-software-architecture}
The basic RPP software, also called the RPP library, is 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
(\textsc{rpp.h}, \textsc{drv.h}, \textsc {hal.h}, \textsc{sys.h} and
\textsc{os.h}), so top layers depends on that layer  interface and not on
individual elements from that layer.  \end{compactitem}

\begin{figure}[H]
\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 \textsc{drv/din.h}. With this organization
user applications only needs to include the top layer interface files (for
example \textsc{rpp/rpp\_can.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 operating system interchangeable layer, containing the FreeRTOS
source files. The system can be easily replaced by another version thanks to
this layer. For example it is possible to compile the library for Linux (using
POSIX version of the FreeRTOS), which can be desirable for some testing. The
source files can be found in the \textsc{$\langle$rpp\_lib\_root$\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[7.0.2] Prefered version of the FreeRTOS, distributed by
Texas Instruments. This version is in use in the current version of the
library.
	\item[7.4.0] Newest version distributed by the Texas Instruments.
	\item[7.4.2] Newer version available from FreeRTOS pages. Slightly
modified to run on TMS570 MCU.
\end{description}

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

Large part of this layer was generated with the HalCoGen tool. % TODO ref

\subsection{HAL abstraction layer}
\label{sec-hal-abstraction-layer}
Hardware Abstraction Layer (HAL) creates an abstraction over the real hardware.
For example imagine an IO port with 8 pins. First four pins are connected to the
MCU directly to GPIO pins, another four pins are connected to an external
integrated circuit, communicating with the MCU via SPI. It would be annoying to
have to remember which group is which and to have two sets of control functions
for one peripheral. This layer maps every pin of the port to a control function
from the System Layer, groups the pins together, names them in a unified style
and provides common read, write and configure functions.

As a result, the higher layers do not have to know anything about the wiring of
the peripherals, they can just call read, write or configure function with a pin
name as a parameter and the HAL handles all the details.

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

\subsection{Drivers layer} 
\label{sec-drivers-layer}
The Drivers layer contains code for controlling the RPP peripherals. The layer
benefits from the lower layers thus it is not too low level, but still there are
some peripherals like ADC or H-bridge, which needs some special procedure for
initialization and running, that would not be very intuitive for the user. For
example the H-bridge needs a watchdog reset task to be started before the bridge
is enabled.

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

\subsection{RPP Layer}
\label{sec-rpp-layer} 
The RPP Layer is the highest layer of the control software. This layer provides
an easy to use set of functions for every peripheral and requires only basic
knowledge about them. For example, to control the H-bridge,
the user can  just call  \textsc{rpp\_hbr\_init()} function to enable the H-bridge
and the function calls a sequence of Drivers layer functions to start the
Watchdog and configure the peripheral.

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

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

This section provides reference documentation for the RPP board:

%%TODO: operating conditions as a reference to the Ti documentation

\begin{compactitem}
	\item Layout description.
	\item Connectors pinout.
	\item Modules capabilities and features.
\end{compactitem}

\subsection{Layout description}
\label{sec-layout-description}
The RPP board has been designed with strict Automotive standards and safety in
mind. The components and pins are placed in sections and wires are routed in a
way to avoid any significant electromagnetic interference.

As can be seen on Figure \ref{board_photo}, the high power output logic is
placed in the top left corner, the low power output logic is placed on the
bottom left corner, while the communication logic is placed on the top right
corner.  In the middle there is the only one button available, the reset button
and below it is placed the TMS570 MCU itself. In the bottom right corner there
are components of analog inputs.

\begin{figure}[H]\begin{center}
\noindent
\includegraphics[width=300px]{images/board-photo.png}
\caption{The RPP board (signal connector missing).}
\label{board_photo}
\end{center}\end{figure}


\subsection{Connectors pinout}
\label{sec-connector-pinout}
The pinout of the board, described by the Figure \ref{pinout}, follows the
layout described in the previous section. The side connectors for communication
(24 pins), signals (56 pins) and power (24 pins) are automotive approved
humidity resistant connectors.

\begin{figure}[H]
\advance\leftskip-1cm
\noindent
\includegraphics[width=530px]{images/pinout.pdf}
\caption{The RPP connectors pinout.}
\label{pinout}
\end{figure}

\subsection{Modules description}
\label{sec-modules-description}
This section enumerates the capabilities of the hardware modules from Software
perspective. The block diagram of the modules can be seen in Figure
\ref{blocks}.

\begin{figure}[H]
\advance
\leftskip-1cm
\noindent
\includegraphics[width=500px]{images/blocks.pdf}
\caption{The RPP layer modules.}
\label{blocks}
\end{figure}

\subsubsection{Logic IO}
\label{sec-logic-io}

\paragraph{Digital Inputs (DIN)}
\label{par-digital-inputs}
\begin{compactitem}
	\item 16 pins available on Signal Connector.
	\item Pins 8-15 status can be read via GPIO using configurable
threshold.  \newline{} Pins 8-11 use variable threshold B and pins 12-15 use
variable threshold A.
	\item Variable threshold is a DAC chip MCP4922.
	\item All pins are read at once via SPI (fixed threshold) using chip
MC33972.
	\item 0-7 are programmable pins and can be set to pull-up or
pull-down. 8-15 are pull-down only.
	\item All pins can be set to be active or tri-stated.
	\item All pins can be set to trigger interrupt.
	\item On-line diagnostic of broken wire.
\end{compactitem}

\paragraph{Digital Outputs (LOUT)}
\label{par-digital-outputs}
\begin{compactitem}
	\item 8 pins available on Signal Connector.
	\item Pins for logic output only, up to 100mA.
	\item All pins are set at once using a chip through SPI.
\end{compactitem}

\paragraph{Analog Input (ADC)}
\label{par-analog-input}
\begin{compactitem}
	\item 12 channels available.
	\item Differential inputs, thus 24 pins available on Signal Connector.
	\item Range for 0-20 volts.
	\item 12 bits resolution.
	\item Using CPU ADC.
\end{compactitem}

\paragraph{Analog Output (DAC)}
\label{par-analog-output}
\begin{compactitem}
	\item 4 pins available on Signal Connector.
	\item Output range is 0-12 volts.
	\item Using 2 x MCP4922 DACs controlled using SPI.
	\item Resolution is 12 bits. But because of amplification and voltage
reference not all range is used.
\end{compactitem}

\subsubsection{Power Output}
\label{sec-power-output}
\paragraph{H-Bridge (HBR)}
\label{par-hbr}
\begin{compactitem}
	\item 1 port (2 pins) available on Power Connector.
	\item Communication is done through SPI.
	\item H-Bridge can be enabled or disabled.
	\item Current direction can be set.
	\item PWM control with 1\% resolution change of the duty cycle.
	\item Port can drive load up to 10A.
\end{compactitem}

\paragraph{Power Output (MOUT)}
\label{par-power-output}
\begin{compactitem}
	\item 6 pins available on Power Connector.
	\item Pins can drive a load up to 2A. Push/Pull.
	\item Pins are set using 6 CPU output GPIOs. Diagnostic are read using 6
externally pulled-up open-drain input GPIOs.
	\item On-line diagnostics. Driver chip will pull-down the corresponding
diagnostic pin on the CPU.  
\end{compactitem}

\paragraph{High-Power Output (HOUT)}
\label{par-high-power-output}
\begin{compactitem}
	\item 6 pins available on Power Connector.
	\item Pins can be set ON/OFF.
	\item Pins can drive a load up to 10A with PWM.
	\item System can read analog values of current flowing (IFBK).
	\item System can read diagnostics values (DIAG). Detection of a fault
condition.  
\end{compactitem}

\subsubsection{Communication}
\label{sec-communication}
\paragraph{CAN bus (CAN)}
\label{par-can}
\begin{compactitem}
	\item 3 ports available (CAN uses differential signaling) thus 6 pins
are available on Communication connector.
	\item High speed.
	\item Recover from error.
	\item Detection of network errors.
\end{compactitem}

\paragraph{Local Interconnect Network (LIN)}
\label{par-lin}
\begin{compactitem}
	\item 2 ports/pins available on Communication Connector.
	\item Only first port can be used when using the SCI. Second port is
shared with SCI.  
\end{compactitem}

\paragraph{FlexRay (FR)}
\label{par-flexray}
\begin{compactitem}
	\item 2 ports available. FlexRay uses differential signaling thus 4 pins are available on
 Communication Connector.
\end{compactitem}

\paragraph{Serial Comm. Interface (SCI)}
\label{par-sci}
\begin{compactitem}
	\item 1 port available inside the box on SCI connector (4 pins).
	\item Variable baud rate. Tested on 9600 and 115200.
	\item RS232 standard compatible.
\end{compactitem}

\paragraph{Ethernet (ETH)}
\label{par-eth}
\begin{compactitem}
	\item 1 port available. Standard Ethernet connector available inside box.
\end{compactitem}

\subsubsection{Data storage/logging}
\label{sec-data-storage}
\paragraph{External Memory SD-RAM (SDR)}
\label{par-external-memory}
\begin{compactitem}
	\item 64MB (currently installed) external RAM used for logging. Maximal
supported capacity is 256MB.
	\item Memory test routine available with test
Software.
\end{compactitem}

\paragraph{SD Card (SDC)}
\label{par-sd-card}
\begin{compactitem}
	\item Standard SD-Card connector or microSD connector available inside box.
	\item Communication done using SPI.
\end{compactitem}

\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.
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 RPP functionality.

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

\section{Software requirements}
\label{sec-software-requirements}
The RPP software stack was developed to be functional on Windows and
Linux platforms. The following sections 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
	\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
	\item Doxygen 1.8.4 (optionaly, see Section \ref{sec-compiling-api-documentation}) 
	\item Uncrustify 0.59 (optionally, see Section \ref{sec-compilation})
        \item Git 1.9.4.msysgit.2 (optional)
\end{itemize}

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

\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 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:

	\begin{quotation}
\url{http://processors.wiki.ti.com/index.php/Category:Code\_Composer\_Studio\_v5}
	\end{quotation}

Once downloaded, add executable permission to the installation file and launch
the installation by executing it. Installation must be done as root 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
32b application and thus requires 32bits libraries:

\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 \textsc{org.eclipse.ui/showIntro} to false.

\subsubsection{Installation on Windows}
\label{sec-installation-on-windows}
The installation for Windows is more straightforward than the previous procedure
for Linux.

Download CCS for Windows from:

	\begin{quotation}
\url{http://processors.wiki.ti.com/index.php/Category:Code\_Composer\_Studio\_v5}
	\end{quotation}

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

\subsubsection{First launch} 
\label{sec-first-launch}
If another licence is not available, choose ``FREE License -- for use with XDS100
JTAG Emulators'' from the licensing options. Code download for the board is using
that particular 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 generation code for target platforms.  Supported Matlab Simulink
version is R2013b for 64 bits Linux and Windows.

\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 

\begin{quotation}
\url{https://sites.google.com/site/terminalbpp/}
\end{quotation}

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

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 installation
file is available at 

\begin{quotation}
\url{http://www.microsoft.com/en-us/download/details.aspx?id=8279}
\end{quotation}

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

\begin{description}
	\item[rpp-lib] The package contains the source codes of the RPP Library,
described in Chapter \ref{chap-c-support-library}. If you want to make any
changes in the drivers or RPP API, this library has to be compiled and linked
with the other two applications in the other two packages. The compile procedure
can be found in Section \ref{sec-compilation}.  
	\item[rpp-simulink] Contains the distributed binary of the RPP Library
static library, source codes of the Matlab Simulink blocks, demo models and
scripts for downloading the resulting firmware to the target. Details can be
found in Chapter \ref{chap-simulink-coder-target} 
	\item[rpp-test-sw]  Contains the distributed binary of the RPP Library
static library and source codes of a Command line testing tool. This application
is designed for direct cotroling of the target over Serial Interface. More
details can be found in Chapter \ref{chap-rpp-test-software}.
\end{description}

\subsection{rpp-lib}
\label{sec-rpp-lib-installation}
You may not need to deal with this package at all as the compiled library is
distributed with the applications. But in case of a contributions or further
development done by your team, this subsection describes how to open the project
in development environment and how to use the resulting static library in an
application.

\begin{enumerate}
	\item Unzip the \textsc{rpp-lib-version.zip} file.
	\item Open the Code Composer Studio (see Section \ref{sec-ti-ccs}).
	\item Follow the procedure for openning the projects in CCS in Section
\ref{sec-openning-of-existing-project} and open the rpp-lib project.  \item
Compile the static library using a procedure in Section \ref{sec-compilation}.
The binary file will appear in the project root directory.
	\item Copy the binary file to the application, where you want to test
and use the new library version.  
	\begin{itemize}
		\item In the rpp-simulink application the library binary file is
present at \textsc{rpp/lib} folder. 
		\item In the rpp-test-sw application the library binary file is
present at \textsc{rpp-lib} folder.  
	\end{itemize}
\end{enumerate}

\subsection{rpp-simulink}
\label{sec-rpp-simulink-installation}
If you want to access the demos, build your own models using the RPP blocks, if
you want to generate a C code, build a firmware for the RPP board and download
it to the real hardware, you have to install this application.

\begin{enumerate}
	\item Unzip the \textsc{rpp-simulink-version.zip} file.
	\item Follow the procedure in Section
\ref{sec-configuration-simulink-for-rpp} for configuring the Matlab Simulink for
the RPP project.  
	\item Follow the procedure in Section \ref{sec-crating-new-model} for
instruction about creating your own model which will be using the RPP Simulink
blocks.  
	\item Follow the instructions in Section \ref{sec-running-model-on-hw}
for download the firmware to the real RPP hardware.
\end{enumerate}

\subsection{rpp-test-sw}
\label{sec-test-sw-installation}
If you want a direct controll over the hardware for example to test your
modifications in the RPP Library follow this procedure for the rpp-test-sw
application installation.

\begin{enumerate}
	\item Unzip the \textsc{rpp-test-sw-version.zip} file.
	\item Open the Code Composer Studio (see Section \ref{sec-ti-ccs}).
	\item Follow the procedure for openning the projects in CCS in Section
\ref{sec-openning-of-existing-project} and open the rpp-test-sw project.  
	\item TODO: add header files, currently there is a Bug \#1061 in the release version
	\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}

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

\subsection{Opening of existing project}
\label{sec-openning-of-existing-project}
The project opening procedure is similar to standard Eclipse project opening.

\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 as depicted
in 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 on \textsc{Finish} button.
\end{enumerate}

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

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

\subsection{Creating new project}
\label{sec-creating-new-project}
In \textsc{\repo/rpp/lib/apps/} there are two RPP based
applications, \textsc{helloworld} and \textsc{helloworld\_posix}, that are
already configured for the RPP Library. It is advised that new applications use
this project as a foundation.

To create a new application copy this directory and rename it. Now open files
\textsc{.project}, \textsc{.cproject} and \textsc{.ccsproject} (if available)
and change any occurrence of the work \textsc{helloworld}
with the name of your project. Use lower case ASCII letters and underscores only.

\textbf{Steps to configure a new CCS (ARM, using CGT) RPP application:}

\begin{compactenum}
	\item Create a new CCS project. \newline{}
\noindent\includegraphics[width=400px]{images/base_1.png}
	\item Create a normal folder \textsc{include}.
	\item Create a source folder \textsc{src}.
	\item Add common \textsc{.gitignore} to the root of that project:
\lstset{language=}
\begin{lstlisting}
Debug
Release
.settings/*
\end{lstlisting}
\newpage
	\item Add new variable \textsc{RPP\_LIB\_ROOT} and point to this
repository branch root.\newline{}
\noindent\includegraphics[width=400px]{images/base_2.png}
	\item Add \textsc{rpp-lib.lib} static library to linker libraries and
add \textsc{RPP\_LIB\_ROOT} to the library search path.\newline{}
\noindent\includegraphics[width=400px]{images/base_3.png}
\newpage
	\item Configure linker to retain \textsc{.intvecs} from RPP static
library.\newline{} \noindent\includegraphics[width=350px]{images/base_4.png}
	\item Configure compiler to include local includes, OS includes for
TMS570 and RPP includes, in that order\todo{Add lwip include paths as
well}.\newline{}
\noindent\includegraphics[width=350px]{images/base_5.png}
\newpage
	\item Configure compiler to allow GCC extensions.\newline{}
\noindent\includegraphics[width=400px]{images/base_6.png}
	\item Import and link (\underline{do not copy!}) linker file and board
upload descriptor.\newline{}
\noindent\includegraphics[width=200px]{images/base_7.png}
\end{compactenum}

\textbf{Steps to configure a new GCC (x86(\_64)) RPP simulated application:}

\begin{compactenum}
	\item Create a new managed C project that uses Linux GCC toolchain.
	\item Create a source folder \textsc{src}. Link all files from original
CCS application to this folder.
	\item Create a normal folder \textsc{include}. Create a folder
\textsc{rpp} inside of it.  
	\item Add common \textsc{.gitignore} to the root of that project:
\lstset{language=}
\begin{lstlisting}
Debug
Release
.settings/*
\end{lstlisting}
\newpage
	\item Add new variable \textsc{RPP\_LIB\_ROOT} and point to this
repository branch root.\newline{}
\noindent\includegraphics[width=400px]{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=400px]{images/base_posix_2.png}
\newpage
	\item Add \textsc{rpp} and \textsc{pthread}to linker libraries and add
\textsc{RPP\_LIB\_ROOT} to the library search path.\newline{}
\noindent\includegraphics[width=400px]{images/base_posix_3.png}
\end{compactenum}

\textbf{In general any RPP application uses the layout/template:}

\begin{enumerate}
	\item Include RPP library header file. You may also include only a
selected modules to save space.  \lstset{language=c++}
\begin{lstlisting}
#include "rpp/rpp.h"
\end{lstlisting}

You may not want to include the whole library to save space and compile time. In
this case you may include only those modules, that you want to use. Inclusion
selected modules only requires two more
header files to be included as well: base.h and, in case sci is used for printing, rpp/sci.h.
\begin{lstlisting}
#include "rpp/hbr.h" /* We want to use H-bridge */
#include <base.h>	/* This is a necessary base header file of the rpp library. */
#include "rpp/sci.h" /* This is needed, because we are using rpp_sci_printf in following examples. */
\end{lstlisting}

\newpage
\item Create one or as many FreeRTOS task function definitions as required. Those tasks should use
  functions from this library.
\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 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.
	\item Catch if idle task could not be created.

\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) { asm(" nop"); }
    }

    /* 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) { asm(" nop"); }
}
\end{lstlisting}

 \end{itemize}
\item Create hook functions for FreeRTOS:
 \begin{itemize}
 \item \textsc{vApplicationMallocFailedHook()} allows to catch memory allocation
errors.
 \item \textsc{vApplicationStackOverflowHook()} allows to catch if a task
overflows it's stack.

\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{Running the software on the HW}
\label{sec-running-software-on-hw}
\subsubsection{Code Composer Studio Project}
\label{sec-ccs-run-project}
When the 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}
	\item Connect the Texas Instruments XDS100v2 USB emulator to the JTAG
port (see Figure \ref{pinout}, port 1).  
	\item Connect a USB cable to the XDS100v2 USB emulator and the
development computer.
	\item Plug in the power supply.  
	\item In the Code Composer Studio click on the
\textsc{Run$\rightarrow$Debug}. The project will  be optionaly built and
the download process will start. The Code Composer Studio will switch into debug
mode, 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 codes 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 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, TMS570LS3137, Texas Instruments XDS100v2 USB Emulator)
and select project template to \textsc{Empty Project}. The filled dialog should
look like on the Figure \ref{fig-new-empty-project}
	\item Click on the \textsc{Finish} button and new empty project will be
created.  
	\item In the \textsc{Project Explorer} click on the project with a right
mouse button and in the context menu select \textsc{Debug
as$\rightarrow$Debug configurations}.
	\item Click on a button \textsc{New launch configuration}
	\item Rename the New\_configuration, for example to myConfiguration.
	\item Select configuration target file by clicking the \textsc{File
System} button, finding and selecting the TMS5703137.ccxml file. The result
should look like on the Figure \ref{fig-debug-conf-main-diag}.  
	\item On 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.
Rpp-test-sw.out for example. The result should look like on the Figure
\ref{fig-debug-conf-program-diag}.
	\item You may also tune the target configuration like in the Section
\ref{sec-target-configuration}. 
	\item Finish the configuration by clicking on the \textsc{Apply} button
and download the code by clicking on the \textsc{Debug} button. You can later
invoke the download also from the \textsc{Run$\rightarrow$Debug} CCS menu. You
may not need to create more Debug configurations and CCS empty project as you
can easily change the binary file in the Debug configuration to load different
binary file.  
\end{enumerate}

\begin{center}
	\includegraphics[width=350px]{images/new_empty_project.png}
	\captionof{figure}{New empty project dialog}
	\label{fig-new-empty-project}
\end{center}

\begin{center}
	\includegraphics[width=350px]{images/debug_configuration_main.png}
	\captionof{figure}{Debug Configuration Main dialog}
	\label{fig-debug-conf-main-diag}
\end{center}

\subsubsection{Target configuration}
\label{sec-target-configuration}
Default target configuration erases the whole Flash memory, before downloading
the code. This is however not needed in most cases. 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 on the \textsc{Apply} button
and close the dialog.
\end{enumerate}

\begin{center}
	\includegraphics[width=350px]{images/debug_configuration_program.png}
	\captionof{figure}{Debug Configuration Program dialog}
	\label{fig-debug-conf-program-diag}
\end{center}

\section{Matlab Simulink usage}
\label{sec-matlab-simulink-usage}

\subsection{Configuring Simulink for RPP}
\label{sec-configuration-simulink-for-rpp}
\begin{enumerate}
\item Download and install CCS for Linux:

Details on how to setup CCS are available in Section \ref{sec-ti-ccs}.

\item Install RPP Target:

Open Matlab and type on command window:

\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 \textsc{armcl}
binary is located), normally:

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

This script will, among other things, ask the user to provide the location of
the armcl parent directory, infer and save some relevant CCS paths, add paths to
Matlab path and build S-Function
blocks for user's architecture (using Matlab's mex command line tool).

\item Create a new model or load a demo:

Demos are located on \textsc{\repo/rpp/demo} or you can start a new model and
configure target to RPP.  For new models see \htmladdnormallink{Target
Reference}{\#target\_reference} section below.
\end{enumerate}


\subsection{Working with demo models}
\label{sec-openning-demo-models}
The demo models are available from the directory \textsc{\repo/rpp/demos}. To
access the demo models for reference or for downloading to the RPP board you
have to change the directory to the one, containing the desired demo. For
example to open the cantransmit demo you have to type these commands into the
Matlab command line:

\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.

\subsection{Creating a new model}
\label{sec-crating-new-model}
\begin{enumerate}
	\item Open or create a model you want to generate code from.  \item Make
sure that the model is configured (\textsc{Simulation $\rightarrow$ Model
Configuration Parameters}) as described later in this section.
	\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 of that directory. The name of
the subdirectory will be \textsc{<model>\_rpp}, where \textsc{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}

If you want to run the model on the RPP board, see Section
\ref{sec-running-model-on-hw}.

The new Simulink model needs to be configured in the following way:

\begin{compactitem}
\item Solver (Figure \ref{fig-solver}):
 \begin{compactitem}
 \item Options: \emph{Fixed-step, discrete}
 \item Tasking mode set to \textit{SingleTasking}.
   \begin{figure}
     \centering
     \includegraphics[width=400px]{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[width=400px]{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 to \textsc{rpp.tlc}.
   \begin{figure}
     \centering
     \includegraphics[width=400px]{images/simulink_code.png}
     \caption{Code Generation settings}
 	 \label{fig-code-gen-settings}
\end{figure}
\end{compactitem}
\end{compactitem}


\subsection{Running model on the RPP board}
\label{sec-running-model-on-hw}
To run the model on the target RPP 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}.)
	\item Click on \textsc{Simulation$\rightarrow$Model Configuration
Parameters}.
	\item In the \textsc{Code Generation$\rightarrow$RPP Options} pane
check \textsc{Download compiled binary to RPP} checkbox.
	\item Click on \textsc{OK} button, connect the target HW to the computer
like in the Section \ref{sec-ccs-run-project} and build the model by \textsc{Code $\rightarrow$ C/C++
Code  $\rightarrow$ Build Model}. If the build
ends with a success, the download process will start and once the downloading is
finished, the application will run immediatelly.
\end{enumerate}

The code downloading is supported for Windows and Linux development systems. If
you are using Linux, you may also try to use the OpenOCD by checking Use OpenOCD
to download the compiled binary checkbox in addition. Refer 

\begin{verbatim}
http://rtime.felk.cvut.cz/hw/index.php/TMS570LS3137#OpenOCD_setup_and_Flashing
\end{verbatim}
fore more information about the OpenOCD configuration.

  Note: You should end the Code Composer Studio debug session before
  downloading the generated code to the RPP board. Otherwise the
  download fails.

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

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

Use GtkTerm in Linux or Bray Terminal for accessing the serial interface. 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}

% TODO: implement

\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{Description}
\label{sec-description}
The RPP C Support Library (also called RPP library) defines the API for
working with the board. It includes drivers and an 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 a static library named \texttt{rpp-lib.lib} and can be found in
\textsc{\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 modules, described later in this document. The
Command line testing tool, described in Chapter \ref{chap-rpp-test-software} and
Simulink Coder target, described in Chapter \ref{chap-simulink-coder-target}.

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.
	\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 \textsc{$\langle$layer$\rangle$\_$\langle$module$\rangle$\_}, for example
\textsc{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 \textsc{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 \textsc{\#include "foo/foo.h"} in any RPP Layer interface
file. 
\end{compactitem}

\section{Coding style}
\label{sec-coding-style}
In order to keep the code as clean as possible, a 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 a usage of a program named
Uncrustify. The Uncrustify program checks the code and fixes those
lines that does not match the coding style. However, keep in mind that
the program is not perfect and sometimes some lines can be modified
even when 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 the existing code. When a new feature is implemented, before
committing to the repository, a command: 

\lstset{language=bash}
\begin{lstlisting}
make uncrustify
\end{lstlisting}
in a Linux terminal should be called. This command fixes any coding style
errors. After that all changes can be committed.

\section{Subdirectory content description}
\label{sec-subdirectory-content-description}
\begin{description}
\item[librpp.a and rpp-lib.lib] static RPP libraries.

The first one is for POSIX simulation, the second one for Simulink models and
other ARM/TMS570 applications. This files are placed here by the Makefile, when
the library is built.

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

This include the CCS studio project for generation of the static library and the
a test suite. The test suit in this directory does not match the test suite
mentioned later in Chapter 5 and those two suits are going to be merged in the
future. Also other demo Hello World like applications are included as a
reference about how to create a TMS570 application.
	\item[os/] OS layers directory. See OS interchangeable layer for more
information.  
	\item[rpp/] Main directory for the RPP Library.
	\item[rpp/doc/] Documentation directory for the RPP Library.
	\item[rpp/TMS570LS3137.ccxml] Descriptor for code download.

This file is used by all the projects including the Simulink RPP Target for code
download. It is configured to use the Texas Instruments XDS100v2 USB Emulator.
	\item[rpp/TMS570LS313xFlashLnk.cmd] CGT Linker command file.

This file is used by all applications linked for the board, including the
Simulink models, static library and test suite. It includes instructions for the
CGT Linker on where to place sections and size of some sections.
	\item[rpp/include/\{layer\} and rpp/src/\{layer\}] Interface files and
implementations files for given \textsc{\{layer\}}. See Section
\ref{sec-software-architecture} in Chapter \ref{chap-introduction} 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 and this file
only. Also, before using any library function please call \textsc{rpp\_init()}
function for hardware initialization.

	\item[rpp/include/rpp/rpp\_\{mnemonic\}.h] Header file for
\textsc{\{mnemonic\}} module.

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

You may include only selected rpp\_\{mnemonic\}.h header files and call the
specific rpp\_\{mnemonic\}\_init functions, instead of the rpp.h and rpp\_init
function, if you want to use only a subset of the library functions.

	\item[rpp/src/rpp/rpp\_\{mnemonic\}.c] Module implementation.

Implementation of \textsc{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}

The RPP Library can be compiled as a static library using a Code
Composer Studio project. The compilation process will automatically
update the static library in the library root directory.

For the compilation of the library as a static library open the Code
Composer studio project for the rpp-lib (see
Section~\ref{sec-openning-of-existing-project}) and build the project.
If the build process is successful, the \textsc{rpp-lib.lib} file will
appear in the library root directory.

Because compilation of the libraries in Eclipse IDE can be error
prone, there is a \textsc{Makefile} that allows to compile the
libraries from the Linux or Windows command line:

\begin{lstlisting}[language=bash]
cd <library-root>
make
\end{lstlisting}

On Windows use \texttt{gmake.exe} supplied with CCS instead of
\texttt{make}. The rpp-lib CCS project is configured to invoke this
build procedure from IDE rather than using a building compilation
procedure. One of the results is that the compilation is much faster
this way.

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

The relevant aspects for compiling and linking an application using the static
libraries are: 

\begin{itemize}
	\item \textbf{ARM compilation using CCS for the RPP board:}
	\begin{compactitem}
		\item Include headers files of the OS for which the library was
compiled against. At the time of this writing the OS is FreeRTOS 7.0.2. See
Section \ref{sec-software-architecture}
		\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 \textsc{rpp-lib.lib} to the linker libraries.
The RPP library \textbf{MUST} be looked for  before Texas Instruments support
library \textsc{rtsv7R4\_T\_be\_v3D16\_eabi.lib}.
		\item Configure linker to retain \textsc{.intvecs} section from
RPP Library:\newline{}
\textsc{--retain="rpp-lib.lib$\langle$sys\_intvecs.obj$\rangle$(.intvecs)"}
		\item Use the provided linker command file
\textsc{TMS570LS313xFlashLnk.cmd}.  
	\end{compactitem}
	\item \textbf{x86(\_64) compilation using GCC for Simulation:}
	\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 \textsc{librpp.a} to the linker libraries.
		\item Add \textsc{pthread} to the linker libraries.
	\end{compactitem}
\end{itemize}

As an important note, all the models compiled using Simulink will link against
\textsc{rpp-lib.lib}.  When compiling a Simulink model, neither Simulink nor the
\textsc{make} invoked during the build process, will update the generated binary
if the model hasn't changed, and then if the source code hasn't changed. Static
libraries changes are not considered for re-compilation and re-linking. If
library development is being done and static library is updated, in order for
the Simulink model to generate a newly linked version of the binary the whole
code generation folder needs to be deleted in order to force code generation,
compilation and linking with the new static library.

\section{Compiling API documentation}
\label{sec-compiling-api-documentation}
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 \textsc{\repo/rpp/lib/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}

\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 (\textsc{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}[H]\begin{center}
\noindent
\includegraphics[width=300px]{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 Supports only single-tasking and single-rate systems. Support
  for single-rate systems will be available in the final version.
  Support for multitasking system will require careful audit of the
  RPP library with respect to thread-safe code.
\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 \textsc{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 \textsc{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 \textsc{rpp\_download.m} script, which is in turn a
  wrapper on the \textsc{loadti.sh}, \textsc{loadti.bat} and \textsc{loadopenocd.sh} script. More information on the \textsc{loadti.sh}
  script can be found in:
\begin{verbatim}
<css>/ccs_base/scripting/examples/loadti/readme.txt
http://processors.wiki.ti.com/index.php/Loadti
\end{verbatim}

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

  The \textsc{loadopenocd.sh} script will close after the download of the
generated program as well, but the program will be stopped.  In order to test
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 option switches
from Ti loading script \textsc{loadti.sh} to OpenOCD script
\textsc{loadopenocd.sh}. The benefit of using OpenOCD, besides that it is open
source
  software, is much shorter loading time. More information about the right
OpenOCD version and its installation can be found at:
\begin{verbatim}
http://rtime.felk.cvut.cz/hw/index.php/TMS570LS3137#OpenOCD_setup_and_Flashing
\end{verbatim}
This feature is available for Linux system only.

\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-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 TLC files, which defines the blocks for
the Matlab Simulink and \textsc{rpp\_lib.slx}, which is the Simulink RPP
Library, containing all the Simulink blocks for RPP.
	\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{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[width=250px]{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 \textsc{S\_FUNCTION\_NAME}.
  \item Include header file \textsc{header.c}, which in connection with
\textsc{trailer.c} creates a miniframework for writing S-Functions.  
  \item In \textsc{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 \textsc{mdlCheckParameters}:
  \begin{itemize}
	\item Check data type of each parameter.
	\item Check range, if applicable, of each parameter.
  \end{itemize}
  \item In \textsc{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 \textsc{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 \textsc{sfunction\_}
and use lower case mnemonic of the block.

Also a script called \textsc{compile\_blocks.m} is included. The script that
allows all \textsc{sfunctions\_*.c} to be fed to the \textsc{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 \textsc{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 \textsc{.tlc}
extension: \textsc{sfunction\_foo.c} \noindent$\rightarrow$ \textsc{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 \textsc{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 \textsc{Start}: \newline{}
  Code here will be placed in the \textsc{void
$\langle$modelname$\rangle$\_initialize(void)}. Code placed here will execute
only once.
\item \textsc{Outputs}: \newline{}
  Code here will be placed in the \textsc{void
$\langle$modelname$\rangle$\_step(void)} function. Should be used to get the
inputs o a block and/or to set the outputs of that block.
\end{itemize}

The general layout of the TLC files implemented for this project are:
\begin{itemize}
\item In \textsc{BlockTypeSetup}: \newline{}
  Call common function \textsc{\%$<$RppCommonBlockTypeSetup(block, system)$>$} that will include the 
  \textsc{rpp/rpp\i\_mnemonic.h} header file (can be called multiple times but header is included only once).
\item \textsc{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 \textsc{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
\textsc{$\langle$modelname$\rangle$.c} along with other support files in a
folder called \textsc{$\langle$modelname$\rangle$\_$\langle$target$\rangle$/}.
For example, the source code generated for model \textsc{foobar} will be placed
in current Matlab directory \textsc{foobar\_rpp/foobar.c}.

The file \textsc{$\langle$modelname$\rangle$.c} has 3 main functions:
\begin{compactitem}
\item \textsc{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 \textsc{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 \textsc{void $\langle$modelname$\rangle$\_terminate(void)}: \newline{}
  This function is called when terminating the model. This should be used to free memory of revert 
  other operations made on 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}
\includegraphics[width=\textwidth]{images/block_library.png}
\caption{Simulink RPP Block Library.}
\label{fig-block-library}
\end{figure}
\clearpage
\input{block_desc.tex}

\section{Demos}
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{Analog pass-through}
\begin{figure}[H]\begin{center}
\noindent
\includegraphics[width=450px]{images/demo_analog_passthrough.png}
\caption{Analog Passthrough Simulink demo for RPP.}
\end{center}\end{figure}

\textbf{Description:}
This demo will read analog input 1 and write it to analog output 1.

In laboratory the minimum read value for analog input a 0 volts is 107. The maximum read at 12
volts is 2478. The map subsystem will map the input domain (ADC)\textsc{[110, 2400]} to the output domain
(DAC)\textsc{[0, 4095]}.


\subsection{Analog sinewave}
\begin{figure}[H]\begin{center}
\noindent
\includegraphics[width=450px]{images/demo_analog_sinewave.png}
\caption{Analog Sinewave Simulink demo for RPP.}
\end{center}\end{figure}

\textbf{Description:}
This demo will generate a sinewave on analog output 1. The frequency
of the sine wave is 10Hz and sampling rate is set to
1000Hz (driven from Simulink step of 1ms, same as operating system). Amplitude is set to use DAC
full range [0-4095] which means output amplitude will be [0-12] volts.

The Software oscilloscope shown should match an external one connected to DAC 1.

Note that the driver configuration of the MCP4922 is set to unbuffered (which should eventually
be changed to buffered) and thus the last resolution millivolts are lost.


\subsection{CAN transmit}
\begin{figure}[H]\begin{center}
\noindent
\includegraphics[width=450px]{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{CAN demo}

\begin{figure}[H]\begin{center}
\noindent
\includegraphics[width=450px]{images/demo_can_demo.png}
\caption{CAN bus demo for RPP.}
\end{center}\end{figure}

\textbf{Description:}

This demo demonstrates simple processing of received messages.

\subsection{Digital pass-through}
\begin{figure}[H]\begin{center}
\noindent
\includegraphics[width=400px]{images/demo_digital_passthrough.png}
\caption{Digital Pass-through Simulink demo for RPP.}
\end{center}\end{figure}

\textbf{Description:}

This demo will directly pass the digital values read on DIN [1-8] to LOUT [1-8], and thus acting
as a digital pass-through or gateway.

Also note that all the ErrFlag are aggregated on a global ErrFlag.

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

\textbf{Description:}

This demo will echo twice (print back) any character received through the Serial Communication
Interface (9600-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{H-bridge analog control}
\begin{figure}[H]\begin{center}
\noindent
\includegraphics[width=450px]{images/demo_hbridge_analog_control.png}
\caption{H-Bridge Analog Control Simulink demo for RPP.}
\end{center}\end{figure}

\textbf{Description:}

This demo will read values from the analog input, map them, and control the H-Bridge. This allows
a motor connected to the H-Bridge to be controlled with a potentiometer connected to Analog Input 1.

Setting the potentiometer to output around 6 volts will stop the motor. Less (or greater) than 6
volts will trigger the motor in one sense (or in the other sense) and speed proportional with 1\%
resolution.

In laboratory the minimum read value for analog input is 107 at 0 volts. The maximum read at 12 volts
is 2478. The map subsystem will map the input domain (ADC)\textsc{[110, 2400]} to the output domain
(HBR)\textsc{[-1.0, 1.0]}.


\subsection{H-bridge digital control}
\begin{figure}[H]\begin{center}
\noindent
\includegraphics[width=450px]{images/demo_hbridge_digital_control.png}
\caption{H-Bridge Digital Control Simulink demo for RPP.}
\end{center}\end{figure}

\textbf{Description:}

This demo toggle the H-Bridge from stop to full speed in one direction using digital input 1.
So basically is a ON/OFF switch on DIN 1 for a motor connected on the HBR. Note the data type
conversion because the output of the DIN is a boolean and the input to the HBR is a double.

\subsection{H-bridge sine wave control}
\begin{figure}[H]\begin{center}
\noindent
\includegraphics[width=300px]{images/demo_hbridge_sinewave_control.png}
\caption{H-Bridge Sinewave Control Simulink demo for RPP.}
\end{center}\end{figure}

\textbf{Description:}

This demo will generate a sine wave to control the H-Bridge. Sine wave is one period per 20
seconds or 0.05Hz. Sampling rate is 20Hz or 100 samples per 1/4 of period (for 1\% speed
resolution change).

Note that the Software oscilloscope should is not the output of the H-Bridge, the H-Bridge will
change current sense and the duty cycle of the pulse that drive it (PWM), it does not output
analog values. The Software oscilloscope just shows what the input to the HBR block is.

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

\textbf{Description:}

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

\subsection{IRC input}
\begin{figure}[H]\begin{center}

\noindent
\includegraphics[width=450px]{images/demo_irc_input.png}
\caption{LED Blink Simulink demo for RPP.}
\end{center}\end{figure}

\textbf{Description:}

This demo is printing IRC sensor (connected to DIN10 and DIN11) value to the Serial Communication
Interface (115200-8-N-1) with six values to one line.

\subsection{LED blink}
\begin{figure}[H]\begin{center}
\noindent
\includegraphics[width=450px]{images/demo_led_blink.png}
\caption{LED Blink Simulink demo for RPP.}
\end{center}\end{figure}

\textbf{Description:}

This the simplest demo of all that shows the basics of using the RPP target and blocks. The
goal of this demo is to show the configuration of the model (not shown on the picture above),
that is, how the RPP Simulink Coder Target is setup, general model setup and step setup.

This demo will toggle each second a LED connected on LOUT 1. The timing is set by the Simulink
model step which is set to 1 second.

\subsection{LED blink all}
\begin{figure}[H]\begin{center}
\noindent
\includegraphics[width=350px]{images/demo_led_blink_all.png}
\caption{LED Blink All Simulink demo for RPP.}
\end{center}\end{figure}

\textbf{Description:}

This demo will toggle all LEDs connected to the LOUT port. Even outputs pins will be negated.
Toggle will happen each second. The timing is driven by Simulink model step configuration that
is set to 1 second. All blocks ErrFlags are aggregated into one global ErrFlag.

\subsection{Log analog input}
\begin{figure}[H]\begin{center}
\noindent
\includegraphics[width=450px]{images/demo_log_analog_input.png}
\caption{Log Analog Input Simulink demo for RPP.}
\end{center}\end{figure}

\textbf{Description:}

This demo will log once per second the value read on the analog input 1. User can read the log
using the SCI logging integrated command processor (9600-8-N-1). Logging block ID set to 1. The
timing is driven by Simulink model step configuration that is set to 1 second.

\subsection{Power toggle}
\begin{figure}[H]\begin{center}
\noindent
\includegraphics[width=300px]{images/demo_power_toggle.png}
\caption{Power Toggle Simulink demo for RPP.}
\end{center}\end{figure}

\textbf{Description:}

This demo will toggle the power output once per second. If an error is detected on at least one of
the outputs a generic error message is printed to the serial line. The timing is driven by Simulink
model step configuration that is set to 1 second. Power outputs can drive a load up to 2A, so please
take into account required safety considerations.

\subsection{Simulink Demo board}
Model for demo board has 6 subsystems. Every subsystem will be described separately.
\begin{figure}[H]\begin{center}
\noindent
\includegraphics[width=0.8\textwidth]{images/demo_board-connection_scheme.pdf}
\caption{Demo board connection and usage scheme.}
\end{center}\end{figure}

\subsubsection{Potentiometer regulation of motor speed}
This is example of driving motor with input signal. Motor can be rotated in
various speed in both directions and stopping motor means setting potentiometer
to half of its range. Potentiometer value is also transmitted through CAN.

\subsubsection{Color music}
This is showing abilities of RPP board to generate analog signals. Bargraphs on
demo board are showing value of analog outputs. Speed of change can be changed
with potentiometer and in one case is used motor 2 IRC. There are five different
modes. Three of them are derived from sinus and rest of them are counter value
and direct control. Modes can be changed with black button. First mod selected
after board start is fifth.  
\begin{enumerate}
\item Sinus signal is sequential delayed by 10 steps for second and third bargraph.
\item Sinus signal on second bargraph is shifted by 120° and on third one is shifted by 240°.
\item Sinus signal for second and third bargraphs are shifted same as in
previous mode, but as counter value is used IRC value with appropriate divider
no potentiometer value.  
\item Visualizing counter value which speed is changed
with potentiometer.
\item Potentiometer value is passed to all bargraphs with appropriate multiplier.
\end{enumerate}

\subsubsection{Buttons and LEDs}
This is example of digital input/output. LEDs on demo board can be driven with
four different subprograms. These subprograms can be changed with red button and
are influenced with green and blue buttons.  
\begin{enumerate}
\item One LED is always ON and others are OFF. Every 0.1 sec is neighborhood LED
switched on and previous one is switched off. With buttons you can change
direction.  
\item Same as previous mode, but change is not done after 0.1 sec
but only when button is pressed.
\item In this mode you can record message in Morse code (max 64 chars including
spaces) and after delay it is repetitively replayed. To record message use green
button as dash and blue button as dot.  
\item Simple game in which you must determine if light is moving left or right
and press green or blue button according to it. Speed of movement is increasing
and in case of wrong answer or long delay is game ends with lights flashing.
\end{enumerate}

\subsubsection{IRC to CAN}
IRC value from Motor 2 is sent every tenth step via CAN2 with message ID 0x4.

\subsubsection{CAN receive -- Button press emulation}
You can simulate press of all four buttons by sending message through CAN2 to
board with message ID 0x0 and value according to button number.

\subsubsection{Configuration and error handling}
RPP supports some basic runtime error handling. Every block can set its error
flag, all these error flags are joined in this demo together and when some
problem is detected CAN2 message of ID 0x10 is transmitted. Also in case of
board overrun (exhaustion of time quanta) is transmitted message through CAN2
with ID 0x11.\\ When model is build without external mode, errors are also
printed to SCI.

\subsubsection{Full list of CAN communication}
The board produces CAN frames with the following IDs:
\begin{itemize}
\item 0x05: Potentiometer 1 value.
\item 0x06: Potentiometer 2 value.
\item 0x08: Selected mod of color music.
\item 0x09: Active subprogram of buttons and LEDs.
\item 0x10: Transmitted only in case of error flag of some block, error code.
\item 0x11: Transmitted only in case of board overrun, no data.
\end{itemize}
The board reacts to CAN frames with following IDs:
\begin{itemize}
\item 0x00: Simulate button press, accepts value 1--4.
\end{itemize}

\chapter{Command line testing tool}
\label{chap-rpp-test-software}
The \textsc{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 a 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 separated module.

The command processor is implemented in <rpp-test-sw>/cmdproc and commands
modules are implemented in <rpp-test-sw>/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:

\begin{verbatim}
TODO: FILL
\end{verbatim}

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

\section{Command 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.

\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[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[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[LIN]
  \textit{Local Interconnect Network.} \newline{}
  The LIN is a serial network protocol used for communication between components in vehicles.
  In this project it is also used as mnemonic to refer to or something related to the LIN
  hardware module.

\item[LOUT]
  \textit{Logic Output.} \newline{}
  Mnemonic to refer to or something related to the digital output hardware module.
  It is logic output (100mA), as opposed to power outputs (2A, 10A).

\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[MOUT]
  \textit{(Motor) Power Output.} \newline{}
  Mnemonic to refer to or something related to the 2A push/pull power output hardware module.

\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 automotive hardware board. Also generic term to define something related
  to the board, like the RPP Library, RPP Layer, RPP API, etc.

\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}

\bibliography{rpp_simulink}
\bibliographystyle{plain}

\end{document}

%  LocalWords:  FreeRTOS RPP POSIX
