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

\documentclass{article}

\usepackage{graphicx} % images and graphics
\usepackage{paralist} % needed for compact lists
\usepackage[normalem]{ulem} % needed by strike
\usepackage{listings} % required for code blocks
\usepackage[urlcolor=blue,colorlinks=true,hyperfootnotes=false]{hyperref} % links
\usepackage[utf8]{inputenc}  % char encoding
\usepackage[bottom]{footmisc} % footnotes

% 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
\addtolength{\parskip}{\baselineskip} % Paragraph spacing
\linespread{1.15} % Lines spacing
\setlength{\plitemsep}{0.5\baselineskip} % List items spacing
\definecolor{deepblue}{RGB}{0,0,61}
\hypersetup{linkcolor=deepblue,}

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

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

\begin{document}

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

\begin{titlepage}
\begin{center}

% Upper part of the page
\includegraphics[width=0.70\textwidth]{media/images/logos.png}\\[1cm]
\textsc{\LARGE Costa Rica Institute of Technology}\\[0.5cm]
\textsc{\LARGE Czech Technical University in Prague}\\[1.5cm]
\textsc{\Large Undergraduate project}\\[0.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{Author:}\\
Carlos \textsc{Jenkins}\\

\vfill

% Bottom of the page
{\large \today}

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

\tableofcontents

\newpage

\listoffigures

\newpage

\hypertarget{introduction}{}
\section{Introduction}

This document describes the final results of the project ``Code generation for automotive rapid
prototyping platform using Matlab/Simulink".

\hypertarget{background}{}
\subsection{Background}

Back in the beginning of 2012 a leading automotive company requested the Czech Technical University
to develop a Engine Control Unit (ECU) for automotive applications. Real-Time Systems group at the
Department of Control Engineering from the Faculty of Electrical Engineering developed a hardware
and Software platform to the needs of this industry. The hardware uses Texas Instruments
TMS570LS3137 CPU and is built with automotive standards and interfaces in mind. It uses a real-time
operating system and was directly programmed in C.

Nevertheless, in accordance to company policies the Software developed for the engine control unit
must be designed in a safe and auditable way. The company has the policy to implement the Software
for their system using Model-Based Design:

	\begin{quotation}
Model-Based Design (MBD) is a mathematical and visual method of addressing
problems associated with designing complex control, signal processing and
communication systems. It is used in many motion control, industrial equipment,
aerospace, and automotive applications. Model-based design is a methodology
applied in designing embedded software.
	\end{quotation}

In order to meet this requirement an interaction layer between the platform and the Software the
company uses, Matlab/Simulink, must be implemented. This document describes the implementation of
this interaction system.

\hypertarget{technologies_involved}{}
\subsection{Technologies involved}

\begin{compactenum}
\item Matlab/Simulink data flow graphical programming language tool for modeling, simulating and
  analyzing multidomain dynamic systems.
\item Standard ANSI C programming.
\item FreeRTOS real-time operating system.
\item Texas Instruments TI Code Generation Tools (CGT).
\item RPP in-house automotive hardware board using Texas Instruments TMS570LS3137 CPU.
\end{compactenum}

\newpage

\hypertarget{objectives}{}
\subsection{Objectives}

Main objectives of this project are:

\begin{compactenum}
\item Allow C code generation from Matlab/Simulink models for custom made hardware platform.
\item Implement model blocks for some of the peripheral units of the board for use in Simulink
  programming.
\end{compactenum}

At the time of this writing the objectives of this project are considered successfully achieved.

\hypertarget{benefits}{}
\subsection{Benefits}

Expected benefits of this project are:

\begin{compactenum}
\item Enabling faster implementation and rapid-prototyping of Software components through the use of
  model-based programming.
\item Enabling better and clearer visualization of Software implementations for the hardware board
  through models.
\item Improve auditability of Software system for automotive applications.
\end{compactenum}

At the time of this writing the benefits of this project are considered enabled.

\hypertarget{final_outcome}{}
\subsection{Final outcome}

The main products generated for this project are:

\begin{itemize}
\item \textbf{C Support Library}: \newline{}
  Define the API to communicate with the board. Include drivers and operating system.

\item \textbf{Simulink Coder Target}: \newline{}
  Allows Simulink model's code generation, compilation and download for the board.

\item \textbf{Simulink Block Library}: \newline{}
  Set of blocks that allows Simulink models to use board IO and communication peripherals.

\item \textbf{Simulink Demos Library}: \newline{}
  Collection of examples of control applications in form of Simulink models.
\end{itemize}

Each of this product is described deeply in the following sections.

\newpage

\hypertarget{document_layout}{}
\subsection{Document layout}

The general layout of this document is as follows:

\begin{compactitem}
\item Project description, objectives and outcome. This section.
\item Software and Hardware setup for development, repository layout and programming standards.
\item A section for each of the four products delivered, with:
 \begin{compactitem}
 \item Implementation fundamentals.
 \item Repository branch description.
 \item Product specific aspects.
 \item Reference documentation.
 \end{compactitem}
\item Glossary.
\item References.
\item Appendices.
\end{compactitem}

\newpage

\hypertarget{project_setup}{}
\section{Project setup}

This sections describes the Software and Hardware aspects required to undertake development for
this project. It considers:

\begin{compactitem}
\item Software development environment.
\item Hardware reference documentation and wiring for development.
\item Repository's general layout.
\end{compactitem}

\hypertarget{development_environment}{}
\subsection{Development environment}

This section describes the Software environment setup for development.

\hypertarget{operating_system}{}
\subsubsection{Operating system}

This project was developed on a GNU/Linux operating system. For development it is recommended to
use a Debian based operating system for development as most of the tools are easily available from
repositories.

Relevant OS information on which this project was developed:

\begin{compactitem}
\item Ubuntu 12.04.2 LTS AMD64.
\item Kernel 3.2.0-48-generic.
\item GCC version 4.6.3.
\end{compactitem}

No test for cross-platform interoperability was performed on the code developed. Although care was
taken to try to provide platform independent code and tools there is elements known to be Linux
dependent. For a list of this elements refer to
\htmladdnormallink{Appendix B: Known operating-system dependent files}{\#appendix\_b\_known\_operating\_system\_dependent\_files}.

\hypertarget{version_control_system}{}
\subsubsection{Version Control System}

The version control system used for this project is \textbf{git}. The repository of this project
contains all the files produced during development, including documentation, references, code and
graphics. Also, the GUI application \textbf{giggle} was used to easily review changes. To install both
execute on a terminal:

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

\newpage

\hypertarget{ti_code_composer_studio}{}
\subsubsection{TI Code Composer Studio}

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.

The version used in this project is the 5.3.0. Download and install CCS for Linux from:

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

CCS download requires a valid MyTI account. Tedious. CCS download is about 1.5GB. Once downloaded
extract the content of the \texttt{tar.gz} archiver and run \texttt{css\_setup\_$<$version$>$.bin} script as
\underline{root}. Installation must done as root in order to install driver set.

After installation the application can be executed with:

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

If the application fails to start on 64bits systems is because CCS5 is a 32bits application a 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 \texttt{org.eclipse.ui/showIntro} to false.

Choose ``FREE License - for use with XDS100 JTAG Emulators" on the licensing options. Code download
for the board is uses that particular hardware. See \htmladdnormallink{Development wiring}{\#development\_wiring} for
more details on this hardware.

CCS include Texas Instruments Code Generation Tools (CGT) (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. \newline{}
See \texttt{$<$repo$>$/rpp/rpp/README.txt} file for more information.

You can find documentation for CGT compiler in \texttt{$<$repo$>$/ref/armcl.pdf} and for CGT archiver in
\texttt{$<$repo$>$/ref/armar.pdf}.

\hypertarget{matlabsimulink}{}
\subsubsection{Matlab/Simulink}

Matlab/Simulink version used is R2012b for Linux 64 bits. For in-house development the CVUT should
provide a network licensing server descriptor file.

\hypertarget{gtkterm}{}
\subsubsection{GtkTerm}

Most of the interaction with the board for development is done through a RS-232 serial connection.
The terminal Software used for communication is called GtkTerm.

The default configuration for the board serial communication module is 9600-8-N-1. Note that the
RPP Library test suite is setup to 115200-8-N-1.

To install GtkTerm execute:

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

\hypertarget{doxygen}{}
\subsubsection{Doxygen}

Doxygen is the name of the documentation generator used to generate the RPP API documentation based
on the source code files. The generated API include dependency graphs and thus it also requires
Graphviz, a graph drawing tool. To install both execute:

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

See \htmladdnormallink{API generation}{\#api\_generation} on how to use Doxygen to generate the API Reference
documentation.

\newpage

\hypertarget{nested}{}
\subsubsection{Nested}

Nested is the documentation editor used to create the document you're reading. It features a plain
text version control friendly simple to read non-cluttered format, WYSIWYM paradigm, divide and
conquer document creation approach, a nested (non-linear) document tree and content/presentation
separation scheme and thus documents can be published to LaTeX, PDF or HTML. Nested is a tool
created by the author of this report.

To install Nested first install dependencies:

\lstset{language=bash}
\begin{lstlisting}
sudo apt-get install python2.7 python-gtk2 python-webkit python-gtkspellcheck texlive-publishers texlive texlive-latex-extra rubber iso-codes subversion
\end{lstlisting}

Then get the latest revision from the stable repository:

\lstset{language=bash}
\begin{lstlisting}
svn checkout svn://svn.code.sf.net/p/nestededitor/code/trunk nested
\end{lstlisting}

Run Nested with:

\lstset{language=bash}
\begin{lstlisting}
cd nested/nested/
./nested
\end{lstlisting}

Nested sources for this document can be found on the repository under
\texttt{$<$repo$>$/doc/reports/report/}.

\hypertarget{lmc1}{}
\subsubsection{LMC1}

The LMC1 is a simple script developed for this project written in Python 3 using Gtk+ 3.0 Python
dynamic bindings PyGObject. This script, based on Michal Horn's command line script, allows to set
or clear the outputs of the test board.

This script includes both a GUI and command line tool. If no parameters are given to the script the
GUI version is launched:

\begin{figure}[H]\begin{center}

\noindent\includegraphics[width=350px]{media/images/lmc1.png}
\caption{LMC1 GUI application.}\end{center}\end{figure}

To run the LMC1 application first install dependencies:

\lstset{language=bash}
\begin{lstlisting}
apt-get install python3 python3-gi python3-serial
\end{lstlisting}

To launch LMC1 GUI version double click file:

\texttt{$<$repo$>$/rpp/lib/apps/lmc1/lmc1.py}

To launch LMC1 command line version type:

\texttt{$<$repo$>$/rpp/lib/apps/lmc1/lmc1.py --help}

\newpage

\hypertarget{hardware_reference}{}
\subsection{Hardware reference}

This section provides reference documentation for the RPP board:

\begin{compactitem}
\item Connectors pinout.
\item Modules capabilities and features.
\item Wiring configuration for development and testing.
\end{compactitem}

Please note that although this is a hardware reference documentation this is from a Software
development perspective and \underline{\textbf{NOT}} Hardware development perspective. For full hardware details
please refer to schematics and related documentation.

\begin{figure}[H]\begin{center}

\noindent\includegraphics[width=300px]{media/images/board.png}
\caption{The RPP board (signal connector missing).}\end{center}\end{figure}

\hypertarget{connectors_pinout}{}
\subsubsection{Connectors pinout}

\begin{figure}[H]\advance\leftskip-1cm

\noindent\includegraphics[width=530px]{media/images/pinout.pdf}
\caption{The RPP connectors pinout.}\end{figure}

\hypertarget{modules_description}{}
\subsubsection{Modules description}

This section enumerates the capabilities of the hardware modules from Software perspective.

\hypertarget{logic_io}{}
\paragraph{Logic IO}\textnormal{\\}

\hypertarget{digital_inputs_din}{}
\subparagraph{Digital Inputs (DIN)}\textnormal{\\}

\begin{compactitem}
\item 16 pins available on Signal Connector.
\item Pins 9-16 status can be read via GPIO using configurable threshold. \newline{}
  Pins 9-12 use variable threshold B and pins 13-16 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 1-8 are programmable pins and ca be set to pull-up or pull-down. 9-16 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}

\hypertarget{digital_outputs_lout}{}
\subparagraph{Digital Outputs (LOUT)}\textnormal{\\}

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

\hypertarget{analog_input_ain}{}
\subparagraph{Analog Input (AIN)}\textnormal{\\}

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

\hypertarget{analog_output_aout}{}
\subparagraph{Analog Output (AOUT)}\textnormal{\\}

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

\hypertarget{power_output}{}
\paragraph{Power Output}\textnormal{\\}

\hypertarget{h_bridge_hbr}{}
\subparagraph{H-Bridge (HBR)}\textnormal{\\}

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

\hypertarget{power_output_mout}{}
\subparagraph{Power Output (MOUT)}\textnormal{\\}

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

\hypertarget{high_power_output_hout}{}
\subparagraph{High-Power Output (HOUT)}\textnormal{\\}

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

\hypertarget{communication}{}
\paragraph{Communication}\textnormal{\\}

\hypertarget{can_bus_can}{}
\subparagraph{CAN bus (CAN)}\textnormal{\\}

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

\hypertarget{local_interconnect_network_lin}{}
\subparagraph{Local Interconnect Network (LIN)}\textnormal{\\}

\begin{compactitem}
\item 2 ports/pins available on Communication Connector.
\item Only first port can be used when using the SCI. Second port us shared with SCI.
\end{compactitem}

\hypertarget{flexray_fr}{}
\subparagraph{FlexRay (FR)}\textnormal{\\}

\begin{compactitem}
\item 2 ports available. FlexRay uses differential signaling thus 4 pins are available on
  Communication Connector.
\end{compactitem}

\hypertarget{serial_comm_interface_sci}{}
\subparagraph{Serial Comm. Interface (SCI)}\textnormal{\\}

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

\hypertarget{ethernet_eth}{}
\subparagraph{Ethernet (ETH)}\textnormal{\\}

\begin{compactitem}
\item 1 port available. Standard Ethernet connector available inside box.
\end{compactitem}

\newpage

\hypertarget{data_storagelogging}{}
\paragraph{Data storage/logging}\textnormal{\\}

\hypertarget{external_memory_sd_ram_sdr}{}
\subparagraph{External Memory SD-RAM (SDR)}\textnormal{\\}

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

\hypertarget{sd_card_sdc}{}
\subparagraph{SD Card (SDC)}\textnormal{\\}

\begin{compactitem}
\item Standard SD-Card connector or microSD connector available inside box.
\item Communication done using SPI.
\end{compactitem}

\newpage

\hypertarget{development_wiring}{}
\subsubsection{Development wiring}

For development, the RPP board needs to be wired as follow:

\begin{compactitem}
\item \textbf{Power input}: supply around 13 volts on any PWR pin (Power and Communication connectors) and 
  connect GND to power supply's GND. See \htmladdnormallink{Connectors pinout}{\#connectors\_pinout}.
\item \textbf{Serial communication}: board serial interface connected to a RS-232 port on the host computer 
  (\texttt{/dev/ttySX}) or to a USB converter (\texttt{/dev/ttyUSBX}).
\item \textbf{Debug and code download}: XDS100v2 JTAG Emulator connected to RPP board JTAG connector, 
  which in turn is connected through USB to the host computer (\texttt{/dev/ttyUSBX}). 
  See below on details for configuring the XDS100v2 on Linux.
\end{compactitem}

Image of the wiring:

\begin{figure}[H]\begin{center}

\noindent\includegraphics[width=300px]{media/images/dev_wiring.png}
\caption{RPP Wiring for Development.}\end{center}\end{figure}

Setup XDS100v2 on Linux:

By default the device (if nothing more connected then \texttt{/dev/ttyUSB0}) is added with permissions 
\texttt{664} and \texttt{root} as user and group. To access the device write access for current user is 
required. To do so create a new udev rule file:

\lstset{language=bash}
\begin{lstlisting}
sudo nano /etc/udev/rules.d/45-pes-rpp.rules
\end{lstlisting}

\newpage
And add line:

\lstset{language=}
\begin{lstlisting}
SUBSYSTEM=="usb", ATTR{idVendor}=="0403", ATTR{idProduct}=="a6d0", MODE="0660", GROUP="plugdev"
\end{lstlisting}

Then reload udev rules with:

\lstset{language=bash}
\begin{lstlisting}
sudo udevadm control --reload-rules
\end{lstlisting}

To check device properties like \texttt{idVendor} or \texttt{idProduct} issue the following command:

\lstset{language=bash}
\begin{lstlisting}
udevadm info -a -p $(udevadm info -q path -n /dev/ttyUSB0)
\end{lstlisting}

\hypertarget{test_wiring}{}
\subsubsection{Test wiring}

Wiring for test differ from testing objectives. It test performed for this project no communication
test, besides SCI, was performed. The following describes how to wire each of the modules tested:

\begin{compactitem}
\item \textbf{DIN}: \newline{}
  Connect all DIN pins to one LMC1 board outputs.
\item \textbf{LOUT}: \newline{}
  Connect all LOUT pins to one LMC1 board inputs.
\item \textbf{AIN}: \newline{}
  Connect all low pins to GND and leave all high pins floating. Allow to hook a potentiometer
  to each pin.
\item \textbf{AOUT}: \newline{}
  Connect all 4 pins to different channels on a oscilloscope.
\item \textbf{HBR}: \newline{}
  Connect a motor to the H-bridge pins.
\item \textbf{MOUT}: \newline{}
  Connect all 6 pins to a LMC1 board inputs. Another option is to connect a motor to one of the 
  outputs.
\item \textbf{SCI}: \newline{}
  Connect the SCI to a host computer. See \htmladdnormallink{Development wiring}{\#development\_wiring}.
\item \textbf{SDR}: \newline{}
  No particular wiring is required for testing the SD-RAM.
\end{compactitem}

It is recommended to setup a power bus using regulated 12volts from Signal Connector. Power the 
LMC1 boards and the potentiometer with this bus. The LCM1 controller board should be connected
to the host computer through a RS-232 port or a USB converter.

\newpage

\begin{figure}[H]\advance\leftskip-1cm

\noindent\includegraphics[width=530px]{media/images/test_wiring.png}
\caption{RPP Wiring for Testing.}\end{figure}

\newpage

\hypertarget{project_repository}{}
\subsection{Project repository}

This git repository holds all the work done on this project.

To get the repository:

	\begin{quotation}
\texttt{git clone ssh://git@rtime.felk.cvut.cz/jenkicar/rpp-simulink.git}
	\end{quotation}

This is a private repository, you require your SSH private key to be authorized. For access please
consult the Real-Time Systems Group, Department of Control Engineering, Faculty of Electrical
Engineering, Czech Technical University in Prague. For details about this git server refer to:

	\begin{quotation}
\htmladdnormallink{http://rtime.felk.cvut.cz/hw/index.php/Git\_repository\_on\_this\_server}{http://rtime.felk.cvut.cz/hw/index.php/Git\_repository\_on\_this\_server}
	\end{quotation}

The general layout of the repository is:

\begin{verbatim}
        .
        |__ doc         - Documentation created for this project.
        |__ refs        - Official reference documentation.
        \__ rpp
            |__ blocks  - Simulink Block Set.
            |__ demos   - Simulink Demos Library.
            |__ lib     - C support Library and API.
            \__ rpp     - Simulink Coder Target.
\end{verbatim}

A detailed description of the content of each subfolder under \texttt{rpp/} can be found in the section
\textit{Subdirectory content description} on each dedicated section for the products developed.

In this document, the root folder on this repository is used as reference for file location and is
referred with the token \texttt{$<$repo$>$}.

\newpage

\hypertarget{c_support_library}{}
\section{C Support Library}

The RPP C Support Library define the API to communicate with the board. It include drivers and
operating system. This section documents the implementation of this library.

\hypertarget{description}{}
\subsection{Description}

The RPP Library is the support library used by Simulink models. It 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 as a concept and as a functional unit was introduced by this project. At the beginning
of this project the RPP board had just one application developed for. This application intended for
board testing allows the user to issue low-level commands to control and test the peripherals of
the board. This application was created using a combination of custom code, contributed drivers and
generated code from TI tool HalCoGen. Library functionality, like drivers and hardware access, and
application logic, like command processor and test routines, was largely merged in a single layer,
166 source code files long highly coupled application. In order to develop independent applications
for the RPP board, as it was expected to be each Simulink model, the library logic needed to be
separated from the application logic. This work implied a heavy refactoring on the testing
application in order extract from it the library functionality. Because the application files were
highly coupled in a single layer the refactoring and testing of the library implied roughly 70\% of
the work done on this project.

\begin{figure}[H]\advance\leftskip-1cm

\noindent\includegraphics[width=500px]{media/images/adc_dep_before.png}
\caption{Dependency graph of the ADC driver before refactoring.}\end{figure}

The above graph shows the dependencies of the ADC driver before the refactoring. Please note the
dependency on \texttt{cmdproc\_io\_tisci.h} and \texttt{cmdproc.h}, both application level modules. Also, note
the indirect dependency on the Operating System is being resolved through the application modules.

\begin{figure}[H]\begin{center}

\noindent\includegraphics[width=150px]{media/images/adc_dep_after.png}
\caption{Dependency graph of the ADC driver after refactoring.}\end{center}\end{figure}

The above graph shows the current dependencies for the ADC driver in the RPP Library. Please note
that it dependents only on the system layer low-level driver and that the Operating System indirect
dependency is resolved through the library foundations \texttt{base.h}.

Some other relevant changes introduced with the refactoring are:

\begin{compactitem}
\item ADC driver was completely rewritten.
\item MOUT driver was implemented.
\item DIN driver was slightly modified and extended.
\item DAC driver was slightly modified.
\item HBR driver was largely modified (in particular watchdog functionality).
\item SCI driver was refactored and extended.
\item SDR driver was implemented.
\end{compactitem}

Also, once the library functionality could be isolated, the resulting API was too low-level to be
used by applications, in consequence one of the contributions of this projects was the
implementation of a high-level API on top of this low level API: the RPP Layer.

\newpage

\hypertarget{architecture}{}
\subsubsection{Architecture}

The RPP library was structured into 5 layers with the following guidelines:

\begin{compactitem}
\item Top-down dependency only. No lower layer depends on anything from upper layers.
\item 1-1 layer dependency only. The top layer depends exclusively on the bottom layer, not on any
  lower level layer (except for a couple of exceptions).
\item Each layer should provide a unified layer interface (\texttt{rpp.h}, \texttt{drv.h}, \texttt{hal.h}, \texttt{sys.h}
  and \texttt{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]{media/images/layers.pdf}
\caption{The RPP library layers.}\end{center}\end{figure}

As a consequence of this division the source code files and interface files are now placed on
private directories so the previous prefix based inclusion \texttt{drv\_din.h} is replaced by
\texttt{drv/din.h}. With this organization user applications only needs to include the top layer
interface file (\texttt{rpp/rpp.h}) to be able to use the library API.

Please note the sublayer uLut, which is used only by the SPI driver in order to use thread safe
queue mechanisms. Because the FreeRTOS already provides thread safe queues and in order to match
the order parts of the system it would be advisable to drop this dependency in the future.

\newpage

\hypertarget{rpp_layer_modules}{}
\subsubsection{RPP Layer Modules}

The RPP Layer was structured into 14 different modules from 4 different categories that match the
hardware modules on the board:

\begin{center}\begin{tabular}{lll}
\textbf{Category} & \textbf{Description} & \textbf{MNEMONIC} \\
Logic IO & Digital Input & \texttt{[DIN ]} \\
 & Digital (Logic) Output & \texttt{[LOUT]} \\
 & Analog Input & \texttt{[AIN ]} \\
 & Analog Output & \texttt{[AOUT]} \\
Power output & H-Bridge output & \texttt{[HBR ]} \\
 & Power output (12V, 2A) & \texttt{[MOUT]} \\
 & High-Power output (12V, 10A) & \texttt{[HOUT]} \\
Communication & CAN Bus & \texttt{[CAN ]} \\
 & LIN (Local Interconnect Network) & \texttt{[LIN ]} \\
 & FlexRay & \texttt{[FR  ]} \\
 & Serial Communication Interface & \texttt{[SCI ]} \\
 & Ethernet & \texttt{[ETH ]} \\
Logging & SD Card & \texttt{[SDC ]} \\
 & SD-RAM & \texttt{[SDR ]} \\
\end{tabular}\end{center}

Please note the mnemonic of each module, as they are constantly used on the Software and
documentation. Also note that only the following modules were implemented as part of this project:

\begin{multicols}{2}

\begin{compactitem}
\item DIN.
\item LOUT.
\item AIN.
\item AOUT.
\item HBR.
\item MOUT.
\item SCI.
\item SDR.
\end{compactitem}

\end{multicols}

Modules for which there is a low-level API available on the library but no high-level module was
implemented:

\begin{multicols}{2}

\begin{compactitem}
\item CAN.
\item LIN.
\item FR.
\end{compactitem}

\end{multicols}

Modules that are not yet available on the library at all:

\begin{multicols}{2}

\begin{compactitem}
\item ETH (in the works).
\item SDC.
\item HOUT (partial).
\end{compactitem}

\end{multicols}

The following graphic shows the library modules and the connectors on the hardware they map to.

\begin{figure}[H]\advance\leftskip-1cm

\noindent\includegraphics[width=500px]{media/images/blocks.pdf}
\caption{The RPP layer modules.}\end{figure}

\newpage

\hypertarget{os_interchangeable_layer}{}
\subsubsection{OS interchangeable layer}

The OS Layer is composed by the FreeRTOS source code files. Because the FreeRTOS exposes an stable
API the OS layer can be changed in order to upgrade the Operating System or use a different port of
the OS, without changing the upper layers source code. The OS Layers currently available for the
RPP Library at \texttt{$<$repo$>$/rpp/lib/os/} at the time of this writing are:

\begin{compactitem}
\item Version 6.0.4 using POSIX port. This layer is the one that should be used when compiling a
  program for x86(\_64) simulation. The port uses the \texttt{pthread} library and because of this the
  port is not true real time and this is considered a simulator.
\item Version 7.0.2 using HalCoGen port for TMS570. This layer is the one currently supported and
  tested. It was originally included in the testing application and was generated by an older
  version of TI code generation tool HalCoGen.
\item Version 7.4.0 using HalCoGen port for TMS570. This layer was extracted from a newly generated
  project using a newer version of HalCoGen. This layer is untested but \textit{should} work out of the
  box.
\item Version 7.4.2 using ARM Cortex R4 official port for CCS. This layer was created from vanilla
  FreeRTOS 7.4.2 release. It is tested but non-working. Ticks are proved to be executed in time but
  applications using this kernel runs at full-speed. The reason if this is currently unknown.
\end{compactitem}

The general layout of all the layers are as following:

\begin{itemize}
\item Common source code (kernel):

\begin{verbatim}
    src/os/croutine.c (Optional)
    src/os/list.c
    src/os/queue.c
    src/os/tasks.c
    src/os/timers.c (Optional)
\end{verbatim}


Originally found in vanilla distribution in: \texttt{$<$FreeRTOSRoot$>$/FreeRTOS/Source}

\item Common interface files:

\begin{verbatim}
    include/os/croutine.h
    include/os/FreeRTOS.h
    include/os/list.h
    include/os/mpu_wrappers.h
    include/os/portable.h (with minor editions)
    include/os/projdefs.h
    include/os/queue.h
    include/os/semphr.h
    include/os/StackMacros.h
    include/os/task.h
    include/os/timers.h
\end{verbatim}


Originally found in vanilla distribution in: \texttt{$<$FreeRTOSRoot$>$/FreeRTOS/Source/include}

\item Memory management file:

\begin{verbatim}
    src/os/heap.c (One of 4 version available, see Appendix A).
\end{verbatim}


Originally found in vanilla distribution in: \texttt{$<$FreeRTOSRoot$>$/FreeRTOS/Source/portable/MemMang}

\item Port specific files:

\begin{verbatim}
    src/os/port.c
    src/os/portASM.asm
    include/os/portmacro.h
    include/os/FreeRTOSConfig.h
\end{verbatim}


This depend of the port. In the case of the 7.4.2 TMS570 / ARM Cortex R4 for CCS port:

 \begin{compactitem}
 \item First three files can be found in vanilla distribution in \newline{}
   \texttt{$<$FreeRTOSRoot$>$/FreeRTOS/Source/portable/CCS/ARM\_Cortex-R4}.
 \item Last file in \texttt{$<$FreeRTOSRoot$>$/FreeRTOS/Demo/CORTEX\_R4\_RM48\_TMS570\_CCS5}.
 \end{compactitem}
\end{itemize}

In general, the following changes were applied to the source code base of all kernels:

\begin{itemize}
\item Replaced include directives to adapt to RPP library standard:

\texttt{\#include "} with \texttt{\#include "os/}

\item Line ending character set to UNIX '$\backslash$n' and tabs replaced by 4 spaces.
\end{itemize}

\newpage

\hypertarget{api_development_guidelines}{}
\subsubsection{API development guidelines}

\vspace{-0.40cm}

The following are the development guidelines use 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 on the headers files is for public functions only. Do not declare
  local/static/private functions on the header.
\item Documentation on source code files should be non-doxygen formatted and intended for developers,
  not users. Documentation here is optional and at the discretion of the developer.
\item Always use standard data types for IO when possible. Use custom structs as very last resort.
\item Use prefix based functions names to avoid clash. The prefix is of the form \texttt{[layer]\_[module]\_},
  for example \texttt{rpp\_din\_update()} for the update function of the DIN module in the RPP Layer.
\item To be very careful about symbol export. Because it is used as a static library the modules should
  not export any symbol that is not intended to be used (function) or \texttt{extern}'ed (variable) from
  application. As a rule of thumb declare all global variables as static.
\item Only the RPP Layer symbols are available to user applications. All information related to lower
  layers is hidden for the application. This is accomplished by conditionally including the layers
  elements on the implementations files only and never on the interface files. Never expose any
  other layer to the application or the the whole system below that layer will be exposed. In other
  words, never \texttt{\#include "foo/foo.h"} in any RPP Layer interface file.
\item Any module is conditionally included by using \texttt{rppCONFIG\_INCLUDE\_\{MNEMONIC\}} directive on the
  \texttt{RppConfig.h} configuration file.
\end{compactitem}

\vspace{-0.40cm}

\hypertarget{further_improvements}{}
\subsubsection{Further improvements}

\vspace{-0.40cm}

The following are recommendations for future improvements of the library:

\begin{compactitem}
\item General code revision to remove local-only methods and variables from being exported.
\item General code revision and refactoring to normalize the functions naming scheme. Normalize DRV and
  HAL to use prefix based scheme, not all the functions and exported variables do. Refactor the SYS
  layer, most of it generated by HalCoGen and that uses \texttt{thisNamingScheme} to use library
  standards (see \htmladdnormallink{RPP API}{\#rpp\_api} programming standards).
\item Simplify doxygen documentation on the SYS layer, because is clunky, doesn't add any value and is
  repetitive. Move it to the header files.
\item Remove error throwing from wrong parameter input in the DRV layer and assume a
  \textit{correct parameter and continue} safe approach. Move all error throwing and validation to the
  RPP layer (already implemented).
\end{compactitem}

\vspace{-0.40cm}

Recommendations for changes on the electrical diagrams:

\begin{compactitem}
\item Change name of GPIO MOUT1\_EN to MOUT1\_DIAG.
\item Change name of GPIO MOUT1\_IN to MOUT1\_EN.
\end{compactitem}

The current names are misleading.

\hypertarget{subdirectory__content_description}{}
\subsection{Subdirectory  content description}

\noindent$\rightarrow$ \texttt{librpp.a} and \texttt{rpp-lib.lib}

Version controlled RPP static 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 projects \texttt{apps/rpp-lib\_posix} and
\texttt{apps/rpp-lib} when built.

\noindent$\rightarrow$ \texttt{apps/}

Applications related to the RPP library.

This include the CCS studio project for generation of the static library and the test suite. See
\htmladdnormallink{Static libraries}{\#static\_libraries}, \htmladdnormallink{Test Suite}{\#test\_suite} and
\htmladdnormallink{Base application}{\#base\_application} for more information.

\noindent$\rightarrow$ \texttt{os/}

OS layers directory.

See \htmladdnormallink{OS interchangeable layer}{\#os\_interchangeable\_layer} for more information.

\noindent$\rightarrow$ \texttt{rpp/}

Main directory for the RPP Library.

\noindent$\rightarrow$ \texttt{rpp/doc/}

Documentation directory for the RPP Library. See \htmladdnormallink{API generation}{\#api\_generation} for more
information.

\noindent$\rightarrow$ \texttt{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. See
\htmladdnormallink{Development wiring}{\#development\_wiring} for information about this hardware.

\noindent$\rightarrow$ \texttt{rpp/TMS570LS313xFlashLnk.cmd}

CGT Linker command file.

This file is used by all applications linking 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.

\noindent$\rightarrow$ \texttt{rpp/include/\{layer\}} and \texttt{rpp/src/\{layer\}}

Interface files and implementations files for given \texttt{\{layer\}}. See below for details on the RPP 
Layer.

\noindent$\rightarrow$ \texttt{rpp/include/rpp/rpp.h}

Main library header file.

To use this library just include this file and this file only. Also, before using any library
function please call \texttt{rpp\_init()} function for hardware initialization.

\noindent$\rightarrow$ \texttt{rpp/include/rpp/RppConfig.h}

Library configuration file.

Please refer to the API documentation and header file comments for specific documentation for each
configuration parameter.

\noindent$\rightarrow$ \texttt{rpp/include/rpp/rpp\_\{mnemonic\}.h}

Header file for \texttt{\{mnemonic\}} module.

This files includes function definitions, pin definitions, etc, specific to \{mnemonic\} module. The
inclusion of this header can be configured in \texttt{RppConfig.h} using
\texttt{rppCONFIG\_INCLUDE\_\{MNEMONIC\}} directive. See
\htmladdnormallink{API development guidelines}{\#api\_development\_guidelines}.

\noindent$\rightarrow$ \texttt{rpp/src/rpp/rpp\_\{mnemonic\}.c}

Module implementation.

Implementation of \texttt{rpp\_\{mnemonic\}.h}'s functions on top of the DRV library. See
\htmladdnormallink{API development guidelines}{\#api\_development\_guidelines}.

\noindent$\rightarrow$ \texttt{rpp/src/rpp/rpp.c}

Implementation of library-wide functions.

\newpage

\hypertarget{test_suite}{}
\subsection{Test Suite}

The \texttt{rpp-test-suite} is a RPP application developed as part of this project that includes a
series of test tasks or test commands to verify the correct behavior and functionality of the RPP
layer modules. There is one command per module, and the command use the same mnemonic that the
module.

This test suite can be found in \texttt{$<$repo$>$/rpp/lib/apps/rpp-test-suite} for the ARM version and in
\texttt{$<$repo$>$/rpp/lib/apps/rpp-test-suite\_posix} for the simulated version.

The application enables a command processor using the SCI at \textbf{115200-8-N-1}:

\begin{verbatim}
RPP Library Test Suite.
===========================================================
[Type a module to test or 'help']
--> help
Available commands:
        help - Display this help.
        ain  - Test Analog Input.
        aout - Test Analog Output.
        can  - Test CAN communication.
        din  - Test Digital Inputs.
        eth  - Test Ethernet communication.
        fr   - Test FlexRay communication.
        hbr  - Test H-Bridge.
        hout - Test High Power Output.
        lin  - Test LIN communication.
        lout - Test Digital Outputs.
        mout - Test Power Outputs.
        sci  - Test Serial Communication Interface.
        sdc  - Test SD-Card.
        sdr  - Test SD-RAM.
\end{verbatim}

Current modules with tests implemented are:

\begin{multicols}{2}

\begin{compactitem}
\item AIN.
\item AOUT.
\item DIN.
\item HBR.
\item LOUT.
\item MOUT.
\item SCI. (the test-suite itself)
\item SDR.
\end{compactitem}

\end{multicols}

A note of warning: tests spawn OS tasks at the beginning of the test and deletes them at the end.
Because current memory memory management implementation cannot free memory the test suite will
fill all the memory and tests will be unable to start. In this case just reset the board. See
\htmladdnormallink{Appendix A: Notes on FreeRTOS memory management}{\#appendix\_a\_notes\_on\_freertos\_memory\_management}
for more information.

\newpage

\hypertarget{ain_test_description}{}
\subsubsection{AIN test description}

This test will read all the analog inputs at a rate of 100 times per second and print the result.

\begin{verbatim}
--> ain
Analog Inputs Test [1-12]:
===========================================================
   1    2    3    4    5    6    7    8    9   10   11   12
   0    0    0    0    0    0    0    0    0    0    0    0
\end{verbatim}

Status: \textbf{PASSED} for channels 1-5. 6-12 remain untested but they \textit{should} work.

\hypertarget{aout_test_description}{}
\subsubsection{AOUT test description}

This test will generate a 10Hz sinus wave on all the analog outputs with a sampling rate of 1kHz.
The sinus wave of each analog output channel is sifted by (1/4)pi.

\begin{verbatim}
--> aout
Analog Output Test at 10 Hz:
===========================================================
Samples: 7331
\end{verbatim}

Status: \textbf{PASSED}.

\hypertarget{din_test_description}{}
\subsubsection{DIN test description}

This test will read all 16 + 8 digital inputs at a rate of 100 times per second, using both low
speed SPI chip and variable threshold high-speed inputs.

\begin{verbatim}
--> din
Digital Inputs Test [1-16]:
===========================================================
 1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16  A  B  C  D  E  F  G  H
 0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0
\end{verbatim}

Status:

 \begin{compactitem}
 \item Low speed fixed threshold [1-16]: \textbf{PASSED}.
 \item High speed variable threshold [A-H]: \textbf{PASSED}.
 \end{compactitem}

\hypertarget{hbr_test_description}{}
\subsubsection{HBR test description}

This test will generate a sinus wave to control the H-Bridge of one period per 20 seconds (0.05Hz)
at a sampling rate of 20Hz.

\begin{verbatim}
--> hbr
H-Bridge Test at 0.05 Hz:
===========================================================
Samples: 72
\end{verbatim}

Status: \textbf{PASSED}.

\hypertarget{lout_test_description}{}
\subsubsection{LOUT test description}

This test will show in the digital outputs the value in binary of a counter, incrementing the
counter once per second. The counter is 8 bits, the same as the outputs, so 255 seconds are
required for an overflow/restart of the counting.

\begin{verbatim}
--> lout
Digital Output Test:
===========================================================
Counter:   40
\end{verbatim}

Status: \textbf{PASSED}.

\hypertarget{mout_test_description}{}
\subsubsection{MOUT test description}

This test will toggle the power outputs one by one per second, then wait 10 seconds in that state
while constantly verifying the diagnostics.

\begin{verbatim}
--> mout
Power Output Test:
===========================================================
1     2     3     4     5     6
1: OK 1: OK 1: OK 1: OK 1: OK 1: OK
\end{verbatim}

Status: \textbf{PASSED}.

\hypertarget{sci_test_description}{}
\subsubsection{SCI test description}

A more comprehensive test is not implemented. The very use of this test-suite implies the correct
function of the SCI module. Nevertheless, as a future improvement, a test that will verify run-time
baud rate changes and test some other RPP SCI functions is desirable.

\begin{verbatim}
--> sci
You're using the SCI, reading this and typing this command.
Press any key to continue...
\end{verbatim}

Status: \textbf{PASSED}.

\hypertarget{sdr_test_description}{}
\subsubsection{SDR test description}

This test will launch a noise generator task that will log noise and then start the library
included SD-RAM logging command processor, allowing the user to see and handle the log on the
SD-RAM.

\begin{verbatim}
--> sdr
Log control: 1024kB available.
===========================================================
--> log
[   1239864] This is the noise generator at iteration 1 putting some noise value 279735017.
[   1240779] This is the noise generator at iteration 2 putting some noise value 1943579783.

--> available
1023 kB of 1024 kB available.

--> clear
Done.

--> exit
\end{verbatim}

Status: \textbf{PASSED}.

\newpage

\hypertarget{static_libraries}{}
\subsection{Static libraries}

The RPP Library can be compiled as a static library for ARM using TI CGT and for x86(\_64) using
GCC. CCS projects \texttt{rpp-lib} and \texttt{rpp-lib\_posix} in \texttt{$<$repo$>$/rpp/lib/apps/} allows to generate
the static libraries. After compilation, as part of the build process, both projects will
automatically update the version-controlled static libraries in \texttt{$<$repo$>$/rpp/lib/}:

\begin{compactitem}
\item \texttt{rpp-lib.lib}, static library for ARM using TI naming scheme.
\item \texttt{librpp.a}, static library for x86(\_64) using standard Linux naming scheme.
\end{compactitem}

One future improvement would be the creation of a Makefile for each compilation scheme in order to
not depend on CCS managed build system. For ARM manual compilation or makefile creation using Texas
CGT see the \texttt{target\_tools.mk} file under the Simulink RPP Target folder. The relevant aspects for
compiling and linking an application using the static libraries are:

\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 \htmladdnormallink{OS interchangeable layer}{\#os\_interchangeable\_layer}
  section above.
\item Include header files for the RPP library.
\item Add library \texttt{rpp-lib.lib} to the linker libraries. The RPP library \textbf{MUST} be looked for
  before Texas Instruments support library \texttt{rtsv7R4\_T\_be\_v3D16\_eabi.lib}.
\item Configure linker to retain \texttt{.intvecs} section from RPP Library:\newline{}
  \texttt{--retain="rpp-lib.lib$<$sys\_intvecs.obj$>$(.intvecs)"}
\item Use the provided linker command file \texttt{TMS570LS313xFlashLnk.cmd}.
\end{compactitem}

\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.
\item Create a \texttt{RppConfig.h} override file and drop DRV layer dependency: \texttt{rppCONFIG\_DRV 0}.
\item Includes must be configured in a way that the \texttt{RppConfig.h} taken under consideration is the
  override and not the library one.
\item Add library \texttt{librpp.a} to the linker libraries.
\item Add \texttt{pthread} to the linker libraries.
\end{compactitem}

As an important note, all the models compiled using Simulink will link against \texttt{rpp-lib.lib}.
When compiling a Simulink model, Simulink, and then \texttt{make}, will not 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.

\newpage

\hypertarget{base_application}{}
\subsection{Base application}

In \texttt{$<$repo$>$/rpp/lib/apps/} there is two RPP base applications, \texttt{base} and \texttt{base\_posix}, that
already configured for the RPP Library. It is advised that new applications uses this projects a
foundations.

To create a new application copy this directory and rename it. Now open files \texttt{.project},
\texttt{.cproject} and \texttt{.ccsproject} (if available) and change any occurrence of the work \texttt{base}
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]{media/images/base_1.png}
\item Create a normal folder \texttt{include}.
\item Create a source folder \texttt{src}.
\item Add common \texttt{.gitignore} to the root of that project:
\lstset{language=}
\begin{lstlisting}
Debug
Release
.settings/*
\end{lstlisting}
\newpage
\item Add new variable \texttt{RPP\_LIB\_ROOT} and point to this repository branch root.\newline{}
\noindent\includegraphics[width=400px]{media/images/base_2.png}
\item Add \texttt{rpp-lib.lib} static library to linker libraries and add \texttt{RPP\_LIB\_ROOT} to the library
  search path.\newline{}
\noindent\includegraphics[width=400px]{media/images/base_3.png}
\newpage
\item Configure linker to retain \texttt{.intvecs} from RPP static library.\newline{}
\noindent\includegraphics[width=350px]{media/images/base_4.png}
\item Configure compiler to include local includes, OS includes for TMS570 and RPP includes, in that
  order.\newline{}
\noindent\includegraphics[width=350px]{media/images/base_5.png}
\newpage
\item Configure compiler to allow GCC extensions.\newline{}
\noindent\includegraphics[width=400px]{media/images/base_6.png}
\item Import and link (\underline{do not copy!}) linker file and board upload descriptor.\newline{}
\noindent\includegraphics[width=200px]{media/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 \texttt{src}. Link all files from original CCS application to this folder.
\item Create a normal folder \texttt{include}. Create a folder \texttt{rpp} inside of it.
\item Add common \texttt{.gitignore} to the root of that project:
\lstset{language=}
\begin{lstlisting}
Debug
Release
.settings/*
\end{lstlisting}
\newpage
\item Add new variable \texttt{RPP\_LIB\_ROOT} and point to this repository branch root.\newline{}
\noindent\includegraphics[width=400px]{media/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]{media/images/base_posix_2.png}
\newpage
\item Add \texttt{rpp} and \texttt{pthread}to linker libraries and add \texttt{RPP\_LIB\_ROOT} to the library search
  path.\newline{}
\noindent\includegraphics[width=400px]{media/images/base_posix_3.png}
\item Copy \texttt{RppConfig.h} from RPP Library to a new folder \texttt{include/rpp} and configure it drop DRV
  layer dependency: \texttt{rppCONFIG\_DRV 0}.\newline{}
\noindent\includegraphics[width=200px]{media/images/base_posix_4.png}
\end{compactenum}

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

\begin{enumerate}
\item Include RPP library header file.
\lstset{language=c++}
\begin{lstlisting}
#include "rpp/rpp.h"
\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.
 \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)
{
    /* Initialize RPP board */
    rpp_init();

    /* 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 \texttt{vApplicationMallocFailedHook()} allows to catch memory allocation errors.
 \item \texttt{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}

\hypertarget{api_generation}{}
\subsection{API generation}

The RPP Layer is formatted using Doxygen documentation generator. This allows to generate a high
quality API reference. To generate the API reference do in a terminal:

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

The files under \texttt{$<$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}

To install Doxygen see \htmladdnormallink{Development environment}{\#development\_environment} section.

\hypertarget{api_reference}{}
\subsection{API Reference}

For the complete API reference please generate the HTML version using the above section
instructions. Here is listed the index of functions of each module and their brief.

Please note that not all modules were implemented as part of this project. See
\htmladdnormallink{RPP Layer Modules}{\#rpp\_layer\_modules} for a list of the modules implemented.

\newpage

\hypertarget{din_api_reference}{}
\subsubsection{DIN API Reference}

\texttt{int8\_t rpp\_din\_init();} \newline{} \noindent$\rightarrow$ DIN module initialization. \newline{} \newline{}
\texttt{int8\_t rpp\_din\_ref(uint16\_t refA, uint16\_t refB);} \newline{} \noindent$\rightarrow$ Configure voltage reference levels for digital inputs using variable reference threshold. \newline{} \newline{}
\texttt{int8\_t rpp\_din\_setup(uint8\_t pin, boolean\_t pull\_type, boolean\_t active, boolean\_t can\_wake);} \newline{} \noindent$\rightarrow$ Configure given pin. \newline{} \newline{}
\texttt{int8\_t rpp\_din\_get(uint8\_t pin, boolean\_t var\_thr);} \newline{} \noindent$\rightarrow$ Get the current cached value of the given pin. \newline{} \newline{}
\texttt{int8\_t rpp\_din\_diag(uint8\_t pin);} \newline{} \noindent$\rightarrow$ Get the diagnostic cached value for given pin. \newline{} \newline{}
\texttt{int8\_t rpp\_din\_update();} \newline{} \noindent$\rightarrow$ Read and update cached values and diagnostic values of all pins. Also commit configuration changes.

\hypertarget{lout_api_reference}{}
\subsubsection{LOUT API Reference}

\texttt{int8\_t rpp\_lout\_init();} \newline{} \noindent$\rightarrow$ LOUT module initialization. \newline{} \newline{}
\texttt{int8\_t rpp\_lout\_set(uint8\_t pin, uint8\_t val);} \newline{} \noindent$\rightarrow$ Set the output cache of given pin to given value. \newline{} \newline{}
\texttt{int8\_t rpp\_lout\_diag(uint8\_t pin);} \newline{} \noindent$\rightarrow$ Get the diagnostic cached value for given pin. \newline{} \newline{}
\texttt{int8\_t rpp\_lout\_update();} \newline{} \noindent$\rightarrow$ Flush cached output values and read back diagnostic values of all pins.

\hypertarget{ain_api_reference}{}
\subsubsection{AIN API Reference}

\texttt{int8\_t rpp\_ain\_init();} \newline{} \noindent$\rightarrow$ AIN module initialization. \newline{} \newline{}
\texttt{int16\_t rpp\_ain\_get(uint8\_t pin);} \newline{} \noindent$\rightarrow$ Get the current analog value on the given pin. \newline{} \newline{}
\texttt{int8\_t rpp\_ain\_update();} \newline{} \noindent$\rightarrow$ Read and update analog cached values.

\hypertarget{aout_api_reference}{}
\subsubsection{AOUT API Reference}

\texttt{\#define RPP\_DAC\_OA   5.6} \newline{} \noindent$\rightarrow$ DAC output operational amplifier multiplication constant. \newline{} \newline{}
\texttt{\#define RPP\_DAC\_VREF 2.5} \newline{} \noindent$\rightarrow$ DAC hardware reference voltage. \newline{} \newline{}
\texttt{int8\_t rpp\_aout\_init();} \newline{} \noindent$\rightarrow$ AOUT module initialization. \newline{} \newline{}
\texttt{int8\_t rpp\_aout\_setup(uint8\_t pin, boolean\_t enabled);} \newline{} \noindent$\rightarrow$ Configure enabled/disabled state for given pin. \newline{} \newline{}
\texttt{int8\_t rpp\_aout\_set(uint8\_t pin, uint16\_t val);} \newline{} \noindent$\rightarrow$ Set the output cache of given pin to given value. \newline{} \newline{}
\texttt{int8\_t rpp\_aout\_set\_voltage(uint8\_t pin, uint16\_t mv);} \newline{} \noindent$\rightarrow$ Set output to given voltage. \newline{} \newline{}
\texttt{int8\_t rpp\_aout\_update();} \newline{} \noindent$\rightarrow$ Flush cached output values and configuration changes.

\hypertarget{hbr_api_reference}{}
\subsubsection{HBR API Reference}

\texttt{int8\_t rpp\_hbr\_init();} \newline{} \noindent$\rightarrow$ HBR module initialization. \newline{} \newline{}
\texttt{int8\_t rpp\_hbr\_enable(int32\_t period);} \newline{} \noindent$\rightarrow$ Enable the H-Bridge for control. \newline{} \newline{}
\texttt{int8\_t rpp\_hbr\_control(double cmd);} \newline{} \noindent$\rightarrow$ Control the H-Bridge direction, enabled/disabled and PWM. \newline{} \newline{}
\texttt{int8\_t rpp\_hbr\_disable();} \newline{} \noindent$\rightarrow$ Disable the H-Bridge.

\newpage

\hypertarget{mout_api_reference}{}
\subsubsection{MOUT API Reference}

\texttt{int8\_t rpp\_hbr\_init();} \newline{} \noindent$\rightarrow$ HBR module initialization. \newline{} \newline{}
\texttt{int8\_t rpp\_mout\_init();} \newline{} \noindent$\rightarrow$ MOUT module initialization. \newline{} \newline{}
\texttt{int8\_t rpp\_mout\_set(uint8\_t pin, uint8\_t val);} \newline{} \noindent$\rightarrow$ Set the output of given pin to given value. \newline{} \newline{}
\texttt{int8\_t rpp\_mout\_get(uint8\_t pin);} \newline{} \noindent$\rightarrow$ Get the cached value of the given pin set by rpp\_mout\_set(). \newline{} \newline{}
\texttt{int8\_t rpp\_mout\_diag(uint8\_t pin);} \newline{} \noindent$\rightarrow$ Reads the value on the given diagnostic pin.

\hypertarget{hout_api_reference}{}
\subsubsection{HOUT API Reference}

\texttt{int8\_t rpp\_hout\_init();} \newline{} \noindent$\rightarrow$ HOUT module initialization.

\hypertarget{can_api_reference}{}
\subsubsection{CAN API Reference}

\texttt{int8\_t rpp\_can\_init();} \newline{} \noindent$\rightarrow$ CAN module initialization.

\hypertarget{lin_api_reference}{}
\subsubsection{LIN API Reference}

\texttt{int8\_t rpp\_lin\_init();} \newline{} \noindent$\rightarrow$ LIN module initialization.

\hypertarget{fr_api_reference}{}
\subsubsection{FR API Reference}

\texttt{int8\_t rpp\_fr\_init();} \newline{} \noindent$\rightarrow$ FR module initialization.

\newpage

\hypertarget{sci_api_reference}{}
\subsubsection{SCI API Reference}

\texttt{int8\_t rpp\_sci\_init();} \newline{} \noindent$\rightarrow$ SCI module initialization. \newline{} \newline{}
\texttt{boolean\_t rpp\_sci\_setup(uint32\_t baud);} \newline{} \noindent$\rightarrow$ SCI module setup. \newline{} \newline{}
\texttt{uint16\_t rpp\_sci\_available();} \newline{} \noindent$\rightarrow$ Number of bytes available on input buffer. \newline{} \newline{}
\texttt{int8\_t rpp\_sci\_read(uint32\_t amount, uint8\_t* buffer);} \newline{} \noindent$\rightarrow$ Read n number of bytes from input buffer. \newline{} \newline{}
\texttt{int8\_t rpp\_sci\_read\_nb(uint32\_t amount, uint8\_t* buffer);} \newline{} \noindent$\rightarrow$ Read n number of bytes from input buffer if possible. \newline{} \newline{}
\texttt{int8\_t rpp\_sci\_write(uint32\_t amount, uint8\_t* data);} \newline{} \noindent$\rightarrow$ Write n number of bytes to the output buffer. \newline{} \newline{}
\texttt{int8\_t rpp\_sci\_write\_nb(uint32\_t amount, uint8\_t* data);} \newline{} \noindent$\rightarrow$ Write n number of bytes to the output buffer if possible. \newline{} \newline{}
\texttt{int8\_t rpp\_sci\_flush(boolean\_t buff);} \newline{} \noindent$\rightarrow$ Flush incomming or outgoing buffers. \newline{} \newline{}
\texttt{int32\_t rpp\_sci\_printf(const char* format, ...);} \newline{} \noindent$\rightarrow$ C style printf using RPP SCI module. \newline{} \newline{}
\texttt{int8\_t rpp\_sci\_putc(uint8\_t byte);} \newline{} \noindent$\rightarrow$ C style putc (put character) using RPP SCI module. \newline{} \newline{}
\texttt{int16\_t rpp\_sci\_getc();} \newline{} \noindent$\rightarrow$ C style getc (get character) using RPP SCI module.

\hypertarget{eth_api_reference}{}
\subsubsection{ETH API Reference}

\texttt{int8\_t rpp\_eth\_init();} \newline{} \noindent$\rightarrow$ ETH module initialization.

\hypertarget{sdc_api_reference}{}
\subsubsection{SDC API Reference}

\texttt{int8\_t rpp\_sdc\_init();} \newline{} \noindent$\rightarrow$ SDC module initialization.

\hypertarget{sdr_api_reference}{}
\subsubsection{SDR API Reference}

\texttt{\#define RPP\_SDR\_ADDR\_START 0x80000000U} \newline{} \noindent$\rightarrow$ SDRAM start address on RPP board. \newline{} \newline{}
\texttt{\#define RPP\_SDR\_ADDR\_END   0x83FFFFFFU} \newline{} \noindent$\rightarrow$ SDRAM end address on RPP board. \newline{} \newline{}
\texttt{int8\_t rpp\_sdr\_init();} \newline{} \noindent$\rightarrow$ SDR module initialization. \newline{} \newline{}
\texttt{int8\_t rpp\_sdr\_setup(boolean\_t enable);} \newline{} \noindent$\rightarrow$ Configure SD-RAM logging. \newline{} \newline{}
\texttt{uint32\_t rpp\_sdr\_available();} \newline{} \noindent$\rightarrow$ Query for the amount of space free on the SD-RAM. \newline{} \newline{}
\texttt{int32\_t rpp\_sdr\_printf(const char* format, ...);} \newline{} \noindent$\rightarrow$ Store a formatted user string on the log, if logging is enabled. \newline{} \newline{}
\texttt{int8\_t rpp\_sdr\_clear();} \newline{} \noindent$\rightarrow$ Clear log. \newline{} \newline{}
\texttt{int8\_t rpp\_sdr\_show(boolean\_t start);} \newline{} \noindent$\rightarrow$ Start/Stop the task that sends the log to the SCI.

\newpage

\hypertarget{simulink_coder_target}{}
\section{Simulink Coder Target}

The Simulink Coder Target allows Simulink model's code generation, compilation and download for the 
board.

\hypertarget{description}{}
\subsection{Description}

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 (armcl) included in the Code Generation Tools available with
Code Composer Studio, and thus it depends on it for proper functioning.

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

\hypertarget{code_generation_process}{}
\subsubsection{Code generation process}

\begin{figure}[H]\begin{center}

\noindent\includegraphics[width=400px]{media/images/tlc_process.png}
\caption{TLC code generation process.}\end{center}\end{figure}

\newpage

\hypertarget{subdirectory__content_description}{}
\subsection{Subdirectory  content description}

\noindent$\rightarrow$ \texttt{rpp\_setup.m}

RPP Target install script.

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

\begin{compactitem}
\item \underline{Reference:}
 \begin{compactitem}
 \item \texttt{$<$repo$>$/refs/rtw\_ug.pdf} p. 1137.
 \end{compactitem}
\end{compactitem}

\noindent$\rightarrow$ \texttt{rpp.tlc}

Embedded real-time system target file for RPP.

This file is the system target file (STF), or target manifest file. Functions of the STF include:

\begin{compactitem}
\item Making the target visible in the System Target File Browser.
\item Definition of code generation options for the target (inherited and target-specific).
\item Providing an entry point for the top-level control of the TLC code generation process.
\end{compactitem}

\begin{compactitem}
\item \underline{Reference:}
 \begin{compactitem}
 \item \texttt{$<$repo$>$/refs/rtw\_ug.pdf} p. 1129 and \underline{1144}.
 \end{compactitem}
\end{compactitem}

\noindent$\rightarrow$ \texttt{rpp.tmf}

Embedded Coder Template Makefile.

This is just standard Embedded Coder Template Makefile, provided by Matlab. It was slightly
modified to support \texttt{armcl} particularities and added template rules for assembler files (which
were included by the \texttt{rpp\_lib\_support.m} script, but is no longer the case).

\begin{compactitem}
\item \underline{Reference:}
 \begin{compactitem}
 \item \texttt{$<$repo$>$/refs/rtw\_ug.pdf} p. 1130 and \underline{1183}.
 \end{compactitem}
\end{compactitem}

\noindent$\rightarrow$ \texttt{rpp\_download.m}

Code download utility for Simulink RPP Target.

This function is optionally executed at the end of the build process if it is successful and the
user selected \textit{Download compiled binary to RPP} option on the build configuration panel. This
function calls \texttt{loadti.sh} script with the generated binary and using configuration for the
XDS100v2 JTAG Emulators. The board should be powered and correctly wired. \newline{}
See \htmladdnormallink{Development wiring}{\#development\_wiring}.

\newpage
\noindent$\rightarrow$ \texttt{rpp\_file\_process.tlc}

Code generation custom file processing template.

This file should decide which \textit{main} to generate according to configuration, in particular which
mode, Single Tasking or Multitasking, is chosen. The RPP Target ignores this settings because it
uses a tasking system based on tasking features provided by FreeRTOS. In consequence is only a
wrapper to the \textit{Single Tasking} main, which clearly is not for single tasking.

\begin{compactitem}
\item \underline{Reference:}
 \begin{compactitem}
 \item \texttt{$<$repo$>$/refs/ecoder\_ug.pdf} p. 556.
 \item \texttt{$<$repo$>$/refs/ecoder\_ref.pdf} p. 1347.
 \end{compactitem}
\end{compactitem}

\noindent$\rightarrow$ \texttt{rpp\_lib\_support.m}

\textbf{DEPRECATED}. Simulink support for RPP library and operating system setup.

This files used to add the source code from the RPP library and operating to the build. This is no
longer required when using the static library. This is left for future reference in case new source
code needs to be included to the build.

\begin{compactitem}
\item \underline{Reference:}
 \begin{compactitem}
 \item \texttt{$<$repo$>$/refs/rtw\_ug.pdf} p. 1058.
 \item \texttt{$<$repo$>$/refs/rtw\_ref.pdf} p. 56.
 \end{compactitem}
\end{compactitem}

\noindent$\rightarrow$ \texttt{rpp\_make\_rtw\_hook.m}

Build process hooks file.

This file is hook file that invoke target-specific functions or executables at specified points in
the build process. In particular, this file handle the copying of required files before the
compilation stage.

\begin{compactitem}
\item \underline{Reference:}
 \begin{compactitem}
 \item \texttt{$<$repo$>$/refs/rtw\_ug.pdf} p. 1066-1072 and 1131.
 \end{compactitem}
\end{compactitem}

\noindent$\rightarrow$ \texttt{rpp\_select\_callback\_handler.m}

RPP Target select callback handler.

This callback function is triggered whenever the user selects the target in the System Target File
Browser. Default values for Simulation and configurations parameters are set. Some options are
disabled if it is not allowed to be changed by user.

\begin{compactitem}
\item \underline{Reference:}
 \begin{compactitem}
 \item \texttt{$<$repo$>$/refs/rtw\_ug.pdf} p. 1211.
 \end{compactitem}
\end{compactitem}

\newpage
\noindent$\rightarrow$ \texttt{rpp\_srmain.tlc}

Custom file processing to generate a \textit{main} file.

This file generated the \textit{main} file for the RPP target on top of the RPP library and the FreeRTOS
operating system. The \texttt{sr} prefix is standard to mark Single Tasking main, which is the case.
See \texttt{rpp\_file\_process.m} description above for more information about this.

\begin{compactitem}
\item \underline{Reference:}
 \begin{compactitem}
 \item Example in \texttt{$<$matlab$>$/rtw/c/tlc/mw/bareboard\_srmain.tlc}.
 \end{compactitem}
\end{compactitem}

\noindent$\rightarrow$ \texttt{target\_tools.mk}

Makefile for CCS (\texttt{armcl}) toolchain support.

This file set variables to CCS tools to support build for this toolchain. This file is included by
\texttt{rpp.tmf} before declaring the rules for source code.

\begin{compactitem}
\item \underline{Reference:}
 \begin{compactitem}
 \item \textit{Include a tool specification settings} comment block in \texttt{rpp.tmf}.
 \item Compiler options documentation available in \texttt{armcl.pdf}.
 \end{compactitem}
\end{compactitem}

\newpage

\hypertarget{installation_procedure}{}
\subsection{Installation procedure}

\begin{enumerate}
\item Download and install CCS for Linux:

Details on how to setup CCS are available in section
\htmladdnormallink{TI Code Composer Studio}{\#ti\_code\_composer\_studio}.

\item Install RPP Target:

Open Matlab and type on command window:

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

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

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

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 \texttt{$<$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{Usage}
\label{sec:usage}

\begin{enumerate}
\item Open or create a model you want to generate code from.
\item Make sure that the model is configured (Simulation $\rightarrow$
  Model Configuration Parameters) as described in Section \ref{sec:target-reference}.
\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 \texttt{<model>\_rpp}, where
  \texttt{model} is the name of the Simulink model.
\item Generate the code by choosing ``Code $\rightarrow$ C/C++ Code
  $\rightarrow$ Build Model''.
\item If \emph{Download compiled binary to RPP} was selected in
  \emph{RPP Options} pane (see Section \ref{sec:rpp-target-options}),
  the compiled binary will be downloaded to the to the board. After
  the download is finished you should reset the board to run the
  downloaded code.

  Note: You should quit the Code Composer Studio before downloading the
  generated code to the RPP board. Otherwise the download fails.
\end{enumerate}

\newpage

\hypertarget{target_reference}{}
\subsection{Target Reference}
\label{sec:target-reference}

This section describes the options required or available for running a Simulink model with the RPP
Target.

\hypertarget{simulink_model_options}{}
\subsubsection{Simulink model options}

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

\begin{compactitem}
\item Solver:
 \begin{compactitem}
 \item \textit{fixed-step discrete}.
 \item Tasking mode set to \textit{SingleTasking}. \newline{}
\noindent\includegraphics[width=400px]{media/images/simulink_solver.png}
\newpage
 \end{compactitem}
\item Diagnostics -- Sample Time:
 \begin{compactitem}
 \item Disable warning source block specifies -1 sampling time. It's ok for the source blocks to run
   once per tick. \newline{}
\noindent\includegraphics[width=400px]{media/images/simulink_diagnostics.png}
 \end{compactitem}
\item Code generation:
 \begin{compactitem}
 \item Set to \texttt{rpp.tlc}. \newline{}
\noindent\includegraphics[width=400px]{media/images/simulink_code.png}
 \end{compactitem}
\end{compactitem}

Note: Single Tasking is the only currently supported mode. If multitasking is required to be
      implemented in the future create a new file \texttt{rpp\_mrmain.tlc} in \texttt{$<$repo$>$/rpp/rpp/} and
      edit \texttt{rpp\_file\_process.tlc} to use that file instead when multitasking is selected.

\hypertarget{rpp_target_options}{}
\subsubsection{RPP Target options}
\label{sec:rpp-target-options}

The RPP Target include the following configuration options, all of them configurable per model
under  \texttt{Code Generation} \noindent$\rightarrow$ \texttt{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 is the stack for the application when running outside a FreeRTOS task,
  normally before the scheduler has started and for system routines. Default value is 4096.

\item \textbf{C system heap size}: this parameter is passed directly to the linker for the allocation of the
  heap. See
  \htmladdnormallink{Appendix A: Notes on FreeRTOS memory management}{\#appendix\_a\_notes\_on\_freertos\_memory\_management}
  for an important information about this parameter.

\item \textbf{Model step task stack size}: this parameter will be passed to the \texttt{xTaskCreate()} that
  creates the task for the model to run. In a Simulink model there is 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. Take into account for example than only a single call to
   \texttt{rpp\_sci\_printf()} requires, with current configuration, 128 bytes from the stack. This value
   should be minor than the C system heap and leaving enough heap for the system tasks. See
   \htmladdnormallink{Appendix A: Notes on FreeRTOS memory management}{\#appendix\_a\_notes\_on\_freertos\_memory\_management}
   for more information.
 \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 upload even if
  only source code has been generated, failing graciously or uploading an old binary laying around
  in the build directory. This option calls the \texttt{rpp\_download.m} script, which is in turn a
  wrapper on the \texttt{loadti.sh} script. More information on the \texttt{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 \texttt{loadti.sh} script will close after the download of the generated program and in
  consequence the execution of the loaded program will stop (because it works as the CCS debug
  server). In order to test the loaded model a manual reset of the board is always required after a
  successful download.

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


\newpage
\end{itemize}

\hypertarget{simulink_block_library}{}
\section{Simulink Block Library}

\vspace{-0.25cm}

The Simulink Block Library is a set of blocks that allows Simulink models to use board IO and 
communication peripherals.

\vspace{-0.5cm}

\hypertarget{description}{}
\subsection{Description}

\vspace{-0.25cm}

As part of this project the ideal set was defined, but not all blocks were implemented. The
following table shows the current status of the block library.

\vspace{-0.25cm}

\begin{center}\begin{tabular}{lllll}
\textbf{CATEGORY} & \textbf{NAME} & \textbf{STATUS*} & \textbf{MNEMONIC} & \textbf{LRH*} \\
System blocks & Configuration block & \texttt{X} & \texttt{[CONF]} & \texttt{RppConfig.h} \\
Logic IO blocks & Digital Input block & \texttt{T} & \texttt{[DIN ]} & \texttt{rpp\_din.h} \\
 & Digital Output block & \texttt{T} & \texttt{[LOUT]} & \texttt{rpp\_lout.h} \\
 & Analog Input block & \texttt{T} & \texttt{[AIN ]} & \texttt{rpp\_ain.h} \\
 & Analog Output block & \texttt{T} & \texttt{[AOUT]} & \texttt{rpp\_aout.h} \\
Power output blocks & H-Bridge Control block & \texttt{T} & \texttt{[HBR ]} & \texttt{rpp\_hbr.h} \\
 & Power output block & \texttt{T} & \texttt{[MOUT]} & \texttt{rpp\_mout.h} \\
 & High-Power output block & \texttt{X} & \texttt{[HOUT]} & \texttt{rpp\_hout.h} \\
Communication blocks & CAN Bus receive block & \texttt{X} & \texttt{[CANR]} & \texttt{rpp\_can.h} \\
 & CAN Bus send msg block & \texttt{X} & \texttt{[CANS]} & - Idem - \\
 & LIN receive block & \texttt{X} & \texttt{[LINR]} & \texttt{rpp\_lin.h} \\
 & LIN send msg block & \texttt{X} & \texttt{[LINS]} & - Idem - \\
 & FlexRay receive block & \texttt{X} & \texttt{[FRR ]} & \texttt{rpp\_fr.h} \\
 & FlexRay send msg block & \texttt{X} & \texttt{[FRS ]} & - Idem - \\
 & SCI receive block & \texttt{T} & \texttt{[SCIR]} & \texttt{rpp\_sci.h} \\
 & SCI send msg block & \texttt{T} & \texttt{[SCIS]} & - Idem - \\
 & SCI configure block & \texttt{T} & \texttt{[SCIC]} & - Idem - \\
 & Ethernet receive block & \texttt{X} & \texttt{[ETHR]} & \texttt{rpp\_eth.h} \\
 & Ethernet send msg block & \texttt{X} & \texttt{[ETHS]} & - Idem - \\
Logging/Storage blocks & SD Card write block & \texttt{T} & \texttt{[SDCW]} & \texttt{rpp\_sdc.h} \\
 & SDRAM write block & \texttt{X} & \texttt{[SDRW]} & \texttt{rpp\_sdr.h} \\
Trigger blocks & Overrun detected block & \texttt{X} & \texttt{[TROR]} & - None - \\
 & Stack overflow detected block & \texttt{X} & \texttt{[TRSO]} & - None - \\
 & Malloc Failed detected block & \texttt{X} & \texttt{[TRMF]} & - None - \\
\end{tabular}\end{center}

\vspace{-0.5cm}
\begin{multicols}{2}

\textbf{Legend:}

\begin{compactitem}
\item *LRH    : Library Reference Header.
\item *STATUS :
 \begin{compactitem}
 \item \texttt{X} - Unimplemented. Files non present.
 \item \texttt{P} - Unimplemented. Files present.
 \item \texttt{W} - Work in progress.
 \item \texttt{I} - Implemented.
 \item \texttt{T} - Implemented and tested.
 \end{compactitem}
\end{compactitem}

\vfill\columnbreak

\textbf{Notes:} \newline{}
Each block that can detect fault condition should have a trigger output. \newline{}
High-power output provides current flow as an input to the model.

\end{multicols}

\hypertarget{c_mex_s_functions}{}
\subsubsection{C MEX S-Functions}

All of the blocks are implemented as a C Mex S-Function coded by hand. In the this section the 
approach taken is explained.

C-MEX S-Function:

 \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 GCC 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 includes the following mandatory callbacks:

\begin{compactenum}
\item \texttt{mdlInitializeSizes}: \newline{}
  Specify the number of inputs, outputs, states, parameters, and other characteristics of the C 
  MEX S-function.
\item \texttt{mdlInitializeSampleTimes}: \newline{}
  Specify the sample rates at which this C MEX S-function operates.
\item \texttt{mdlOutputs}: \newline{}
  Compute the signals that this block emits.
\item \texttt{mdlTerminate}: \newline{}
  Perform any actions required at termination of the simulation.
\end{compactenum}

Plus many more optional callbacks. Relevant optional callbacks are:

\begin{compactenum}
\item \texttt{mdlCheckParameters}: \newline{}
  Check the validity of a C MEX S-function's parameters.
\item \texttt{mdlRTW}: \newline{}
  Generate code generation data for a C MEX S-function.
\item \texttt{mdlSetWorkWidths}: \newline{}
  Specify the sizes of the work vectors and create the run-time parameters required by the C MEX 
  S-function.
\item \texttt{mdlStart}: \newline{}
  Initialize the state vectors of the C MEX S-function.
\end{compactenum}

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}

\newpage
The way a C-MEX S-Function participates in a Simulink simulation is shown by the following diagram:

\begin{figure}[H]\begin{center}

\noindent\includegraphics[width=250px]{media/images/sfunctions_process.png}
\caption{Simulation cycle of a S-Function.}\end{center}\end{figure}

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

The S-Functions required could be implemented in several ways:

\begin{compactenum}
\item Writing the S-Function. \newline{}
  Using this method, the user hand write a new C S-Function and associated TLC file. This method 
  requires the most knowledge about the structure of a C S-Function.
\item Using an S-Function Builder block. \newline{}
  Using this method, the user enter the characteristics of the S-function into a block dialog. This 
  method does not require any knowledge about writing S-Functions. However, a basic understanding 
  of the structure of an S-Function can make the S-Function Builder dialog box easier to use.
\item Using the Legacy Code Tool (LCT). \newline{}
  Using this command line method, the user define the characteristics of your S-function in a data 
  structure in the MATLAB workspace. This method requires the least amount of knowledge about 
  S-Functions.
\end{compactenum}

From the above, the LCT is a tool that can be called within Matlab workshop that allows to generate 
source code for S-Functions given the descriptor of a C function call. This approach is used by
most of the other targets reviewed for this project. The descriptor is a Matlab file with 
definitions like the following:

\newpage
\begin{lstlisting}[language=Matlab]
%% GPIO Write
% Populate legacy_code structure with information
GPIOWrite = legacy_code('initialize');
GPIOWrite.SFunctionName = 'sfun_GPIOWrite';
GPIOWrite.HeaderFiles = {'gpiolct.h'};
GPIOWrite.SourceFiles = {'gpiolct.c'};
GPIOWrite.OutputFcnSpec = 'GPIOWrite(uint32 p1, uint8 u1, uint8 u2)';
% Support calling from within For-Each subsystem
GPIOWrite.Options.supportsMultipleExecInstances = true;
\end{lstlisting}

The interface and implementation files specified should hold the declaration and implementation of
the \texttt{OutputFcnSpec} function. This tool will generate a simple S-Function that will input and 
output the values required by that function. This approach was \textbf{not} for this project, mainly 
because:

\begin{itemize}
\item The RPP Library requires that after some actions (like setting one LOUT output) the changes are 
  committed to the hardware, or before some other actions (like getting the value from DIN using 
  the fixed threshold) the values cached are updated. And the implementation of a wrapper function
  that would update or commit the changes wasn't considered because of the efficiency impact it
  would have.

\item Furthermore, the error handling of the function call is not considered, and for some blocks 
  (like MOUT and HOUT) the diagnostic handling is mandatory.

\item Also, the dialog parameters of the S-Function cannot be validated otherwise than data type 
  (cannot validate range, for example). 

\item For future improvements the LCT cannot generate code for simulation, and a lot of S-Function 
  options cannot not be fine tuned. 

\item Finally, the generated code is very obscure, hard to read and to maintain in case the above 
  functionality had to be implemented on top of the generated code.
\end{itemize}

Similarly the hand written S-Functions shares a large amount of code like parameters scalar, data 
type and range validation, standard options for this kind of blocks, unused functions, among other. 
Because of this a mini framework for writing S-Functions for RPP was implemented in the form of two 
files that are directly included at the beginning and end of the S-Function implementation: 
\texttt{header.c} and  \texttt{trailer.c}. 

This mini-framework reduces the amount of required code for each S-Function considerably, making 
easier to maintain and adapt. Because each S-Function is a program by itself there is no need to 
use interface files and the files are directly included.

\newpage
The final form of the S-Function is a C file of around 100 lines of code with the following layout:

\begin{itemize}
\item Define S-Function name \texttt{S\_FUNCTION\_NAME}.

\item Include header file \texttt{header.c}.

\item In \texttt{mdlInitializeSizes} define:
 \begin{itemize}
 \item Number of \textit{dialog} parameter.
 \item Number of input ports.
  \begin{compactitem}
  \item Data type of each input port.
  \end{compactitem}
 \item Number of output ports.
  \begin{compactitem}
  \item Data type of each output port.
  \end{compactitem}
 \item Standard options for driver blocks.

 \end{itemize}
\item In \texttt{mdlCheckParameters}:
 \begin{itemize}
 \item Check data type of each parameter.
 \item Check range, if applicable, of each parameter.

 \end{itemize}
\item In \texttt{mdlSetWorkWidths}:
 \begin{compactitem}
 \item Map \textit{dialog} parameter to \textit{runtime} parameters.
  \begin{itemize}
  \item Data type of each \textit{runtime} parameter.

  \end{itemize}
 \end{compactitem}
\item Define symbols for unused functions.

\item Include trailer file \texttt{trailer.c}.
\end{itemize}

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

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

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

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

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

\newpage

\hypertarget{target_language_compiler_files}{}
\subsubsection{Target Language Compiler files}

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

The file \texttt{$<$modelname$>$.c} has 3 main functions:

\begin{compactitem}
\item \texttt{void $<$modelname$>$\_step(void)}: \newline{}
  This function recalculates all the outputs of the blocks and should be called once per step. This
  is the main working function.
\item \texttt{void $<$modelname$>$\_initialize(void)}: \newline{}
  This function is called only once before the first step is issued. Default values for blocks IOs
  should be placed here.
\item \texttt{void $<$modelname$>$\_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 errors is detected and in most models it is empty.
\end{compactitem}

In order to generate code for each one of those functions each S-Function implement a TLC file
for \textit{inlining} the S-Function on the generated code. The TLC files are files that 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.

TLC files are located under \texttt{$<$repo$>$/rpp/blocks/tlc\_c/} directory. For a diagram on how TLC files 
work see \htmladdnormallink{Code generation process}{\#code\_generation\_process} section.

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

\texttt{sfunction\_foo.c} \noindent$\rightarrow$ \texttt{tlc\_c/sfunction\_foo.tlc}

The TLC files implemented for this project use 3 hook functions in particular (other are available, 
see TLC reference documentation):

\begin{itemize}
\item \texttt{BlockTypeSetup}: \newline{}
  BlockTypeSetup executes once per block type before code generation begins.
  This function can be used to include elements required by this block type, like includes or
  definitions.

\item \texttt{Start}: \newline{}
  Code here will be placed in the \texttt{void $<$modelname$>$\_initialize(void)}. Code placed here will
  execute only once.

\item \texttt{Outputs}: \newline{}
  Code here will be placed in the \texttt{void $<$modelname$>$\_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 \texttt{BlockTypeSetup}: \newline{}
  Call common function \texttt{\%$<$RppCommonBlockTypeSetup(block, system)$>$} that will include the 
  \texttt{rpp/rpp.h} header file (can be called multiple times but header is included only once).

\item \texttt{Start}: \newline{}
  Call setup routines from RPP Layer for the specific block type, like HBR enable, DIN pin setup, 
  AOUT value initialization, SCI baud rate setup, among others.

\item \texttt{Outputs}: \newline{}
  Call common IO routines from RPP Layer, like DIN read, AOUT set, etc. Success of this functions
  is checked and in case of failure error is reported to the block using ErrFlag.
\end{itemize}

\newpage

\hypertarget{subdirectory__content_description}{}
\subsection{Subdirectory  content description}

\noindent$\rightarrow$ \texttt{header.c} and \texttt{trailer.c}

RPP framework for simple S-Functions.

This files are included at the head and tail of each S-Function file. They include refactored and
commonly repeated structures that pollute S-Functions implementations. They include basic includes,
required definitions, macro definitions, common functions implementations and documentation on
optional functions and commented prototypes for optional model calls/hooks.

\begin{compactitem}
\item \underline{Reference:}
 \begin{compactitem}
 \item See header of those files.
 \end{compactitem}
\end{compactitem}

\noindent$\rightarrow$ \texttt{sfunction\_\{mnemonic\}.c}

C-MEX S-Function implementation for \{mnemonic\} block.

This file implements the \{mnemonic\} block using C-MEX S-Function API. See the reference for 
information about the S-Function API.

\begin{compactitem}
\item \underline{Reference:}
 \begin{compactitem}
 \item \texttt{$<$repo$>$/refs/sfunctions.pdf}
 \end{compactitem}
\end{compactitem}

\noindent$\rightarrow$ \texttt{tlc\_c/sfunction\_\{mnemonic\}.tlc}

Target Language Compiler (TLC) file for \{mnemonic\} block.

This file implements the C code inlining for \{mnemonic\} block. See the reference for information 
about the TLC API.

\begin{compactitem}
\item \underline{Reference:}
 \begin{compactitem}
 \item \texttt{$<$repo$>$/refs/rtw\_tlc.pdf}
 \end{compactitem}
\end{compactitem}

\noindent$\rightarrow$ \texttt{tlc\_c/common.tlc}

Common TLC functions.

This file implements common TLC functions used by all the blocks.

\begin{compactitem}
\item \underline{Reference:}
 \begin{compactitem}
 \item None.
 \end{compactitem}
\end{compactitem}

\newpage
\noindent$\rightarrow$ \texttt{slblocks.m}

Simulink library control file.

This file allows a group of blocks to be integrated into the Simulink Library and Simulink Library
Browser. This file is required by Simulink in order to interpret this folder as a block library.
For information about this file see the references.

\begin{compactitem}
\item \underline{Reference:}
 \begin{compactitem}
 \item \texttt{$<$repo$>$/refs/rtw\_ug.pdf} p. 1127
 \end{compactitem}
\end{compactitem}

\noindent$\rightarrow$ \texttt{rpp\_lib.slx}

RPP Simulink block library.

Simulink block library that includes all the blocks. This file is referenced by \texttt{slblocks.m}

\begin{compactitem}
\item \underline{Reference:}
 \begin{compactitem}
 \item None.
 \end{compactitem}
\end{compactitem}

\noindent$\rightarrow$ compile\_blocks.m

Blocks compilation script.

This script compiles all the sfunction blocks to MEX executables. This script is called by the
\texttt{rpp\_setup()} function in order make all the blocks available to the Simulink environment or it
can be called independently when developing S-Functions.

\begin{compactitem}
\item \underline{Reference:}
 \begin{compactitem}
 \item None.
 \end{compactitem}
\end{compactitem}

\newpage

\hypertarget{block_library_reference}{}
\subsection{Block Library Reference}

This section describes each one of the Simulink blocks implements as part of this project:

\begin{figure}[H]\advance\leftskip-1cm

\noindent\includegraphics[width=530px]{media/images/block_library.png}
\caption{Simulink RPP Block Library.}\end{figure}

\newpage

\hypertarget{din_digital_input_block}{}
\subsubsection{DIN Digital Input block}

\begin{verbatim}
    Inputs      : 0
        None

    Outputs     : 2
        bool    Digital Input
        bool    ErrFlag

    Parameters  : 2
        uint8   Pin number [1-16]
        bool    Use variable threshold
\end{verbatim}

This block allows to read the digital inputs on the RPP board. The variable threshold check change 
the read mode of the pin. The ErrFlag should raise if \texttt{rpp\_din\_update()} or \texttt{rpp\_din\_get()} 
returns error. \texttt{rpp\_din\_update()} is called just by the first DIN block in the model and thus 
only the first block could raise the flag because of this. In case an errors occurs the return 
value will always be LOW (0). Because the ErrFlag should never set, once set the following steps 
will never clear it back.

\begin{multicols}{3}

\begin{compactitem}
\item \textbf{Tested}:
 \begin{compactitem}
 \item Changing the pin.
 \item Compilation and general use.
 \item Using variable threshold.
 \end{compactitem}
\end{compactitem}

\vfill\columnbreak

\begin{compactitem}
\item \textbf{Untested}:
 \begin{compactitem}
 \item Faulty situation for the ErrFlag to set.
 \end{compactitem}
\end{compactitem}

\vfill\columnbreak

\begin{compactitem}
\item \textbf{Not working}:
\end{compactitem}

\end{multicols}

\textbf{RPP API functions used:}

\begin{compactitem}
\item \texttt{rpp\_din\_setup()}.
\item \texttt{rpp\_din\_update()}.
\item \texttt{rpp\_din\_get()}.
\end{compactitem}

\textbf{Relevant demos:}

\begin{compactitem}
\item \texttt{digital\_passthrough}.
\item \texttt{hbridge\_digital\_control}.
\end{compactitem}

\newpage

\hypertarget{lout_digital_output_block}{}
\subsubsection{LOUT Digital Output block}

\begin{verbatim}
    Inputs      : 1
        bool    Digital Output

    Outputs     : 1
        bool    ErrFlag

    Parameters  : 1
        uint8   Pin number [1-8]
\end{verbatim}

This block allows to write to the digital outputs on the RPP board. The ErrFlag should raise if 
\texttt{rpp\_lout\_set()} or \texttt{rpp\_lout\_update()} returns error. Because the ErrFlag should never set, 
once set the following steps will never clear it back. \texttt{rpp\_lout\_update()} is called on each 
block, which is not the most efficient but guaranties consistent behavior.

\textbf{Status:}
\begin{multicols}{3}

\begin{compactitem}
\item \textbf{Tested}:
 \begin{compactitem}
 \item Changing the pin.
 \item Compilation and general use.
 \end{compactitem}
\end{compactitem}

\vfill\columnbreak

\begin{compactitem}
\item \textbf{Untested}:
 \begin{compactitem}
 \item Faulty situation for the ErrFlag to set.
 \end{compactitem}
\end{compactitem}

\vfill\columnbreak

\begin{compactitem}
\item \textbf{Not working}:
\end{compactitem}

\end{multicols}

\textbf{RPP API functions used:}

\begin{compactitem}
\item \texttt{rpp\_lout\_set()}.
\item \texttt{rpp\_lout\_update()}.
\end{compactitem}

\textbf{Relevant demos:}

\begin{compactitem}
\item \texttt{digital\_passthrough}.
\item \texttt{led\_blink\_all}.
\item \texttt{led\_blink}.
\end{compactitem}

\newpage

\hypertarget{ain_analog_input_block}{}
\subsubsection{AIN Analog Input block}

\begin{verbatim}
    Inputs      : 0
        None

    Outputs     : 2
        uint16  Analog Input
        bool    ErrFlag

    Parameters  : 1
        uint8   Pin number [1-12]
\end{verbatim}

This block allows to read the analog inputs on the RPP board. The ErrFlag should if raise 
\texttt{rpp\_ain\_update()} or \texttt{rpp\_ain\_get()} returns error. \texttt{rpp\_ain\_update()} is called just by the 
first DIN block in the model and thus only the first block could raise the flag because of this. 
In case an errors occurs the return value will always be 0. Because the ErrFlag should never set, 
once set the following steps will never clear it back.

\textbf{Status:}
\begin{multicols}{3}

\begin{compactitem}
\item \textbf{Tested}:
 \begin{compactitem}
 \item Changing the pin.
 \item Compilation and general use.
 \end{compactitem}
\end{compactitem}

\vfill\columnbreak

\begin{compactitem}
\item \textbf{Untested}:
 \begin{compactitem}
 \item Faulty situation for the ErrFlag to set.
 \end{compactitem}
\end{compactitem}

\vfill\columnbreak

\begin{compactitem}
\item \textbf{Not working}:
\end{compactitem}

\end{multicols}

\textbf{RPP API functions used:}

\begin{compactitem}
\item \texttt{rpp\_ain\_update()}.
\item \texttt{rpp\_ain\_get()}.
\end{compactitem}

\textbf{Relevant demos:}

\begin{compactitem}
\item \texttt{analog\_passthrough}.
\item \texttt{hbridge\_analog\_control}.
\item \texttt{log\_analog\_input}.
\end{compactitem}

\newpage

\hypertarget{aout_analog_output_block}{}
\subsubsection{AOUT Analog Output block}

\begin{verbatim}
    Inputs      : 1
        uint16  Analog Output

    Outputs     : 1
        bool    ErrFlag

    Parameters  : 1
        uint8   Pin number [1-4]
        bool    UseVoltage
\end{verbatim}

This block allows to write to the analog outputs on the RPP board. The UseVoltage flag allows the 
user to configure if block inputs should be interpreted as raw DAC value or millivolts. The ErrFlag 
should raise if \texttt{rpp\_aout\_update()} or \texttt{rpp\_aout\_set()} (or \texttt{rpp\_aout\_set\_voltage()} 
depending on block configuration) returns error. Because the ErrFlag should never set, once set the 
following steps will never clear it back.

\texttt{rpp\_aout\_update()} is called on each block but the implementation provides this to be efficient.

There is a know bug on the RPP Library, check \texttt{rpp\_aout\_update()} on the RPP API for details. 
Because of this, the outputs of the DACs are initialized on the first step of the model and not on 
the model initialization.

\textbf{Status:}
\begin{multicols}{3}

\begin{compactitem}
\item \textbf{Tested}:
 \begin{compactitem}
 \item Changing the pin.
 \item Changing voltage/value flag.
 \item Compilation and general use.
 \end{compactitem}
\end{compactitem}

\vfill\columnbreak

\begin{compactitem}
\item \textbf{Untested}:
 \begin{compactitem}
 \item Faulty situation for the ErrFlag to set.
 \end{compactitem}
\end{compactitem}

\vfill\columnbreak

\begin{compactitem}
\item \textbf{Not working}:
 \begin{compactitem}
 \item Initializing DACs on model's initialization.
 \end{compactitem}
\end{compactitem}

\end{multicols}

\textbf{RPP API functions used:}

\begin{compactitem}
\item \texttt{rpp\_aout\_setup()}.
\item \texttt{rpp\_aout\_set()}, or
\item \texttt{rpp\_aout\_set\_voltage()}.
\item \texttt{rpp\_aout\_update()}.
\end{compactitem}

\textbf{Relevant demos:}

\begin{compactitem}
\item \texttt{analog\_passthrough}.
\item \texttt{analog\_sinewave}.
\end{compactitem}

\newpage

\hypertarget{hbr_h_bridge_control_block}{}
\subsubsection{HBR H-Bridge Control block}

\begin{verbatim}
    Inputs      : 1
        double  Control

    Outputs     : 1
        bool    ErrFlag

    Parameters  : 0
        None
\end{verbatim}

This block allows to control the H-Bridge on the RPP board. The ErrFlag should raise only if
\texttt{rpp\_hbr\_control()} returns error. The H-Bridge is initialized with the default frequency 
(\~{}18kHz). A future improvement could include a parameter to set the frequency. Because the ErrFlag 
should never set, once set the following steps will never clear it back.

\textbf{Status:}
\begin{multicols}{3}

\begin{compactitem}
\item \textbf{Tested}:
 \begin{compactitem}
 \item Compilation and general use.
 \end{compactitem}
\end{compactitem}

\vfill\columnbreak

\begin{compactitem}
\item \textbf{Untested}:
 \begin{compactitem}
 \item Faulty situation for the ErrFlag to set.
 \end{compactitem}
\end{compactitem}

\vfill\columnbreak

\begin{compactitem}
\item \textbf{Not working}:
\end{compactitem}

\end{multicols}

\textbf{RPP API functions used:}

\begin{compactitem}
\item \texttt{rpp\_hbr\_enable()}.
\item \texttt{rpp\_hbr\_control()}.
\end{compactitem}

\textbf{Relevant demos:}

\begin{compactitem}
\item \texttt{hbridge\_analog\_control}.
\item \texttt{hbridge\_digital\_control}.
\item \texttt{hbridge\_sinewave\_control}.
\end{compactitem}

\newpage

\hypertarget{mout_power_output_block}{}
\subsubsection{MOUT Power Output block}

\begin{verbatim}
    Inputs      : 1
        bool    Power Output

    Outputs     : 1
        bool    ErrFlag

    Parameters  : 1
        uint8   Pin number [1-6]
\end{verbatim}

This block allows to write the power outputs (2A) on the RPP board. The ErrFlag should raise only 
if \texttt{rpp\_mout\_set()}returns error. Note that \texttt{rpp\_mout\_set()} returns error only if some bad 
parameter or in case it could detect a faulty condition on the pin in a very very short period of 
time after setting the value, see the function API for details. If the faulty condition persist on 
the next step the call will successfully detect the faulty condition and ErrFlag should set. 
Because the ErrFlag should never set, once set the following steps will never clear it back.

\textbf{Status:}
\begin{multicols}{3}

\begin{compactitem}
\item \textbf{Tested}:
 \begin{compactitem}
 \item Changing the pin.
 \item Compilation and general use.
 \end{compactitem}
\end{compactitem}

\vfill\columnbreak

\begin{compactitem}
\item \textbf{Untested}:
 \begin{compactitem}
 \item Faulty situation for the ErrFlag to set.
 \end{compactitem}
\end{compactitem}

\vfill\columnbreak

\begin{compactitem}
\item \textbf{Not working}:
\end{compactitem}

\end{multicols}

\textbf{RPP API functions used:}

\begin{compactitem}
\item \texttt{rpp\_mout\_set()}.
\end{compactitem}

\textbf{Relevant demos:}

\begin{compactitem}
\item \texttt{power\_toggle}.
\end{compactitem}

\newpage

\hypertarget{scir_serial_comm_interface_receive}{}
\subsubsection{SCIR Serial Comm. Interface Receive}

\begin{verbatim}
    Inputs      : 0
        None

    Outputs     : 2
        uint8   Data
        bool    ErrFlag

    Parameters  : 0
        None
\end{verbatim}

This block allows to receive a byte from the SCI. The ErrFlag should raise if \texttt{rpp\_sci\_read\_nb()}
doesn't succeed. The behavior of the ErrFlag is different from others blocks in that this block 
will set or clear the flag if the call fails of success at each step. Note that this block uses the
non-blocking call to read the SCI and thus will never cause an overrun.

\textbf{Status:}
\begin{multicols}{3}

\begin{compactitem}
\item \textbf{Tested}:
 \begin{compactitem}
 \item Receiving data.
 \item Compilation and general use.
 \item Faulty situation for the ErrFlag to set.
 \end{compactitem}
\end{compactitem}

\vfill\columnbreak

\begin{compactitem}
\item \textbf{Untested}:
\end{compactitem}

\vfill\columnbreak

\begin{compactitem}
\item \textbf{Not working}:
\end{compactitem}

\end{multicols}

\textbf{RPP API functions used:}

\begin{compactitem}
\item \texttt{rpp\_sci\_read\_nb()}.
\end{compactitem}

\textbf{Relevant demos:}

\begin{compactitem}
\item \texttt{echo\_char}.
\end{compactitem}

\newpage

\hypertarget{scis_serial_comm_interface_send}{}
\subsubsection{SCIS Serial Comm. Interface Send}

\begin{verbatim}
    Inputs      : 1
        uint8   Data

    Outputs     : 1
        bool    ErrFlag

    Parameters  : 2
        bool    UsePrintf
        string  PrintFormat [SETTING]
\end{verbatim}

This block allows to send a byte to the SCI or to print a formatted string that uses that byte. The
UsePrintf flag allows to user to select \texttt{rpp\_sci\_write\_nb()} (raw send) or \texttt{rpp\_sci\_printf()}
(formatted print) as the function the block should use on code generation. If UsePrintf is set the
PrintFormat string parameters SETTING is used as the format specifier. Note that this value is
inserted raw between quotes on code generation and thus there is no validation on it. User should
always put any valid integer specifier for the value on the input of the block.

The behavior of this block depends if UsePrintf is set or not. If set, the call \texttt{rpp\_sci\_printf()}
(a blocking call) could potentially overrun the step. Also, the ErrFlag will set only if
\texttt{rpp\_sci\_printf()} returns an error, and because it should never set, once set it will never
clear back. On the contrary, if UsePrintf is clear, the call \texttt{rpp\_sci\_write\_nb()} (non-blocking)
is used and thus the step cannot be overrun, but because is a best-effort call it cannot guarantee 
that all the data will be sent. In the case that not all data could be sent, the ErrFlag will set, 
but it will clear back if the next step is able to send all it's data (which with the current 
implementation is just one byte).

A possible future improvement for this block is to allow input to be non-scalar so user can print a 
whole string in one step using raw non-blocking write. This is currently possible if input 
configuration is adapted in S-Function and TLC. The problem this could pose is is that for printf 
user should include specifiers for all the cells in the non-scalar input, and if unknown, then 
printf cannot be used.

\textbf{Status:}
\begin{multicols}{3}

\begin{compactitem}
\item \textbf{Tested}:
 \begin{compactitem}
 \item Sending data.
 \item Compilation and general use.
 \end{compactitem}
\end{compactitem}

\vfill\columnbreak

\begin{compactitem}
\item \textbf{Untested}:
 \begin{compactitem}
 \item Faulty situation for the ErrFlag to set.
 \end{compactitem}
\end{compactitem}

\vfill\columnbreak

\begin{compactitem}
\item \textbf{Not working}:
\end{compactitem}

\end{multicols}

\textbf{RPP API functions used:}

\begin{compactitem}
\item \texttt{rpp\_sci\_write\_nb()}, or \texttt{rpp\_sci\_printf()}.
\end{compactitem}

\textbf{Relevant demos:}

\begin{compactitem}
\item \texttt{echo\_char} and \texttt{hello\_world}.
\end{compactitem}

\newpage

\hypertarget{scic_serial_comm_interface_configure}{}
\subsubsection{SCIC Serial Comm. Interface Configure}

\begin{verbatim}
    Inputs      : 0
        None

    Outputs     : 0
        None

    Parameters  : 1
        uint32  Baud rate
\end{verbatim}

This block allows to configure the baud rate of the SCI. There should only one block of this type 
per model, and this requirement is not validated, but the inclusion of several blocks is harmless 
and will just produce the baud rate to be changed several times, being the final baud rate to be 
the one of the last executed block. This block just executes on model initialization and not on 
each step.

\textbf{Status:}
\begin{multicols}{3}

\begin{compactitem}
\item \textbf{Tested}:
 \begin{compactitem}
 \item Changing baud rate.
 \item Compilation and general use.
 \end{compactitem}
\end{compactitem}

\vfill\columnbreak

\begin{compactitem}
\item \textbf{Untested}:
 \begin{compactitem}
 \item Using more than one block in a model.
 \end{compactitem}
\end{compactitem}

\vfill\columnbreak

\begin{compactitem}
\item \textbf{Not working}:
\end{compactitem}

\end{multicols}

\textbf{RPP API functions used:}

\begin{compactitem}
\item \texttt{rpp\_sci\_setup()}.
\end{compactitem}

\textbf{Relevant demos:}

\begin{compactitem}
\item \texttt{echo\_char}.
\item \texttt{hello\_world}.
\end{compactitem}

\newpage

\hypertarget{sdrw_sd_ram_write}{}
\subsubsection{SDRW SD-RAM Write}

\begin{verbatim}
    Inputs      : 1
        double  Data

    Outputs     : 1
        bool    ErrFlag

    Parameters  : 2
        uint8   Block ID
        string  PrintFormat [SETTING]
\end{verbatim}

This block allows to log a double value to the SD-RAM. User needs to provide a valid PrintFormat 
string to format and register the double value on the log. The PrintFormat string should include 
two specifiers:

\begin{compactitem}
\item For the block ID. Any valid integer specifier.
\item For the value to log. Any valid double specifier.
\end{compactitem}

Note that the value of PrintFormat is inserted raw between quotes on code generation and thus there 
is no validation on it. Error to provide a valid PrintFormat could generate compilation errors on 
even run-time errors (normally this generates a warning on compile time). Note that the function 
for logging used is \texttt{rpp\_sdr\_printf()}, which is a blocking call, and can potentially overrun the 
step. The ErrFlag will set if \texttt{rpp\_sdr\_printf()} returns an error (for example out of memory), 
but will clear back if the next step the call to this function is successful.

\textbf{Status:}
\begin{multicols}{3}

\begin{compactitem}
\item \textbf{Tested}:
 \begin{compactitem}
 \item Logging data.
 \item Compilation and general use.
 \end{compactitem}
\end{compactitem}

\vfill\columnbreak

\begin{compactitem}
\item \textbf{Untested}:
 \begin{compactitem}
 \item Faulty situation for the ErrFlag to set.
 \end{compactitem}
\end{compactitem}

\vfill\columnbreak

\begin{compactitem}
\item \textbf{Not working}:
\end{compactitem}

\end{multicols}

\textbf{RPP API functions used:}

\begin{compactitem}
\item \texttt{rpp\_sdr\_printf()}.
\end{compactitem}

\textbf{Relevant demos:}

\begin{compactitem}
\item \texttt{log\_analog\_input}.
\end{compactitem}

\newpage

\hypertarget{simulink_demos_library}{}
\section{Simulink Demos Library}

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.

\hypertarget{description}{}
\subsection{Description}

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.

The following table shows the current status of the demos:

\begin{center}\begin{tabular}{|l|l|l|}
\hline \textbf{Name} & \textbf{Implemented} & \textbf{Tested} \\
\hline analog\_passthrough & \multicolumn{1}{|c|}{YES} & \multicolumn{1}{|r|}{SUCCESS} \\
\hline analog\_sinewave & \multicolumn{1}{|c|}{YES} & \multicolumn{1}{|r|}{SUCCESS} \\
\hline digital\_passthrough & \multicolumn{1}{|c|}{YES} & \multicolumn{1}{|r|}{SUCCESS} \\
\hline echo\_char & \multicolumn{1}{|c|}{YES} & \multicolumn{1}{|r|}{SUCCESS} \\
\hline hbridge\_analog\_control & \multicolumn{1}{|c|}{YES} & \multicolumn{1}{|r|}{SUCCESS} \\
\hline hbridge\_digital\_control & \multicolumn{1}{|c|}{YES} & \multicolumn{1}{|r|}{SUCCESS} \\
\hline hbridge\_sinewave\_control & \multicolumn{1}{|c|}{YES} & \multicolumn{1}{|r|}{SUCCESS} \\
\hline hello\_world & \multicolumn{1}{|c|}{YES} & \multicolumn{1}{|r|}{SUCCESS} \\
\hline led\_blink\_all & \multicolumn{1}{|c|}{YES} & \multicolumn{1}{|r|}{SUCCESS} \\
\hline led\_blink & \multicolumn{1}{|c|}{YES} & \multicolumn{1}{|r|}{SUCCESS} \\
\hline log\_analog\_input & \multicolumn{1}{|c|}{YES} & \multicolumn{1}{|r|}{SUCCESS} \\
\hline power\_toggle & \multicolumn{1}{|c|}{YES} & \multicolumn{1}{|r|}{SUCCESS} \\
\hline \end{tabular}\end{center}

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

\hypertarget{subdirectory__content_description}{}
\subsection{Subdirectory  content description}

\noindent$\rightarrow$ \texttt{\{demo\}.slx}

A Simulink demo.

This subdirectory just includes all the Simulink demos described in the following section.

\newpage

\hypertarget{demos_reference}{}
\subsection{Demos Reference}

This section describes the demos implemented as part of this project that uses the Simulink RRP
Block Library and generates code using the RPP Simulink Target.

\hypertarget{analog_pass_through}{}
\subsubsection{Analog pass-through}

\begin{figure}[H]\begin{center}

\noindent\includegraphics[width=450px]{media/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 (AIN)\texttt{[110, 2400]} to the output domain
(AOUT)\texttt{[0, 4095]}.

\newpage

\hypertarget{analog_sinewave}{}
\subsubsection{Analog sinewave}

\begin{figure}[H]\begin{center}

\noindent\includegraphics[width=450px]{media/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. Siwave is 10Hz and sampling rate is set to
1000Hz (driven from Simulink step of 1ms, same as operating system). Amplitude is set to use AOUT
full range [0-4095] which means output amplitude will be [0-12] volts.

The Software oscilloscope shown should match an external one connected to AOUT 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.

\newpage

\hypertarget{digital_pass_through}{}
\subsubsection{Digital pass-through}

\begin{figure}[H]\begin{center}

\noindent\includegraphics[width=400px]{media/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.

\newpage

\hypertarget{echo_char}{}
\subsubsection{Echo char}

\begin{figure}[H]\begin{center}

\noindent\includegraphics[width=450px]{media/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.

\newpage

\hypertarget{h_bridge_analog_control}{}
\subsubsection{H-bridge analog control}

\begin{figure}[H]\begin{center}

\noindent\includegraphics[width=450px]{media/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 (AIN)\texttt{[110, 2400]} to the output domain
(HBR)\texttt{[-1.0, 1.0]}.

\newpage

\hypertarget{h_bridge_digital_control}{}
\subsubsection{H-bridge digital control}

\begin{figure}[H]\begin{center}

\noindent\includegraphics[width=450px]{media/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.

\newpage

\hypertarget{h_bridge_sine_wave_control}{}
\subsubsection{H-bridge sine wave control}

\begin{figure}[H]\begin{center}

\noindent\includegraphics[width=300px]{media/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.

\newpage

\hypertarget{hello_world}{}
\subsubsection{Hello world}

\begin{figure}[H]\begin{center}

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

\textbf{Description:}

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

\newpage

\hypertarget{led_blink}{}
\subsubsection{LED blink}

\begin{figure}[H]\begin{center}

\noindent\includegraphics[width=450px]{media/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.

\newpage

\hypertarget{led_blink_all}{}
\subsubsection{LED blink all}

\begin{figure}[H]\begin{center}

\noindent\includegraphics[width=350px]{media/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.

\newpage

\hypertarget{log_analog_input}{}
\subsubsection{Log analog input}

\begin{figure}[H]\begin{center}

\noindent\includegraphics[width=450px]{media/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.

\newpage

\hypertarget{power_toggle}{}
\subsubsection{Power toggle}

\begin{figure}[H]\begin{center}

\noindent\includegraphics[width=300px]{media/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.

\newpage

\hypertarget{glossary}{}
\section{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.

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

\newpage

\hypertarget{references}{}
\section{References}

\begin{itemize}
\item Horn, M. (2013). \textit{Software obsluhující periferie a flexray na automobilové rídicí jednotce}.
  (Unpublished master's thesis, Czech Technical University in Prague, Prague, Czech Republic).

\item \textit{Model-based design}. (n.d.). In Wikipedia. Retrieved March 10, 2013, from \newline{}
  \htmladdnormallink{http://en.wikipedia.org/wiki/Model-based\_design}{http://en.wikipedia.org/wiki/Model-based\_design}

\item (2012). \textit{ARM Assembly Language Tools}. Texas Instruments.

\item (2012). \textit{ARM Optimizing C/C++ Compiler}. Texas Instruments.

\item (2013). \textit{Embedded Coder - Reference}. MathWorks.

\item (2013). \textit{Embedded Coder - User's Guide}. MathWorks.

\item Barry, R. (2009). \textit{Using the FreeRTOS real time kernel - A practical guide}.

\item (2013). \textit{Simulink Coder - Reference}. MathWorks.

\item (2013). \textit{Simulink - Target Language Compiler}. MathWorks.

\item (2013). \textit{Simulink Coder - User's Guide}. MathWorks.

\item (2013). \textit{Simulink - Developing S-Functions}. MathWorks.

\item (2012). \textit{TMS570LS31x/21x 16/32-Bit RISC Flash Microcontroller - Technical Reference Manual}.
  Texas Instruments.
\end{itemize}

\newpage

\hypertarget{appendix_a_notes_on_freertos_memory_management}{}
\section{Appendix A: Notes on FreeRTOS memory management}

FreeRTOS provides 4 different (at the time of this writing) memory management implementations.
On vanilla distribution of FreeRTOS these can be found in
\texttt{$<$FreeRTOSRoot$>$/FreeRTOS/Source/portable/MemMang} with the names \texttt{heap\_1.c}, \texttt{heap\_2.c},
\texttt{heap\_3.c} and \texttt{heap\_4.c}. The user is supposed to choose one and rename it to \texttt{heap.c}
and include it in the port for the target processor. Memory management implementation of each file
is explained in depth in:

	\begin{quotation}
\htmladdnormallink{Memory Management}{http://www.freertos.org/a00111.html}
	\end{quotation}

The above is a must read documentation. In summary:

\noindent$\rightarrow$ \texttt{heap\_1.c}

\begin{compactitem}
\item Use a static allocated array for memory and thus will be placed on the \texttt{.bss} section.
\item Subdivides the array into smaller blocks as RAM is requested.
\item Memory cannot be freed.
\item Array is as large as \texttt{configTOTAL\_HEAP\_SIZE} option in \texttt{FreeRTOSConfig.h}.
\end{compactitem}

\noindent$\rightarrow$ \texttt{heap\_2.c}

\begin{compactitem}
\item Use a static allocated array for memory and thus will be placed on the \texttt{.bss} section.
\item Uses a best fit algorithm and allows previously allocated blocks to be freed.
\item It does \textbf{not} however combine adjacent free blocks into a single large block.
\item Array is as large as \texttt{configTOTAL\_HEAP\_SIZE} option in \texttt{FreeRTOSConfig.h}.
\end{compactitem}

\noindent$\rightarrow$ \texttt{heap\_3.c}

\begin{compactitem}
\item Wrapper around standard C library \texttt{malloc()} and \texttt{free()}.
\item Wrapper makes \texttt{malloc()} and \texttt{free()} functions thread safe.
\item Memory is as large as defined in linker for C system heap.
\item \texttt{configTOTAL\_HEAP\_SIZE} option in \texttt{FreeRTOSConfig.h} is ignored.
\end{compactitem}

\noindent$\rightarrow$ \texttt{heap\_4.c}

\begin{compactitem}
\item Use a static allocated array for memory and thus will be placed on the \texttt{.bss} section.
\item Uses a first fit algorithm.
\item It \textbf{does} combine adjacent free memory blocks into a single large block (it does include a
  coalescence algorithm).
\item Array is as large as \texttt{configTOTAL\_HEAP\_SIZE} option in \texttt{FreeRTOSConfig.h}.
\end{compactitem}

Not all kernels available for the RPP C Library use the same implementation. This is what each
kernel is currently configured to use:

\begin{center}\begin{tabular}{|r|c|c|}
\hline \textbf{Kernel} & \textbf{Origin} & \textbf{Implementation} \\
\hline 6.0.4 Posix & Simulator from OpenPilot.org & \texttt{heap\_3.c} \\
\hline 7.0.2 TMS570 & HalCoGen & \texttt{heap\_1.c} \\
\hline 7.4.0 TMS570 & HalCoGen & \texttt{heap\_4.c} \\
\hline 7.4.2 TMS570 & Adapted from vanilla distribution & \texttt{heap\_4.c} \\
\hline \end{tabular}\end{center}

The relevant implications of this are:

\begin{itemize}
\item If a kernel with \texttt{heap\_3.c} is used the Simulink model \textit{C system heap size} and
  \textit{Model step task stack size} should be tightly related and the first should be large enough to
  allocate system tasks and the stack for the stepping task.

\item If a kernel with \texttt{heap\_1.c} is used the programs should not delete tasks, queues or semaphores.
  If the application spawn and deletes tasks it will eventually deplete the memory available. This
  is the case with the \textit{rpp-test-suite}. Note that failure to allocated memory from the array
  will trigger the \textit{Malloc Failed Hook Function} \texttt{vApplicationMallocFailedHook()}, even if the
  implementation doesn't use the C system \texttt{malloc()} function. \newline{}
  Also, \textit{Model step task stack size} should never be set larger than \texttt{configTOTAL\_HEAP\_SIZE}
  option in \texttt{FreeRTOSConfig.h}. Currently the RPP Target doesn't include a GUI option for setting
  \texttt{configTOTAL\_HEAP\_SIZE} because the library is statically linked and thus memory will be of the
  size specified when built. The RPP Target \textbf{doesn't} check that the requested memory for the
  step task is less than the \texttt{configTOTAL\_HEAP\_SIZE}, and if greater then the application will
  fail at runtime and trigger the \textit{Malloc Failed Hook Function}.
\end{itemize}

\newpage

\hypertarget{appendix_b_known_operating_system_dependent_files}{}
\section{Appendix B: Known operating-system dependent files}

This project was developed on a GNU/Linux operating system. No test for cross-platform
interoperability was performed on the code developed. Although care was taken to try to provide
platform independent code and tools this are the elements that are know to be Linux dependent:

\begin{itemize}
\item LCM1 hardware control tool \texttt{lmc1.py}. \newline{}
  This tool is both GUI and command line capable, the following just affects the GUI part. \newline{}
  Command line should be usable under Windows systems.

  \underline{Cause}: Serial port search algorithm is Linux dependent and Gtk 3.0 dynamic Python bindings
             are not yet available on other operating systems.

\item TI CGT support file for RPP Simulink Target \texttt{target\_tools.mk}.

  \underline{Cause}: Use UNIX path separator \texttt{/}.

\item Simulink RPP Target download script \texttt{rpp\_download.m}.

  \underline{Cause}: Use UNIX path separator \texttt{/}.

\item Simulink RPP Target install script \texttt{rpp\_setup.m}.

  \underline{Cause}: Use UNIX path separator \texttt{/}.

\item Simulink RPP Block Library block compilation script \texttt{compile\_blocks.m}.

  \underline{Cause}: Call Matlab MEX executable with Unix name.

\item All CCS projects under \texttt{$<$repo$>$/rpp/lib/apps/}.
  \underline{Cause}: Paths are configure using UNIX path separator \texttt{/}.
\end{itemize}

\end{document}
