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