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