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