]> rtime.felk.cvut.cz Git - jenkicar/rpp-simulink.git/blob - doc/thesis/thesis.t2t
Finished the final report. Well, almost, just one section and done.
[jenkicar/rpp-simulink.git] / doc / thesis / thesis.t2t
1 Undergraduate Thesis
2 Carlos Jenkins
3 %%date(%B, %Y)
4
5 %!target: tex
6 %!style(xhtmls): media/themes/Clean/style.css
7 %!postproc(xhtmls): 'NEWPAGE' ''
8 %!nested(xhtmls): --libs syntaxhighlighter
9 %!options(tex): --enum-title --toc --toc-level 5
10 %!postproc(tex): '\.pdf\.png' '.pdf'
11 %!postproc(tex): 'NEWPAGE' '\\newpage'
12 %!postproc(tex): '-\$>\$' '\\noindent$\\rightarrow$'
13 %!postproc(tex): 'TAB' '\\hspace{1.0em}'
14 %!nested(tex): --docclass {article} --pdf
15
16 %S = Table of contents =[table_of_contents]
17
18 %DONE
19
20 %Table of contents
21 %%toc
22
23 NEWPAGE
24
25 %Table of figures
26 %tex% ''' \listoffigures
27
28 NEWPAGE
29
30 = Introduction =[introduction]
31
32 %DONE
33
34 This document describes the final results of the project ``Code generation for automotive rapid
35 prototyping platform using Matlab/Simulink".
36
37
38 == Background ==[background]
39
40 %DONE
41
42 Back in the beginning of 2012 a leading automotive company requested the Czech Technical University
43 to develop a Engine Control Unit (ECU) for automotive applications. Real-Time Systems group at the
44 Department of Control Engineering from the Faculty of Electrical Engineering developed a hardware
45 and Software platform to the needs of this industry. The hardware uses Texas Instruments
46 TMS570LS3137 CPU and is built with automotive standards and interfaces in mind. It uses a real-time
47 operating system and was directly programmed in C.
48
49 Nevertheless, in accordance to company policies the Software developed for the engine control unit
50 must be designed in a safe and auditable way. The company has the policy to implement the Software
51 for their system using Model-Based Design:
52
53         Model-Based Design (MBD) is a mathematical and visual method of addressing
54         problems associated with designing complex control, signal processing and
55         communication systems. It is used in many motion control, industrial equipment,
56         aerospace, and automotive applications. Model-based design is a methodology
57         applied in designing embedded software.
58
59 In order to meet this requirement an interaction layer between the platform and the Software the
60 company uses, Matlab/Simulink, must be implemented. This document describes the implementation of
61 this interaction system.
62
63 == Technologies involved ==[technologies_involved]
64
65 %DONE
66
67 + Matlab/Simulink data flow graphical programming language tool for modeling, simulating and
68   analyzing multidomain dynamic systems.
69 + Standard ANSI C programming.
70 + FreeRTOS real-time operating system.
71 + Texas Instruments TI Code Generation Tools (CGT).
72 + RPP in-house automotive hardware board using Texas Instruments TMS570LS3137 CPU.
73
74
75
76 NEWPAGE
77
78 == Objectives ==[objectives]
79
80 %DONE
81
82 Main objectives of this project are:
83
84 + Allow C code generation from Matlab/Simulink models for custom made hardware platform.
85 + Implement model blocks for some of the peripheral units of the board for use in Simulink
86   programming.
87
88
89 At the time of this writing the objectives of this project are considered successfully achieved.
90
91 == Benefits ==[benefits]
92
93 %DONE
94
95 Expected benefits of this project are:
96
97 + Enabling faster implementation and rapid-prototyping of Software components through the use of
98   model-based programming.
99 + Enabling better and clearer visualization of Software implementations for the hardware board
100   through models.
101 + Improve auditability of Software system for automotive applications.
102
103
104 At the time of this writing the benefits of this project are considered enabled.
105
106 == Final outcome ==[final_outcome]
107
108 %DONE
109
110 The main products generated for this project are:
111
112 - **C Support Library**: @@
113   Define the API to communicate with the board. Include drivers and operating system.
114
115 - **Simulink Coder Target**: @@
116   Allows Simulink model's code generation, compilation and download for the board.
117
118 - **Simulink Block Library**: @@
119   Set of blocks that allows Simulink models to use board IO and communication peripherals.
120
121 - **Simulink Demos Library**: @@
122   Collection of examples of control applications in form of Simulink models.
123
124
125 Each of this product is described deeply in the following sections.
126
127 NEWPAGE
128
129 == Document layout ==[document_layout]
130
131 %DONE
132
133 The general layout of this document is as follows:
134
135 - Project description, objectives and outcome. This section.
136 - Software and Hardware setup for development, repository layout and programming standards.
137 - A section for each of the four products delivered, with:
138  - Implementation fundamentals.
139  - Repository branch description.
140  - Product specific aspects.
141  - Reference documentation.
142 - Glossary.
143 - References.
144 - Appendices.
145
146
147 NEWPAGE
148
149 = Project setup =[project_setup]
150
151 %DONE
152
153 This sections describes the Software and Hardware aspects required to undertake development for
154 this project. It considers:
155
156 - Software development environment.
157 - Hardware reference documentation and wiring for development.
158 - Repository's general layout.
159
160
161 == Development environment ==[development_environment]
162
163 %DONE
164
165 This section describes the Software environment setup for development.
166
167 === Operating system ===[operating_system]
168
169 %DONE
170
171 This project was developed on a GNU/Linux operating system. For development it is recommended to
172 use a Debian based operating system for development as most of the tools are easily available from
173 repositories.
174
175 Relevant OS information on which this project was developed:
176
177 - Ubuntu 12.04.2 LTS AMD64.
178 - Kernel 3.2.0-48-generic.
179 - GCC version 4.6.3.
180
181
182 No test for cross-platform interoperability was performed on the code developed. Although care was
183 taken to try to provide platform independent code and tools there is elements known to be Linux
184 dependent. For a list of this elements refer to
185 [Appendix B: Known operating-system dependent files #appendix_b_known_operating_system_dependent_files].
186
187 === Version Control System ===[version_control_system]
188
189 %DONE
190
191 The version control system used for this project is **git**. The repository of this project
192 contains all the files produced during development, including documentation, references, code and
193 graphics. Also, the GUI application **giggle** was used to easily review changes. To install both
194 execute on a terminal:
195
196 {{{ bash
197 sudo apt-get install git giggle
198 }}}
199
200 NEWPAGE
201
202 === TI Code Composer Studio ===[ti_code_composer_studio]
203
204 %DONE
205
206 Code Composer Studio (CCS) is the official Integrated Development Environment (IDE) for developing
207 applications for Texas Instruments embedded processors. CCS is multiplatform Software based on
208 Eclipse Open Source IDE.
209
210 The version used in this project is the 5.3.0. Download and install CCS for Linux from:
211
212         http://processors.wiki.ti.com/index.php/Category:Code_Composer_Studio_v5
213
214 CCS download requires a valid MyTI account. Tedious. CCS download is about 1.5GB. Once downloaded
215 extract the content of the ``tar.gz`` archiver and run ``css_setup_<version>.bin`` script as
216 __root__. Installation must done as root in order to install driver set.
217
218 After installation the application can be executed with:
219
220 {{{ bash
221 cd <ccs>/ccsv5/eclipse/
222 ./ccstudio
223 }}}
224
225 If the application fails to start on 64bits systems is because CCS5 is a 32bits application a thus
226 requires 32bits libraries:
227
228 {{{ bash
229 sudo apt-get install libgtk2.0-0:i386 libxtst6:i386
230 }}}
231
232 If the application crashes with a segmentation fault edit file:
233
234 {{{ bash
235 nano <ccs>/ccsv5/eclipse/plugins/com.ti.ccstudio.branding_<version>/plugin_customization.ini
236 }}}
237
238 And change key ``org.eclipse.ui/showIntro`` to false.
239
240 Choose ``FREE License - for use with XDS100 JTAG Emulators" on the licensing options. Code download
241 for the board is uses that particular hardware. See [Development wiring #development_wiring] for
242 more details on this hardware.
243
244 CCS include Texas Instruments Code Generation Tools (CGT) (compiler, linker, etc). Simulink code
245 generation requires the CGT to be available in the system, and thus, even if no library development
246 will be done or the IDE is not going to be used CCS is still required. @@
247 See ``<repo>/rpp/rpp/README.txt`` file for more information.
248
249 You can find documentation for CGT compiler in ``<repo>/ref/armcl.pdf`` and for CGT archiver in
250 ``<repo>/ref/armar.pdf``.
251
252
253 === Matlab/Simulink ===[matlabsimulink]
254
255 %DONE
256
257 Matlab/Simulink version used is R2012b for Linux 64 bits. For in-house development the CVUT should
258 provide a network licensing server descriptor file.
259
260 === GtkTerm ===[gtkterm]
261
262 %DONE
263
264 Most of the interaction with the board for development is done through a RS-232 serial connection.
265 The terminal Software used for communication is called GtkTerm.
266
267 The default configuration for the board serial communication module is 9600-8-N-1. Note that the
268 RPP Library test suite is setup to 115200-8-N-1.
269
270 To install GtkTerm execute:
271
272 {{{ bash
273 sudo apt-get install gtkterm
274 }}}
275
276
277
278 === Doxygen ===[doxygen]
279
280 %DONE
281
282 Doxygen is the name of the documentation generator used to generate the RPP API documentation based
283 on the source code files. The generated API include dependency graphs and thus it also requires
284 Graphviz, a graph drawing tool. To install both execute:
285
286 {{{ bash
287 sudo apt-get install doxygen graphviz
288 }}}
289
290 See [API generation #api_generation] on how to use Doxygen to generate the API Reference
291 documentation.
292
293 NEWPAGE
294
295 === Nested ===[nested]
296
297 %DONE
298
299 Nested is the documentation editor used to create the document you're reading. It features a plain
300 text version control friendly simple to read non-cluttered format, WYSIWYM paradigm, divide and
301 conquer document creation approach, a nested (non-linear) document tree and content/presentation
302 separation scheme and thus documents can be published to LaTeX, PDF or HTML. Nested is a tool
303 created by the author of this report.
304
305 To install Nested first install dependencies:
306
307 {{{ bash
308 sudo apt-get install python2.7 python-gtk2 python-webkit python-gtkspellcheck texlive-publishers texlive texlive-latex-extra rubber iso-codes subversion
309 }}}
310
311 Then get the latest revision from the stable repository:
312
313 {{{ bash
314 svn checkout svn://svn.code.sf.net/p/nestededitor/code/trunk nested
315 }}}
316
317 Run Nested with:
318
319 {{{ bash
320 cd nested/nested/
321 ./nested
322 }}}
323
324 Nested sources for this document can be found on the repository under
325 ``<repo>/doc/reports/report/``.
326
327
328 === LMC1 ===[lmc1]
329
330 %DONE
331
332 The LMC1 is a simple script developed for this project written in Python 3 using Gtk+ 3.0 Python
333 dynamic bindings PyGObject. This script, based on Michal Horn's command line script, allows to set
334 or clear the outputs of the test board.
335
336 This script includes both a GUI and command line tool. If no parameters are given to the script the
337 GUI version is launched:
338
339 %tex% ''' \begin{figure}[H]\begin{center}
340 [350-lmc1.png]
341 %tex% ''' \caption{LMC1 GUI application.}\end{center}\end{figure}
342
343 To run the LMC1 application first install dependencies:
344
345 {{{ bash
346 apt-get install python3 python3-gi python3-serial
347 }}}
348
349 To launch LMC1 GUI version double click file:
350
351 ``<repo>/rpp/lib/apps/lmc1/lmc1.py``
352
353 To launch LMC1 command line version type:
354
355 ``<repo>/rpp/lib/apps/lmc1/lmc1.py --help``
356
357
358 NEWPAGE
359
360 == Hardware reference ==[hardware_reference]
361
362 %DONE 
363
364 This section provides reference documentation for the RPP board:
365
366 - Connectors pinout.
367 - Modules capabilities and features.
368 - Wiring configuration for development and testing.
369
370
371 Please note that although this is a hardware reference documentation this is from a Software
372 development perspective and __**NOT**__ Hardware development perspective. For full hardware details
373 please refer to schematics and related documentation.
374
375 %tex% ''' \begin{figure}[H]\begin{center}
376 [300-board.png]
377 %tex% ''' \caption{The RPP board (signal connector missing).}\end{center}\end{figure}
378
379 === Connectors pinout ===[connectors_pinout]
380
381 %DONE
382
383 %tex% ''' \begin{figure}[H]\advance\leftskip-1cm
384 [530-pinout.pdf.png]
385 %tex% ''' \caption{The RPP connectors pinout.}\end{figure}
386
387
388 === Modules description ===[modules_description]
389
390 %DONE
391
392 This section enumerates the capabilities of the hardware modules from Software perspective.
393
394 ==== Logic IO ====[logic_io]
395
396 %DONE
397
398 ===== Digital Inputs (DIN) =====[digital_inputs_din]
399
400 %DONE
401
402 - 16 pins available on Signal Connector.
403 - Pins 9-16 status can be read via GPIO using configurable threshold. @@
404   Pins 9-12 use variable threshold B and pins 13-16 use variable threshold A.
405 - Variable threshold is a DAC chip MCP4922.
406 - All pins are read at once via SPI (fixed threshold) using chip MC33972.
407 - 1-8 are programmable pins and ca be set to pull-up or pull-down. 9-16 are pull-down only.
408 - All pins can be set to be active or tri-stated.
409 - All pins can be set to trigger interrupt.
410 - On-line diagnostic of broken wire.
411
412
413 ===== Digital Outputs (LOUT) =====[digital_outputs_lout]
414
415 %DONE
416
417 - 8 pins available on Signal Connector.
418 - Pins for logic output only, up to 100mA.
419 - All pins are set at once using a chip through SPI.
420
421
422 ===== Analog Input (AIN) =====[analog_input_ain]
423
424 %DONE
425
426 - 12 channels available.
427 - Differential inputs, thus 24 pins available on Signal Connector.
428 - Range for 0-20 volts.
429 - 12 bits resolution.
430 - Using CPU ADC.
431
432 ===== Analog Output (AOUT) =====[analog_output_aout]
433
434 %DONE
435
436 - 4 pins available on Signal Connector.
437 - Output range is 0-12 volts.
438 - Using 2 x MCP4922 DACs controlled using SPI.
439 - Resolution is 12 bits. But because of amplification and voltage reference not all range is used.
440
441
442 ==== Power Output ====[power_output]
443
444 %DONE
445
446 ===== H-Bridge (HBR) =====[h_bridge_hbr]
447
448 %DONE
449
450 - 1 port (2 pins) available on Power Connector.
451 - Communication is done through SPI.
452 - H-Bridge can be enabled or disabled.
453 - Current direction can be set.
454 - PWM control with 1% resolution change of the duty cycle.
455 - Port can drive load up to 10A.
456
457 ===== Power Output (MOUT) =====[power_output_mout]
458
459 %DONE
460
461 - 6 pins available on Power Connector.
462 - Pins can drive a load up to 2A. Push/Pull.
463 - Pins are set using 6 CPU output GPIOs. Diagnostic are read using 6 externally pulled-up
464   open-drain input GPIOs.
465 - On-line diagnostics. Driver chip will pull-down the corresponding diagnostic pin on the CPU.
466
467
468 ===== High-Power Output (HOUT) =====[high_power_output_hout]
469
470 %DONE
471
472 - 6 pins available on Power Connector.
473 - Pins can be set ON/OFF.
474 - Pins can drive a load up to 10A with PWM.
475 - System can read analog values of current flowing (IFBK).
476 - System can read diagnostics values (DIAG). Detection of a fault condition.
477
478
479 ==== Communication ====[communication]
480
481 %DONE
482
483 ===== CAN bus (CAN) =====[can_bus_can]
484
485 %DONE
486
487 - 3 ports available (CAN uses differential signaling) thus 6 pins are available on Communication
488   connector.
489 - High speed.
490 - Recover from error.
491 - Detection of network errors.
492
493
494 ===== Local Interconnect Network (LIN) =====[local_interconnect_network_lin]
495
496 %DONE
497
498 - 2 ports/pins available on Communication Connector.
499 - Only first port can be used when using the SCI. Second port us shared with SCI.
500
501
502 ===== FlexRay (FR) =====[flexray_fr]
503
504 %DONE
505
506 - 2 ports available. FlexRay uses differential signaling thus 4 pins are available on
507   Communication Connector.
508
509
510
511 ===== Serial Comm. Interface (SCI) =====[serial_comm_interface_sci]
512
513 %DONE
514
515 - 1 port available inside the box on SCI connector (4 pins).
516 - Variable baud rate. Tested on 9600 and 115200.
517 - RS232 standard compatible.
518
519 ===== Ethernet (ETH) =====[ethernet_eth]
520
521 %DONE
522
523 - 1 port available. Standard Ethernet connector available inside box.
524
525
526 NEWPAGE
527
528 ==== Data storage/logging ====[data_storagelogging]
529
530 %DONE
531
532 ===== External Memory SD-RAM (SDR) =====[external_memory_sd_ram_sdr]
533
534 %DONE 
535
536 - 64MB (currently installed) external RAM used for logging. Maximal supported capacity is 256MB.
537 - Memory test routine available with test Software.
538
539
540 ===== SD Card (SDC) =====[sd_card_sdc]
541
542 %DONE
543
544 - Standard SD-Card connector or microSD connector available inside box.
545 - Communication done using SPI.
546
547
548 NEWPAGE
549
550 === Development wiring ===[development_wiring]
551
552 %DONE
553
554 For development, the RPP board needs to be wired as follow:
555
556 - **Power input**: supply around 13 volts on any PWR pin (Power and Communication connectors) and 
557   connect GND to power supply's GND. See [Connectors pinout #connectors_pinout].
558 - **Serial communication**: board serial interface connected to a RS-232 port on the host computer 
559   (``/dev/ttySX``) or to a USB converter (``/dev/ttyUSBX``).
560 - **Debug and code download**: XDS100v2 JTAG Emulator connected to RPP board JTAG connector, 
561   which in turn is connected through USB to the host computer (``/dev/ttyUSBX``). 
562   See below on details for configuring the XDS100v2 on Linux.
563
564
565 Image of the wiring:
566
567 %tex% ''' \begin{figure}[H]\begin{center}
568 [300-dev_wiring.png]
569 %tex% ''' \caption{RPP Wiring for Development.}\end{center}\end{figure}
570
571
572 Setup XDS100v2 on Linux:
573
574 By default the device (if nothing more connected then ``/dev/ttyUSB0``) is added with permissions 
575 ``664`` and ``root`` as user and group. To access the device write access for current user is 
576 required. To do so create a new udev rule file:
577
578 {{{ bash
579 sudo nano /etc/udev/rules.d/45-pes-rpp.rules
580 }}}
581
582 NEWPAGE
583 And add line:
584
585 {{{ plain
586 SUBSYSTEM=="usb", ATTR{idVendor}=="0403", ATTR{idProduct}=="a6d0", MODE="0660", GROUP="plugdev"
587 }}}
588
589 Then reload udev rules with:
590
591 {{{ bash
592 sudo udevadm control --reload-rules
593 }}}
594
595
596 To check device properties like ``idVendor`` or ``idProduct`` issue the following command:
597
598 {{{ bash
599 udevadm info -a -p $(udevadm info -q path -n /dev/ttyUSB0)
600 }}}
601
602
603 === Test wiring ===[test_wiring]
604
605 %DONE
606
607 Wiring for test differ from testing objectives. It test performed for this project no communication
608 test, besides SCI, was performed. The following describes how to wire each of the modules tested:
609
610 - **DIN**: @@
611   Connect all DIN pins to one LMC1 board outputs.
612 - **LOUT**: @@
613   Connect all LOUT pins to one LMC1 board inputs.
614 - **AIN**: @@
615   Connect all low pins to GND and leave all high pins floating. Allow to hook a potentiometer
616   to each pin.
617 - **AOUT**: @@
618   Connect all 4 pins to different channels on a oscilloscope.
619 - **HBR**: @@
620   Connect a motor to the H-bridge pins.
621 - **MOUT**: @@
622   Connect all 6 pins to a LMC1 board inputs. Another option is to connect a motor to one of the 
623   outputs.
624 - **SCI**: @@
625   Connect the SCI to a host computer. See [Development wiring #development_wiring].
626 - **SDR**: @@
627   No particular wiring is required for testing the SD-RAM.
628
629
630 It is recommended to setup a power bus using regulated 12volts from Signal Connector. Power the 
631 LMC1 boards and the potentiometer with this bus. The LCM1 controller board should be connected
632 to the host computer through a RS-232 port or a USB converter.
633
634 NEWPAGE
635
636 %tex% ''' \begin{figure}[H]\advance\leftskip-1cm
637 [530-test_wiring.png]
638 %tex% ''' \caption{RPP Wiring for Testing.}\end{figure}
639
640 NEWPAGE
641
642 == Project repository ==[project_repository]
643
644 %DONE
645
646 This git repository holds all the work done on this project.
647
648 To get the repository:
649
650         ``git clone ssh://git@rtime.felk.cvut.cz/jenkicar/rpp-simulink.git``
651
652 This is a private repository, you require your SSH private key to be authorized. For access please
653 consult the Real-Time Systems Group, Department of Control Engineering, Faculty of Electrical
654 Engineering, Czech Technical University in Prague. For details about this git server refer to:
655
656         http://rtime.felk.cvut.cz/hw/index.php/Git_repository_on_this_server
657
658 The general layout of the repository is:
659
660 ```
661         .
662         |__ doc         - Documentation created for this project.
663         |__ refs        - Official reference documentation.
664         \__ rpp
665             |__ blocks  - Simulink Block Set.
666             |__ demos   - Simulink Demos Library.
667             |__ lib     - C support Library and API.
668             \__ rpp     - Simulink Coder Target.
669 ```
670
671 A detailed description of the content of each subfolder under ``rpp/`` can be found in the section
672 //Subdirectory content description// on each dedicated section for the products developed.
673
674 In this document, the root folder on this repository is used as reference for file location and is
675 referred with the token ``<repo>``.
676
677
678 %S == Programming standards ==[programming_standards]
679
680
681
682 %S === TLC files ===[tlc_files]
683
684
685
686 %S === RPP API ===[rpp_api]
687
688
689
690 %S === S-Functions ===[s_functions]
691
692 NEWPAGE
693
694 = C Support Library =[c_support_library]
695
696 %DONE
697
698 The RPP C Support Library define the API to communicate with the board. It include drivers and
699 operating system. This section documents the implementation of this library.
700
701 == Description ==[description]
702
703 %DONE
704
705 The RPP Library is the support library used by Simulink models. It is designed from the board user
706 perspective and exposes a simplified high-level API to handle the board's peripheral modules in a
707 safe manner.
708
709 The library as a concept and as a functional unit was introduced by this project. At the beginning
710 of this project the RPP board had just one application developed for. This application intended for
711 board testing allows the user to issue low-level commands to control and test the peripherals of
712 the board. This application was created using a combination of custom code, contributed drivers and
713 generated code from TI tool HalCoGen. Library functionality, like drivers and hardware access, and
714 application logic, like command processor and test routines, was largely merged in a single layer,
715 166 source code files long highly coupled application. In order to develop independent applications
716 for the RPP board, as it was expected to be each Simulink model, the library logic needed to be
717 separated from the application logic. This work implied a heavy refactoring on the testing
718 application in order extract from it the library functionality. Because the application files were
719 highly coupled in a single layer the refactoring and testing of the library implied roughly 70% of
720 the work done on this project.
721
722 %tex% ''' \begin{figure}[H]\advance\leftskip-1cm
723 [500-adc_dep_before.png]
724 %tex% ''' \caption{Dependency graph of the ADC driver before refactoring.}\end{figure}
725
726 The above graph shows the dependencies of the ADC driver before the refactoring. Please note the
727 dependency on ``cmdproc_io_tisci.h`` and ``cmdproc.h``, both application level modules. Also, note
728 the indirect dependency on the Operating System is being resolved through the application modules.
729
730 %tex% ''' \begin{figure}[H]\begin{center}
731 [150-adc_dep_after.png]
732 %tex% ''' \caption{Dependency graph of the ADC driver after refactoring.}\end{center}\end{figure}
733
734 The above graph shows the current dependencies for the ADC driver in the RPP Library. Please note
735 that it dependents only on the system layer low-level driver and that the Operating System indirect
736 dependency is resolved through the library foundations ``base.h``.
737
738 Some other relevant changes introduced with the refactoring are:
739
740 - ADC driver was completely rewritten.
741 - MOUT driver was implemented.
742 - DIN driver was slightly modified and extended.
743 - DAC driver was slightly modified.
744 - HBR driver was largely modified (in particular watchdog functionality).
745 - SCI driver was refactored and extended.
746 - SDR driver was implemented.
747
748
749 Also, once the library functionality could be isolated, the resulting API was too low-level to be
750 used by applications, in consequence one of the contributions of this projects was the
751 implementation of a high-level API on top of this low level API: the RPP Layer.
752
753
754 NEWPAGE
755
756 === Architecture ===[architecture]
757
758 %DONE
759
760 The RPP library was structured into 5 layers with the following guidelines:
761
762 - Top-down dependency only. No lower layer depends on anything from upper layers.
763 - 1-1 layer dependency only. The top layer depends exclusively on the bottom layer, not on any
764   lower level layer (except for a couple of exceptions).
765 - Each layer should provide a unified layer interface (``rpp.h``, ``drv.h``, ``hal.h``, ``sys.h``
766   and ``os.h``), so top layers depends on that layer interface and not on individual elements from
767   that layer.
768
769
770 %tex% ''' \begin{figure}[H]\begin{center}
771 [250-layers.pdf.png]
772 %tex% ''' \caption{The RPP library layers.}\end{center}\end{figure}
773
774
775 As a consequence of this division the source code files and interface files are now placed on
776 private directories so the previous prefix based inclusion ``drv_din.h`` is replaced by
777 ``drv/din.h``. With this organization user applications only needs to include the top layer
778 interface file (``rpp/rpp.h``) to be able to use the library API.
779
780 Please note the sublayer uLut, which is used only by the SPI driver in order to use thread safe
781 queue mechanisms. Because the FreeRTOS already provides thread safe queues and in order to match
782 the order parts of the system it would be advisable to drop this dependency in the future.
783
784 NEWPAGE
785
786 === RPP Layer Modules ===[rpp_layer_modules]
787
788 %DONE
789
790 The RPP Layer was structured into 14 different modules from 4 different categories that match the
791 hardware modules on the board:
792
793 || Category      | Description                        | MNEMONIC
794  | Logic IO      | Digital Input                      | ``[DIN ]``   |
795  |               | Digital (Logic) Output             | ``[LOUT]``   |
796  |               | Analog Input                       | ``[AIN ]``   |
797  |               | Analog Output                      | ``[AOUT]``   |
798  | Power output  | H-Bridge output                    | ``[HBR ]``   |
799  |               | Power output (12V, 2A)             | ``[MOUT]``   |
800  |               | High-Power output (12V, 10A)       | ``[HOUT]``   |
801  | Communication | CAN Bus                            | ``[CAN ]``   |
802  |               | LIN (Local Interconnect Network)   | ``[LIN ]``   |
803  |               | FlexRay                            | ``[FR  ]``   |
804  |               | Serial Communication Interface     | ``[SCI ]``   |
805  |               | Ethernet                           | ``[ETH ]``   |
806  | Logging       | SD Card                            | ``[SDC ]``   |
807  |               | SD-RAM                             | ``[SDR ]``   |
808
809
810 Please note the mnemonic of each module, as they are constantly used on the Software and
811 documentation. Also note that only the following modules were implemented as part of this project:
812
813 %tex% ''' \begin{multicols}{2}
814 - DIN.
815 - LOUT.
816 - AIN.
817 - AOUT.
818 - HBR.
819 - MOUT.
820 - SCI.
821 - SDR.
822
823
824 %tex% ''' \end{multicols}
825
826 Modules for which there is a low-level API available on the library but no high-level module was
827 implemented:
828
829 %tex% ''' \begin{multicols}{2}
830 - CAN.
831 - LIN.
832 - FR.
833
834
835 %tex% ''' \end{multicols}
836
837 Modules that are not yet available on the library at all:
838
839 %tex% ''' \begin{multicols}{2}
840 - ETH (in the works).
841 - SDC.
842 - HOUT (partial).
843
844
845 %tex% ''' \end{multicols}
846
847 The following graphic shows the library modules and the connectors on the hardware they map to.
848
849 %tex% ''' \begin{figure}[H]\advance\leftskip-1cm
850 [500-blocks.pdf.png]
851 %tex% ''' \caption{The RPP layer modules.}\end{figure}
852
853 NEWPAGE
854
855 === OS interchangeable layer ===[os_interchangeable_layer]
856
857 %DONE
858
859 The OS Layer is composed by the FreeRTOS source code files. Because the FreeRTOS exposes an stable
860 API the OS layer can be changed in order to upgrade the Operating System or use a different port of
861 the OS, without changing the upper layers source code. The OS Layers currently available for the
862 RPP Library at ``<repo>/rpp/lib/os/`` at the time of this writing are:
863
864 - Version 6.0.4 using POSIX port. This layer is the one that should be used when compiling a
865   program for x86(_64) simulation. The port uses the ``pthread`` library and because of this the
866   port is not true real time and this is considered a simulator.
867 - Version 7.0.2 using HalCoGen port for TMS570. This layer is the one currently supported and
868   tested. It was originally included in the testing application and was generated by an older
869   version of TI code generation tool HalCoGen.
870 - Version 7.4.0 using HalCoGen port for TMS570. This layer was extracted from a newly generated
871   project using a newer version of HalCoGen. This layer is untested but //should// work out of the
872   box.
873 - Version 7.4.2 using ARM Cortex R4 official port for CCS. This layer was created from vanilla
874   FreeRTOS 7.4.2 release. It is tested but non-working. Ticks are proved to be executed in time but
875   applications using this kernel runs at full-speed. The reason if this is currently unknown.
876
877
878 The general layout of all the layers are as following:
879
880 - Common source code (kernel):
881
882 ```
883     src/os/croutine.c (Optional)
884     src/os/list.c
885     src/os/queue.c
886     src/os/tasks.c
887     src/os/timers.c (Optional)
888 ```
889
890 Originally found in vanilla distribution in: ``<FreeRTOSRoot>/FreeRTOS/Source``
891
892 - Common interface files:
893
894 ```
895     include/os/croutine.h
896     include/os/FreeRTOS.h
897     include/os/list.h
898     include/os/mpu_wrappers.h
899     include/os/portable.h (with minor editions)
900     include/os/projdefs.h
901     include/os/queue.h
902     include/os/semphr.h
903     include/os/StackMacros.h
904     include/os/task.h
905     include/os/timers.h
906 ```
907
908 Originally found in vanilla distribution in: ``<FreeRTOSRoot>/FreeRTOS/Source/include``
909
910 - Memory management file:
911
912 ```
913     src/os/heap.c (One of 4 version available, see Appendix A).
914 ```
915
916 Originally found in vanilla distribution in: ``<FreeRTOSRoot>/FreeRTOS/Source/portable/MemMang``
917
918 - Port specific files:
919
920 ```
921     src/os/port.c
922     src/os/portASM.asm
923     include/os/portmacro.h
924     include/os/FreeRTOSConfig.h
925 ```
926
927 This depend of the port. In the case of the 7.4.2 TMS570 / ARM Cortex R4 for CCS port:
928
929  - First three files can be found in vanilla distribution in @@
930    ``<FreeRTOSRoot>/FreeRTOS/Source/portable/CCS/ARM_Cortex-R4``.
931  - Last file in ``<FreeRTOSRoot>/FreeRTOS/Demo/CORTEX_R4_RM48_TMS570_CCS5``.
932
933
934 In general, the following changes were applied to the source code base of all kernels:
935
936 - Replaced include directives to adapt to RPP library standard:
937
938 ``#include "`` with ``#include "os/``
939
940 - Line ending character set to UNIX '\n' and tabs replaced by 4 spaces.
941
942
943 NEWPAGE
944
945 === API development guidelines ===[api_development_guidelines]
946
947 %DONE
948
949 %tex% ''' \vspace{-0.40cm}
950
951 The following are the development guidelines use for developing the RPP API:
952
953 - User documentation should be placed in header files, not in source code, and should be Doxygen
954   formatted using autobrief. Documentation for each function present is mandatory.
955 - Function declarations on the headers files is for public functions only. Do not declare
956   local/static/private functions on the header.
957 - Documentation on source code files should be non-doxygen formatted and intended for developers,
958   not users. Documentation here is optional and at the discretion of the developer.
959 - Always use standard data types for IO when possible. Use custom structs as very last resort.
960 - Use prefix based functions names to avoid clash. The prefix is of the form ``[layer]_[module]_``,
961   for example ``rpp_din_update()`` for the update function of the DIN module in the RPP Layer.
962 - To be very careful about symbol export. Because it is used as a static library the modules should
963   not export any symbol that is not intended to be used (function) or ``extern``'ed (variable) from
964   application. As a rule of thumb declare all global variables as static.
965 - Only the RPP Layer symbols are available to user applications. All information related to lower
966   layers is hidden for the application. This is accomplished by conditionally including the layers
967   elements on the implementations files only and never on the interface files. Never expose any
968   other layer to the application or the the whole system below that layer will be exposed. In other
969   words, never ``#include "foo/foo.h"`` in any RPP Layer interface file.
970 - Any module is conditionally included by using ``rppCONFIG_INCLUDE_{MNEMONIC}`` directive on the
971   ``RppConfig.h`` configuration file.
972
973
974 %tex% ''' \vspace{-0.40cm}
975
976 === Further improvements ===[further_improvements]
977
978 %DONE
979
980 %tex% ''' \vspace{-0.40cm}
981
982 The following are recommendations for future improvements of the library:
983
984 - General code revision to remove local-only methods and variables from being exported.
985 - General code revision and refactoring to normalize the functions naming scheme. Normalize DRV and
986   HAL to use prefix based scheme, not all the functions and exported variables do. Refactor the SYS
987   layer, most of it generated by HalCoGen and that uses ``thisNamingScheme`` to use library
988   standards (see [RPP API #rpp_api] programming standards).
989 - Simplify doxygen documentation on the SYS layer, because is clunky, doesn't add any value and is
990   repetitive. Move it to the header files.
991 - Remove error throwing from wrong parameter input in the DRV layer and assume a
992   //correct parameter and continue// safe approach. Move all error throwing and validation to the
993   RPP layer (already implemented).
994
995
996 %tex% ''' \vspace{-0.40cm}
997 Recommendations for changes on the electrical diagrams:
998
999 - Change name of GPIO MOUT1_EN to MOUT1_DIAG.
1000 - Change name of GPIO MOUT1_IN to MOUT1_EN.
1001
1002
1003 The current names are misleading.
1004
1005 == Subdirectory  content description ==[subdirectory__content_description]
1006
1007 %DONE
1008
1009 -> ``librpp.a`` and ``rpp-lib.lib``
1010
1011 Version controlled RPP static libraries.
1012
1013 The first one is for POSIX simulation, the second one for Simulink models and other ARM/TMS570
1014 applications. This files are placed here by the projects ``apps/rpp-lib_posix`` and
1015 ``apps/rpp-lib`` when built.
1016
1017
1018 -> ``apps/``
1019
1020 Applications related to the RPP library.
1021
1022 This include the CCS studio project for generation of the static library and the test suite. See
1023 [Static libraries #static_libraries], [Test Suite #test_suite] and
1024 [Base application #base_application] for more information.
1025
1026
1027 -> ``os/``
1028
1029 OS layers directory.
1030
1031 See [OS interchangeable layer #os_interchangeable_layer] for more information.
1032
1033
1034 -> ``rpp/``
1035
1036 Main directory for the RPP Library.
1037
1038
1039 -> ``rpp/doc/``
1040
1041 Documentation directory for the RPP Library. See [API generation #api_generation] for more
1042 information.
1043
1044
1045 -> ``rpp/TMS570LS3137.ccxml``
1046
1047 Descriptor for code download.
1048
1049 This file is used by all the projects including the Simulink RPP Target for code download. It is
1050 configured to use the Texas Instruments XDS100v2 USB Emulator. See
1051 [Development wiring #development_wiring] for information about this hardware.
1052
1053
1054 -> ``rpp/TMS570LS313xFlashLnk.cmd``
1055
1056 CGT Linker command file.
1057
1058 This file is used by all applications linking for the board, including the Simulink models, static
1059 library and test suite. It includes instructions for the CGT Linker on where to place sections
1060 and size of some sections.
1061
1062
1063 -> ``rpp/include/{layer}`` and ``rpp/src/{layer}``
1064
1065 Interface files and implementations files for given ``{layer}``. See below for details on the RPP 
1066 Layer.
1067
1068
1069 -> ``rpp/include/rpp/rpp.h``
1070
1071 Main library header file.
1072
1073 To use this library just include this file and this file only. Also, before using any library
1074 function please call ``rpp_init()`` function for hardware initialization.
1075
1076
1077 -> ``rpp/include/rpp/RppConfig.h``
1078
1079 Library configuration file.
1080
1081 Please refer to the API documentation and header file comments for specific documentation for each
1082 configuration parameter.
1083
1084
1085 -> ``rpp/include/rpp/rpp_{mnemonic}.h``
1086
1087 Header file for ``{mnemonic}`` module.
1088
1089 This files includes function definitions, pin definitions, etc, specific to {mnemonic} module. The
1090 inclusion of this header can be configured in ``RppConfig.h`` using
1091 ``rppCONFIG_INCLUDE_{MNEMONIC}`` directive. See
1092 [API development guidelines #api_development_guidelines].
1093
1094
1095 -> ``rpp/src/rpp/rpp_{mnemonic}.c``
1096
1097 Module implementation.
1098
1099 Implementation of ``rpp_{mnemonic}.h``'s functions on top of the DRV library. See
1100 [API development guidelines #api_development_guidelines].
1101
1102
1103 -> ``rpp/src/rpp/rpp.c``
1104
1105 Implementation of library-wide functions.
1106
1107
1108 NEWPAGE
1109
1110
1111 == Test Suite ==[test_suite]
1112
1113 %DONE
1114
1115 The ``rpp-test-suite`` is a RPP application developed as part of this project that includes a
1116 series of test tasks or test commands to verify the correct behavior and functionality of the RPP
1117 layer modules. There is one command per module, and the command use the same mnemonic that the
1118 module.
1119
1120 This test suite can be found in ``<repo>/rpp/lib/apps/rpp-test-suite`` for the ARM version and in
1121 ``<repo>/rpp/lib/apps/rpp-test-suite_posix`` for the simulated version.
1122
1123 The application enables a command processor using the SCI at **115200-8-N-1**:
1124
1125 ```
1126 RPP Library Test Suite.
1127 ===========================================================
1128 [Type a module to test or 'help']
1129 --> help
1130 Available commands:
1131         help - Display this help.
1132         ain  - Test Analog Input.
1133         aout - Test Analog Output.
1134         can  - Test CAN communication.
1135         din  - Test Digital Inputs.
1136         eth  - Test Ethernet communication.
1137         fr   - Test FlexRay communication.
1138         hbr  - Test H-Bridge.
1139         hout - Test High Power Output.
1140         lin  - Test LIN communication.
1141         lout - Test Digital Outputs.
1142         mout - Test Power Outputs.
1143         sci  - Test Serial Communication Interface.
1144         sdc  - Test SD-Card.
1145         sdr  - Test SD-RAM.
1146 ```
1147
1148 Current modules with tests implemented are:
1149
1150 %tex% ''' \begin{multicols}{2}
1151 - AIN.
1152 - AOUT.
1153 - DIN.
1154 - HBR.
1155 - LOUT.
1156 - MOUT.
1157 - SCI. (the test-suite itself)
1158 - SDR.
1159
1160
1161 %tex% ''' \end{multicols}
1162
1163 A note of warning: tests spawn OS tasks at the beginning of the test and deletes them at the end.
1164 Because current memory memory management implementation cannot free memory the test suite will
1165 fill all the memory and tests will be unable to start. In this case just reset the board. See
1166 [Appendix A: Notes on FreeRTOS memory management #appendix_a_notes_on_freertos_memory_management]
1167 for more information.
1168
1169 NEWPAGE
1170
1171 === AIN test description ===[ain_test_description]
1172
1173 %DONE
1174
1175 This test will read all the analog inputs at a rate of 100 times per second and print the result.
1176
1177 ```
1178 --> ain
1179 Analog Inputs Test [1-12]:
1180 ===========================================================
1181    1    2    3    4    5    6    7    8    9   10   11   12
1182    0    0    0    0    0    0    0    0    0    0    0    0
1183 ```
1184
1185 Status: **PASSED** for channels 1-5. 6-12 remain untested but they //should// work.
1186
1187 === AOUT test description ===[aout_test_description]
1188
1189 %DONE
1190
1191 This test will generate a 10Hz sinus wave on all the analog outputs with a sampling rate of 1kHz.
1192 The sinus wave of each analog output channel is sifted by (1/4)pi.
1193
1194 ```
1195 --> aout
1196 Analog Output Test at 10 Hz:
1197 ===========================================================
1198 Samples: 7331
1199 ```
1200
1201 Status: **PASSED**.
1202
1203 === DIN test description ===[din_test_description]
1204
1205 %DONE
1206
1207 This test will read all 16 + 8 digital inputs at a rate of 100 times per second, using both low
1208 speed SPI chip and variable threshold high-speed inputs.
1209
1210 ```
1211 --> din
1212 Digital Inputs Test [1-16]:
1213 ===========================================================
1214  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16  A  B  C  D  E  F  G  H
1215  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0
1216 ```
1217
1218 Status:
1219  - Low speed fixed threshold [1-16]: **PASSED**.
1220  - High speed variable threshold [A-H]: **PASSED**.
1221
1222 === HBR test description ===[hbr_test_description]
1223
1224 %DONE
1225
1226 This test will generate a sinus wave to control the H-Bridge of one period per 20 seconds (0.05Hz)
1227 at a sampling rate of 20Hz.
1228
1229 ```
1230 --> hbr
1231 H-Bridge Test at 0.05 Hz:
1232 ===========================================================
1233 Samples: 72
1234 ```
1235
1236 Status: **PASSED**.
1237
1238 === LOUT test description ===[lout_test_description]
1239
1240 %DONE
1241
1242 This test will show in the digital outputs the value in binary of a counter, incrementing the
1243 counter once per second. The counter is 8 bits, the same as the outputs, so 255 seconds are
1244 required for an overflow/restart of the counting.
1245
1246 ```
1247 --> lout
1248 Digital Output Test:
1249 ===========================================================
1250 Counter:   40
1251 ```
1252
1253 Status: **PASSED**.
1254
1255 === MOUT test description ===[mout_test_description]
1256
1257 %DONE
1258
1259 This test will toggle the power outputs one by one per second, then wait 10 seconds in that state
1260 while constantly verifying the diagnostics.
1261
1262 ```
1263 --> mout
1264 Power Output Test:
1265 ===========================================================
1266 1     2     3     4     5     6
1267 1: OK 1: OK 1: OK 1: OK 1: OK 1: OK
1268 ```
1269
1270 Status: **PASSED**.
1271
1272 === SCI test description ===[sci_test_description]
1273
1274 %DONE
1275
1276 A more comprehensive test is not implemented. The very use of this test-suite implies the correct
1277 function of the SCI module. Nevertheless, as a future improvement, a test that will verify run-time
1278 baud rate changes and test some other RPP SCI functions is desirable.
1279
1280 ```
1281 --> sci
1282 You're using the SCI, reading this and typing this command.
1283 Press any key to continue...
1284 ```
1285
1286 Status: **PASSED**.
1287
1288 === SDR test description ===[sdr_test_description]
1289
1290 %DONE
1291
1292 This test will launch a noise generator task that will log noise and then start the library
1293 included SD-RAM logging command processor, allowing the user to see and handle the log on the
1294 SD-RAM.
1295
1296 ```
1297 --> sdr
1298 Log control: 1024kB available.
1299 ===========================================================
1300 --> log
1301 [   1239864] This is the noise generator at iteration 1 putting some noise value 279735017.
1302 [   1240779] This is the noise generator at iteration 2 putting some noise value 1943579783.
1303
1304 --> available
1305 1023 kB of 1024 kB available.
1306
1307 --> clear
1308 Done.
1309
1310 --> exit
1311 ```
1312
1313 Status: **PASSED**.
1314
1315 NEWPAGE
1316
1317 == Static libraries ==[static_libraries]
1318
1319 %DONE
1320
1321 The RPP Library can be compiled as a static library for ARM using TI CGT and for x86(_64) using
1322 GCC. CCS projects ``rpp-lib`` and ``rpp-lib_posix`` in ``<repo>/rpp/lib/apps/`` allows to generate
1323 the static libraries. After compilation, as part of the build process, both projects will
1324 automatically update the version-controlled static libraries in ``<repo>/rpp/lib/``:
1325
1326 - ``rpp-lib.lib``, static library for ARM using TI naming scheme.
1327 - ``librpp.a``, static library for x86(_64) using standard Linux naming scheme.
1328
1329
1330 One future improvement would be the creation of a Makefile for each compilation scheme in order to
1331 not depend on CCS managed build system. For ARM manual compilation or makefile creation using Texas
1332 CGT see the ``target_tools.mk`` file under the Simulink RPP Target folder. The relevant aspects for
1333 compiling and linking an application using the static libraries are:
1334
1335 **ARM compilation using CCS for the RPP board:**
1336
1337 - Include headers files of the OS for which the library was compiled against. At the time of this
1338   writing the OS is FreeRTOS 7.0.2. See [OS interchangeable layer #os_interchangeable_layer]
1339   section above.
1340 - Include header files for the RPP library.
1341 - Add library ``rpp-lib.lib`` to the linker libraries. The RPP library **MUST** be looked for
1342   before Texas Instruments support library ``rtsv7R4_T_be_v3D16_eabi.lib``.
1343 - Configure linker to retain ``.intvecs`` section from RPP Library:@@
1344   ``--retain="rpp-lib.lib<sys_intvecs.obj>(.intvecs)"``
1345 - Use the provided linker command file ``TMS570LS313xFlashLnk.cmd``.
1346
1347
1348 **x86(_64) compilation using GCC for Simulation:**
1349
1350 - Include headers files of the OS for Simulation. At the time of this writing the OS is POSIX
1351   FreeRTOS 6.0.4.
1352 - Include header files for the RPP library.
1353 - Create a ``RppConfig.h`` override file and drop DRV layer dependency: ``rppCONFIG_DRV 0``.
1354 - Includes must be configured in a way that the ``RppConfig.h`` taken under consideration is the
1355   override and not the library one.
1356 - Add library ``librpp.a`` to the linker libraries.
1357 - Add ``pthread`` to the linker libraries.
1358
1359
1360 As an important note, all the models compiled using Simulink will link against ``rpp-lib.lib``.
1361 When compiling a Simulink model, Simulink, and then ``make``, will not update the generated binary
1362 if the model hasn't changed, and then if the source code hasn't changed. Static libraries changes
1363 are not considered for re-compilation and re-linking. If library development is being done and
1364 static library is updated, in order for the Simulink model to generate a newly linked version of
1365 the binary the whole code generation folder needs to be deleted in order to force code generation,
1366 compilation and linking with the new static library.
1367
1368
1369 NEWPAGE
1370
1371 == Base application ==[base_application]
1372
1373 %DONE
1374
1375 In ``<repo>/rpp/lib/apps/`` there is two RPP base applications, ``base`` and ``base_posix``, that
1376 already configured for the RPP Library. It is advised that new applications uses this projects a
1377 foundations.
1378
1379 To create a new application copy this directory and rename it. Now open files ``.project``,
1380 ``.cproject`` and ``.ccsproject`` (if available) and change any occurrence of the work ``base``
1381 with the name of your project. Use lower case ASCII letters and underscores only.
1382
1383 **Steps to configure a new CCS (ARM, using CGT) RPP application:**
1384
1385 + Create a new CCS project. @@
1386 [400-base_1.png]
1387 + Create a normal folder ``include``.
1388 + Create a source folder ``src``.
1389 + Add common ``.gitignore`` to the root of that project:
1390 {{{ plain
1391 Debug
1392 Release
1393 .settings/*
1394 }}}
1395 NEWPAGE
1396 + Add new variable ``RPP_LIB_ROOT`` and point to this repository branch root.@@
1397 [400-base_2.png]
1398 + Add ``rpp-lib.lib`` static library to linker libraries and add ``RPP_LIB_ROOT`` to the library
1399   search path.@@
1400 [400-base_3.png]
1401 NEWPAGE
1402 + Configure linker to retain ``.intvecs`` from RPP static library.@@
1403 [350-base_4.png]
1404 + Configure compiler to include local includes, OS includes for TMS570 and RPP includes, in that
1405   order.@@
1406 [350-base_5.png]
1407 NEWPAGE
1408 + Configure compiler to allow GCC extensions.@@
1409 [400-base_6.png]
1410 + Import and link (__do not copy!__) linker file and board upload descriptor.@@
1411 [200-base_7.png]
1412
1413
1414 **Steps to configure a new GCC (x86(_64)) RPP simulated application:**
1415
1416 + Create a new managed C project that uses Linux GCC toolchain.
1417 + Create a source folder ``src``. Link all files from original CCS application to this folder.
1418 + Create a normal folder ``include``. Create a folder ``rpp`` inside of it.
1419 + Add common ``.gitignore`` to the root of that project:
1420 {{{ plain
1421 Debug
1422 Release
1423 .settings/*
1424 }}}
1425 NEWPAGE
1426 + Add new variable ``RPP_LIB_ROOT`` and point to this repository branch root.@@
1427 [400-base_posix_1.png]
1428 + Configure compiler to include local includes, CCS application includes, OS includes for POSIX and
1429   RPP includes, in that order.@@
1430 [400-base_posix_2.png]
1431 NEWPAGE
1432 + Add ``rpp`` and ``pthread``to linker libraries and add ``RPP_LIB_ROOT`` to the library search
1433   path.@@
1434 [400-base_posix_3.png]
1435 + Copy ``RppConfig.h`` from RPP Library to a new folder ``include/rpp`` and configure it drop DRV
1436   layer dependency: ``rppCONFIG_DRV 0``.@@
1437 [200-base_posix_4.png]
1438
1439
1440 **In general any RPP application uses the layout/template:**
1441
1442 + Include RPP library header file.
1443 {{{ cpp
1444 #include "rpp/rpp.h"
1445 }}}
1446
1447 NEWPAGE
1448 + Create one or as many FreeRTOS task function definitions as required. Those tasks should use
1449   functions from this library.
1450 {{{ cpp
1451 void my_task(void* p)
1452 {
1453     static const portTickType freq_ticks = 1000 / portTICK_RATE_MS;
1454     portTickType last_wake_time = xTaskGetTickCount();
1455     while(TRUE) {
1456         /* Wait until next step */
1457         vTaskDelayUntil(&last_wake_time, freq_ticks);
1458         rpp_sci_printf((const char*)"Hello RPP.\r\n");
1459     }
1460 }
1461 }}}
1462
1463 + Create the main function that will:
1464  - Initialize the RPP board.
1465  - Spawn the tasks the application requires. Refer to FreeRTOS API for
1466    details.
1467  - Start the FreeRTOS Scheduler. Refer to FreeRTOS API for details.
1468  - Catch if idle task could not be created.
1469 +
1470 {{{ cpp
1471 void main(void)
1472 {
1473     /* Initialize RPP board */
1474     rpp_init();
1475
1476     /* Spawn tasks */
1477     if(xTaskCreate(my_task, (const signed char*)"my_task",
1478             512, NULL, 0, NULL) != pdPASS) {
1479         #ifdef DEBUG
1480         rpp_sci_printf((const char*)
1481             "ERROR: Cannot spawn control task.\r\n"
1482         );
1483         #endif
1484         while(TRUE) { asm(" nop"); }
1485     }
1486
1487     /* Start the FreeRTOS Scheduler */
1488     vTaskStartScheduler();
1489
1490     /* Catch scheduler start error */
1491     #ifdef DEBUG
1492     rpp_sci_printf((const char*)
1493             "ERROR: Problem allocating memory for idle task.\r\n"
1494         );
1495     #endif
1496     while(TRUE) { asm(" nop"); }
1497 }
1498 }}}
1499
1500 + Create hook functions for FreeRTOS:
1501  - ``vApplicationMallocFailedHook()`` allows to catch memory allocation errors.
1502  - ``vApplicationStackOverflowHook()`` allows to catch if a task overflows it's
1503    stack.
1504 +
1505 {{{ cpp
1506 #if configUSE_MALLOC_FAILED_HOOK == 1
1507 /**
1508  * FreeRTOS malloc() failed hook.
1509  */
1510 void vApplicationMallocFailedHook(void) {
1511     #ifdef DEBUG
1512     rpp_sci_printf((const char*)
1513             "ERROR: manual memory allocation failed.\r\n"
1514         );
1515     #endif
1516 }
1517 #endif
1518
1519
1520 #if configCHECK_FOR_STACK_OVERFLOW > 0
1521 /**
1522  * FreeRTOS stack overflow hook.
1523  */
1524 void vApplicationStackOverflowHook(xTaskHandle xTask,
1525                                    signed portCHAR *pcTaskName) {
1526     #ifdef DEBUG
1527     rpp_sci_printf((const char*)
1528             "ERROR: Stack overflow : \"%s\".\r\n", pcTaskName
1529         );
1530     #endif
1531 }
1532 #endif
1533 }}}
1534
1535 NEWPAGE
1536
1537
1538 == API generation ==[api_generation]
1539
1540 %DONE
1541
1542 The RPP Layer is formatted using Doxygen documentation generator. This allows to generate a high
1543 quality API reference. To generate the API reference do in a terminal:
1544
1545 {{{ bash
1546 cd <repo>/rpp/lib/rpp/doc/api
1547 doxygen doxygen.conf
1548 xdg-open html/index.html
1549 }}}
1550
1551 The files under ``<repo>/rpp/lib/rpp/doc/api/content`` are used for the API reference generation
1552 are their name is self-explanatory:
1553
1554 ```
1555 blocks_map.html
1556 blocks.png
1557 cvut.png
1558 footer.html
1559 main_page.dox
1560 ```
1561
1562 To install Doxygen see [Development environment #development_environment] section.
1563
1564 == API Reference ==[api_reference]
1565
1566 %DONE
1567
1568 For the complete API reference please generate the HTML version using the above section
1569 instructions. Here is listed the index of functions of each module and their brief.
1570
1571 Please note that not all modules were implemented as part of this project. See
1572 [RPP Layer Modules #rpp_layer_modules] for a list of the modules implemented.
1573
1574 NEWPAGE
1575
1576 === DIN API Reference ===[din_api_reference]
1577
1578 %DONE
1579
1580 ``int8_t rpp_din_init();`` @@ -> DIN module initialization. @@ @@
1581 ``int8_t rpp_din_ref(uint16_t refA, uint16_t refB);`` @@ -> Configure voltage reference levels for digital inputs using variable reference threshold. @@ @@
1582 ``int8_t rpp_din_setup(uint8_t pin, boolean_t pull_type, boolean_t active, boolean_t can_wake);`` @@ -> Configure given pin. @@ @@
1583 ``int8_t rpp_din_get(uint8_t pin, boolean_t var_thr);`` @@ -> Get the current cached value of the given pin. @@ @@
1584 ``int8_t rpp_din_diag(uint8_t pin);`` @@ -> Get the diagnostic cached value for given pin. @@ @@
1585 ``int8_t rpp_din_update();`` @@ -> Read and update cached values and diagnostic values of all pins. Also commit configuration changes.
1586
1587 === LOUT API Reference ===[lout_api_reference]
1588
1589 %DONE
1590
1591 ``int8_t rpp_lout_init();`` @@ -> LOUT module initialization. @@ @@
1592 ``int8_t rpp_lout_set(uint8_t pin, uint8_t val);`` @@ -> Set the output cache of given pin to given value. @@ @@
1593 ``int8_t rpp_lout_diag(uint8_t pin);`` @@ -> Get the diagnostic cached value for given pin. @@ @@
1594 ``int8_t rpp_lout_update();`` @@ -> Flush cached output values and read back diagnostic values of all pins.
1595
1596 === AIN API Reference ===[ain_api_reference]
1597
1598 %DONE
1599
1600 ``int8_t rpp_ain_init();`` @@ -> AIN module initialization. @@ @@
1601 ``int16_t rpp_ain_get(uint8_t pin);`` @@ -> Get the current analog value on the given pin. @@ @@
1602 ``int8_t rpp_ain_update();`` @@ -> Read and update analog cached values.
1603
1604
1605 === AOUT API Reference ===[aout_api_reference]
1606
1607 %DONE
1608
1609 ``#define RPP_DAC_OA   5.6`` @@ -> DAC output operational amplifier multiplication constant. @@ @@
1610 ``#define RPP_DAC_VREF 2.5`` @@ -> DAC hardware reference voltage. @@ @@
1611 ``int8_t rpp_aout_init();`` @@ -> AOUT module initialization. @@ @@
1612 ``int8_t rpp_aout_setup(uint8_t pin, boolean_t enabled);`` @@ -> Configure enabled/disabled state for given pin. @@ @@
1613 ``int8_t rpp_aout_set(uint8_t pin, uint16_t val);`` @@ -> Set the output cache of given pin to given value. @@ @@
1614 ``int8_t rpp_aout_set_voltage(uint8_t pin, uint16_t mv);`` @@ -> Set output to given voltage. @@ @@
1615 ``int8_t rpp_aout_update();`` @@ -> Flush cached output values and configuration changes.
1616
1617 === HBR API Reference ===[hbr_api_reference]
1618
1619 %DONE
1620
1621 ``int8_t rpp_hbr_init();`` @@ -> HBR module initialization. @@ @@
1622 ``int8_t rpp_hbr_enable(int32_t period);`` @@ -> Enable the H-Bridge for control. @@ @@
1623 ``int8_t rpp_hbr_control(double cmd);`` @@ -> Control the H-Bridge direction, enabled/disabled and PWM. @@ @@
1624 ``int8_t rpp_hbr_disable();`` @@ -> Disable the H-Bridge.
1625
1626 NEWPAGE
1627
1628 === MOUT API Reference ===[mout_api_reference]
1629
1630 %DONE
1631
1632 ``int8_t rpp_hbr_init();`` @@ -> HBR module initialization. @@ @@
1633 ``int8_t rpp_mout_init();`` @@ -> MOUT module initialization. @@ @@
1634 ``int8_t rpp_mout_set(uint8_t pin, uint8_t val);`` @@ -> Set the output of given pin to given value. @@ @@
1635 ``int8_t rpp_mout_get(uint8_t pin);`` @@ -> Get the cached value of the given pin set by rpp_mout_set(). @@ @@
1636 ``int8_t rpp_mout_diag(uint8_t pin);`` @@ -> Reads the value on the given diagnostic pin.
1637
1638 === HOUT API Reference ===[hout_api_reference]
1639
1640 %DONE
1641
1642 ``int8_t rpp_hout_init();`` @@ -> HOUT module initialization.
1643
1644 === CAN API Reference ===[can_api_reference]
1645
1646 %DONE
1647
1648 ``int8_t rpp_can_init();`` @@ -> CAN module initialization.
1649
1650 === LIN API Reference ===[lin_api_reference]
1651
1652 %DONE
1653
1654 ``int8_t rpp_lin_init();`` @@ -> LIN module initialization.
1655
1656 === FR API Reference ===[fr_api_reference]
1657
1658 %DONE
1659
1660 ``int8_t rpp_fr_init();`` @@ -> FR module initialization.
1661
1662 NEWPAGE
1663
1664 === SCI API Reference ===[sci_api_reference]
1665
1666 %DONE
1667
1668 ``int8_t rpp_sci_init();`` @@ -> SCI module initialization. @@ @@
1669 ``boolean_t rpp_sci_setup(uint32_t baud);`` @@ -> SCI module setup. @@ @@
1670 ``uint16_t rpp_sci_available();`` @@ -> Number of bytes available on input buffer. @@ @@
1671 ``int8_t rpp_sci_read(uint32_t amount, uint8_t* buffer);`` @@ -> Read n number of bytes from input buffer. @@ @@
1672 ``int8_t rpp_sci_read_nb(uint32_t amount, uint8_t* buffer);`` @@ -> Read n number of bytes from input buffer if possible. @@ @@
1673 ``int8_t rpp_sci_write(uint32_t amount, uint8_t* data);`` @@ -> Write n number of bytes to the output buffer. @@ @@
1674 ``int8_t rpp_sci_write_nb(uint32_t amount, uint8_t* data);`` @@ -> Write n number of bytes to the output buffer if possible. @@ @@
1675 ``int8_t rpp_sci_flush(boolean_t buff);`` @@ -> Flush incomming or outgoing buffers. @@ @@
1676 ``int32_t rpp_sci_printf(const char* format, ...);`` @@ -> C style printf using RPP SCI module. @@ @@
1677 ``int8_t rpp_sci_putc(uint8_t byte);`` @@ -> C style putc (put character) using RPP SCI module. @@ @@
1678 ``int16_t rpp_sci_getc();`` @@ -> C style getc (get character) using RPP SCI module.
1679
1680 === ETH API Reference ===[eth_api_reference]
1681
1682 %DONE
1683
1684 ``int8_t rpp_eth_init();`` @@ -> ETH module initialization.
1685
1686 === SDC API Reference ===[sdc_api_reference]
1687
1688 %DONE
1689
1690 ``int8_t rpp_sdc_init();`` @@ -> SDC module initialization.
1691
1692 === SDR API Reference ===[sdr_api_reference]
1693
1694 %DONE
1695
1696 ``#define RPP_SDR_ADDR_START 0x80000000U`` @@ -> SDRAM start address on RPP board. @@ @@
1697 ``#define RPP_SDR_ADDR_END   0x83FFFFFFU`` @@ -> SDRAM end address on RPP board. @@ @@
1698 ``int8_t rpp_sdr_init();`` @@ -> SDR module initialization. @@ @@
1699 ``int8_t rpp_sdr_setup(boolean_t enable);`` @@ -> Configure SD-RAM logging. @@ @@
1700 ``uint32_t rpp_sdr_available();`` @@ -> Query for the amount of space free on the SD-RAM. @@ @@
1701 ``int32_t rpp_sdr_printf(const char* format, ...);`` @@ -> Store a formatted user string on the log, if logging is enabled. @@ @@
1702 ``int8_t rpp_sdr_clear();`` @@ -> Clear log. @@ @@
1703 ``int8_t rpp_sdr_show(boolean_t start);`` @@ -> Start/Stop the task that sends the log to the SCI.
1704
1705 NEWPAGE
1706
1707 = Simulink Coder Target =[simulink_coder_target]
1708
1709 %DONE
1710
1711 The Simulink Coder Target allows Simulink model's code generation, compilation and download for the 
1712 board.
1713
1714 == Description ==[description]
1715
1716 %DONE
1717
1718 The Simulink RPP Target provides support for C source code generation from Simulink models and
1719 compilation of that code on top of the RPP library and the FreeRTOS operating system. This target
1720 uses Texas Instrument ARM compiler (armcl) included in the Code Generation Tools available with
1721 Code Composer Studio, and thus it depends on it for proper functioning.
1722
1723 This library also provides support for automatically download the compiled machine code to the RPP
1724 board.
1725
1726 === Code generation process ===[code_generation_process]
1727
1728 %DONE
1729
1730 %tex% ''' \begin{figure}[H]\begin{center}
1731 [400-tlc_process.png]
1732 %tex% ''' \caption{TLC code generation process.}\end{center}\end{figure}
1733
1734 NEWPAGE
1735
1736 == Subdirectory  content description ==[subdirectory__content_description]
1737
1738 %DONE
1739
1740 -> ``rpp_setup.m``
1741
1742 RPP Target install script.
1743
1744 This script will, among other things, ask the user to provide the location of the armcl parent
1745 directory, infer and save some relevant CCS paths, add paths to Matlab path and build S-Function
1746 blocks for user's architecture (using Matlab's mex command line tool).
1747
1748 - __Reference:__
1749  - ``<repo>/refs/rtw_ug.pdf`` p. 1137.
1750
1751
1752 -> ``rpp.tlc``
1753
1754 Embedded real-time system target file for RPP.
1755
1756 This file is the system target file (STF), or target manifest file. Functions of the STF include:
1757
1758 - Making the target visible in the System Target File Browser.
1759 - Definition of code generation options for the target (inherited and target-specific).
1760 - Providing an entry point for the top-level control of the TLC code generation process.
1761
1762
1763 - __Reference:__
1764  - ``<repo>/refs/rtw_ug.pdf`` p. 1129 and __1144__.
1765
1766
1767 -> ``rpp.tmf``
1768
1769 Embedded Coder Template Makefile.
1770
1771 This is just standard Embedded Coder Template Makefile, provided by Matlab. It was slightly
1772 modified to support ``armcl`` particularities and added template rules for assembler files (which
1773 were included by the ``rpp_lib_support.m`` script, but is no longer the case).
1774
1775 - __Reference:__
1776  - ``<repo>/refs/rtw_ug.pdf`` p. 1130 and __1183__.
1777
1778
1779 -> ``rpp_download.m``
1780
1781 Code download utility for Simulink RPP Target.
1782
1783 This function is optionally executed at the end of the build process if it is successful and the
1784 user selected //Download compiled binary to RPP// option on the build configuration panel. This
1785 function calls ``loadti.sh`` script with the generated binary and using configuration for the
1786 XDS100v2 JTAG Emulators. The board should be powered and correctly wired. @@
1787 See [Development wiring #development_wiring].
1788
1789
1790 NEWPAGE
1791 -> ``rpp_file_process.tlc``
1792
1793 Code generation custom file processing template.
1794
1795 This file should decide which //main// to generate according to configuration, in particular which
1796 mode, Single Tasking or Multitasking, is chosen. The RPP Target ignores this settings because it
1797 uses a tasking system based on tasking features provided by FreeRTOS. In consequence is only a
1798 wrapper to the //Single Tasking// main, which clearly is not for single tasking.
1799
1800 - __Reference:__
1801  - ``<repo>/refs/ecoder_ug.pdf`` p. 556.
1802  - ``<repo>/refs/ecoder_ref.pdf`` p. 1347.
1803
1804
1805 -> ``rpp_lib_support.m``
1806
1807 **DEPRECATED**. Simulink support for RPP library and operating system setup.
1808
1809 This files used to add the source code from the RPP library and operating to the build. This is no
1810 longer required when using the static library. This is left for future reference in case new source
1811 code needs to be included to the build.
1812
1813 - __Reference:__
1814  - ``<repo>/refs/rtw_ug.pdf`` p. 1058.
1815  - ``<repo>/refs/rtw_ref.pdf`` p. 56.
1816
1817
1818 -> ``rpp_make_rtw_hook.m``
1819
1820 Build process hooks file.
1821
1822 This file is hook file that invoke target-specific functions or executables at specified points in
1823 the build process. In particular, this file handle the copying of required files before the
1824 compilation stage.
1825
1826 - __Reference:__
1827  - ``<repo>/refs/rtw_ug.pdf`` p. 1066-1072 and 1131.
1828
1829
1830 -> ``rpp_select_callback_handler.m``
1831
1832 RPP Target select callback handler.
1833
1834 This callback function is triggered whenever the user selects the target in the System Target File
1835 Browser. Default values for Simulation and configurations parameters are set. Some options are
1836 disabled if it is not allowed to be changed by user.
1837
1838 - __Reference:__
1839  - ``<repo>/refs/rtw_ug.pdf`` p. 1211.
1840
1841
1842 NEWPAGE
1843 -> ``rpp_srmain.tlc``
1844
1845 Custom file processing to generate a //main// file.
1846
1847 This file generated the //main// file for the RPP target on top of the RPP library and the FreeRTOS
1848 operating system. The ``sr`` prefix is standard to mark Single Tasking main, which is the case.
1849 See ``rpp_file_process.m`` description above for more information about this.
1850
1851 - __Reference:__
1852  - Example in ``<matlab>/rtw/c/tlc/mw/bareboard_srmain.tlc``.
1853
1854
1855 -> ``target_tools.mk``
1856
1857 Makefile for CCS (``armcl``) toolchain support.
1858
1859 This file set variables to CCS tools to support build for this toolchain. This file is included by
1860 ``rpp.tmf`` before declaring the rules for source code.
1861
1862 - __Reference:__
1863  - //Include a tool specification settings// comment block in ``rpp.tmf``.
1864  - Compiler options documentation available in ``armcl.pdf``.
1865
1866
1867 NEWPAGE
1868
1869 == Installation procedure ==[installation_procedure]
1870
1871 %DONE
1872
1873 **1) Download and install CCS for Linux:**
1874
1875 Details on how to setup CCS are available in section
1876 [TI Code Composer Studio #ti_code_composer_studio].
1877
1878
1879 **2) Install RPP Target:**
1880
1881 Open Matlab and type on command window:
1882
1883 {{{ plain
1884 cd <repo>/rpp/rpp/
1885 rpp_setup()
1886 }}}
1887
1888 This will launch the RPP setup script. This script will ask the user to provide the path to the CCS
1889 compiler root directory (the directory where ``armcl`` binary is located), normally:
1890
1891 ```
1892 <ccs>/tools/compiler/arm_5.X.X/
1893 ```
1894
1895 This script will, among other things, ask the user to provide the location of the armcl parent
1896 directory, infer and save some relevant CCS paths, add paths to Matlab path and build S-Function
1897 blocks for user's architecture (using Matlab's mex command line tool).
1898
1899
1900 **3) Create a new model or load a demo:**
1901
1902 Demos are located on ``<repo>/rpp/demo`` or you can start a new model and configure target to RPP.
1903 For new models see [Target Reference #target_reference] section below.
1904
1905 NEWPAGE
1906
1907 == Target Reference ==[target_reference]
1908
1909 %DONE
1910
1911 This section describes the options required or available for running a Simulink model with the RPP
1912 Target.
1913
1914 === Simulink model options ===[simulink_model_options]
1915
1916 %DONE
1917
1918 The Simulink model needs to be configured in the following way:
1919
1920 - Solver:
1921  - //fixed-step discrete//.
1922  - Tasking mode set to //SingleTasking//. @@
1923 [400-simulink_solver.png]
1924 NEWPAGE
1925 - Diagnostics - Sample Time:
1926  - Disable warning source block specifies -1 sampling time. It's ok for the source blocks to run
1927    once per tick. @@
1928 [400-simulink_diagnostics.png]
1929 - Code generation:
1930  - Set to ``rpp.tlc``. @@
1931 [400-simulink_code.png]
1932
1933
1934 Note: Single Tasking is the only currently supported mode. If multitasking is required to be
1935       implemented in the future create a new file ``rpp_mrmain.tlc`` in ``<repo>/rpp/rpp/`` and
1936       edit ``rpp_file_process.tlc`` to use that file instead when multitasking is selected.
1937
1938
1939 === RPP Target options ===[rpp_target_options]
1940
1941 %DONE
1942
1943 The RPP Target include the following configuration options, all of them configurable per model
1944 under  ``Code Generation`` -> ``RPP Options``:
1945
1946 - **C system stack size**: this parameter is passed directly to the linker for the allocation of
1947   the stack. Note that this is the stack for the application when running outside a FreeRTOS task,
1948   normally before the scheduler has started and for system routines. Default value is 4096.
1949
1950 - **C system heap size**: this parameter is passed directly to the linker for the allocation of the
1951   heap. See
1952   [Appendix A: Notes on FreeRTOS memory management #appendix_a_notes_on_freertos_memory_management]
1953   for an important information about this parameter.
1954
1955 - **Model step task stack size**: this parameter will be passed to the ``xTaskCreate()`` that
1956   creates the task for the model to run. In a Simulink model there is always two tasks:
1957  - The worker task. This task is the one that executes the model step. This task requires enough
1958    stack memory to execute the step. Take into account for example than only a single call to
1959    ``rpp_sci_printf()`` requires, with current configuration, 128 bytes from the stack. This value
1960    should be minor than the C system heap and leaving enough heap for the system tasks. See
1961    [Appendix A: Notes on FreeRTOS memory management #appendix_a_notes_on_freertos_memory_management]
1962    for more information.
1963  - The control task. This task controls when the worker task should execute and controls overruns.
1964
1965 - **Download compiled binary to RPP**: if set, this option will download the generated binary to
1966   the board after the model is successfully built. Note that this option is unaware of the option
1967   //Generate code only// in the //Code Generation// options panel, so it will try to upload even if
1968   only source code has being generated, failing graciously or uploading an old binary laying around
1969   in the build directory. This option calls the ``rpp_download.m`` script, which is in turn a
1970   wrapper on the ``loadti.sh`` script. More information on the ``loadti.sh`` script can be found
1971   in:
1972 ```
1973 <css>/ccs_base/scripting/examples/loadti/readme.txt
1974 http://processors.wiki.ti.com/index.php/Loadti
1975 ```
1976   The ``loadti.sh`` script will close after the download of the generated program and in
1977   consequence the execution of the loaded program will stop (because it work as the CCS debug
1978   server). In order to test the loaded model a manual reset of the board is always required after a
1979   successful download.
1980
1981 - **Print model metadata to SCI at start**: if set this option will print a message to the Serial
1982   Communication Interface when the model start execution on the board. This is very helpful to
1983   identify the model running on the board. The message is in the form:
1984 ```
1985 `model_name' - generated_date (TLC tlc_version)
1986 ```
1987   For example:
1988 ```
1989 `hbridge_analog_control' - Wed Jun 19 14:10:44 2013 (TLC 8.3 (Jul 20 2012))
1990 ```
1991
1992 NEWPAGE
1993
1994 = Simulink Block Library =[simulink_block_library]
1995
1996 %DONE
1997
1998 %tex% ''' \vspace{-0.25cm}
1999
2000 The Simulink Block Library is a set of blocks that allows Simulink models to use board IO and 
2001 communication peripherals.
2002
2003 %tex% ''' \vspace{-0.5cm}
2004
2005 == Description ==[description]
2006
2007 %DONE
2008
2009 %tex% ''' \vspace{-0.25cm}
2010
2011 As part of this project the ideal set was defined, but not all blocks were implemented. The
2012 following table shows the current status of the block library.
2013
2014 %tex% ''' \vspace{-0.25cm}
2015
2016 || CATEGORY                | NAME                           | STATUS*  | MNEMONIC    | LRH*
2017  | System blocks           | Configuration block            | ``X``    | ``[CONF]``  | ``RppConfig.h``  |
2018  | Logic IO blocks         | Digital Input block            | ``T``    | ``[DIN ]``  | ``rpp_din.h``    |
2019  |                         | Digital Output block           | ``T``    | ``[LOUT]``  | ``rpp_lout.h``   |
2020  |                         | Analog Input block             | ``T``    | ``[AIN ]``  | ``rpp_ain.h``    |
2021  |                         | Analog Output block            | ``T``    | ``[AOUT]``  | ``rpp_aout.h``   |
2022  | Power output blocks     | H-Bridge Control block         | ``T``    | ``[HBR ]``  | ``rpp_hbr.h``    |
2023  |                         | Power output block             | ``T``    | ``[MOUT]``  | ``rpp_mout.h``   |
2024  |                         | High-Power output block        | ``X``    | ``[HOUT]``  | ``rpp_hout.h``   |
2025  | Communication blocks    | CAN Bus receive block          | ``X``    | ``[CANR]``  | ``rpp_can.h``    |
2026  |                         | CAN Bus send msg block         | ``X``    | ``[CANS]``  | - Idem -         |
2027  |                         | LIN receive block              | ``X``    | ``[LINR]``  | ``rpp_lin.h``    |
2028  |                         | LIN send msg block             | ``X``    | ``[LINS]``  | - Idem -         |
2029  |                         | FlexRay receive block          | ``X``    | ``[FRR ]``  | ``rpp_fr.h``     |
2030  |                         | FlexRay send msg block         | ``X``    | ``[FRS ]``  | - Idem -         |
2031  |                         | SCI receive block              | ``T``    | ``[SCIR]``  | ``rpp_sci.h``    |
2032  |                         | SCI send msg block             | ``T``    | ``[SCIS]``  | - Idem -         |
2033  |                         | SCI configure block            | ``T``    | ``[SCIC]``  | - Idem -         |
2034  |                         | Ethernet receive block         | ``X``    | ``[ETHR]``  | ``rpp_eth.h``    |
2035  |                         | Ethernet send msg block        | ``X``    | ``[ETHS]``  | - Idem -         |
2036  | Logging/Storage blocks  | SD Card write block            | ``T``    | ``[SDCW]``  | ``rpp_sdc.h``    |
2037  |                         | SDRAM write block              | ``X``    | ``[SDRW]``  | ``rpp_sdr.h``    |
2038  | Trigger blocks          | Overrun detected block         | ``X``    | ``[TROR]``  | - None -         |
2039  |                         | Stack overflow detected block  | ``X``    | ``[TRSO]``  | - None -         |
2040  |                         | Malloc Failed detected block   | ``X``    | ``[TRMF]``  | - None -         |
2041
2042 %tex% ''' \vspace{-0.5cm}
2043
2044 %tex% ''' \begin{multicols}{2}
2045 **Legend:**
2046 - *LRH    : Library Reference Header.
2047 - *STATUS :
2048  - ``X`` - Unimplemented. Files non present.
2049  - ``P`` - Unimplemented. Files present.
2050  - ``W`` - Work in progress.
2051  - ``I`` - Implemented.
2052  - ``T`` - Implemented and tested.
2053
2054
2055 %tex% ''' \vfill\columnbreak
2056 **Notes:** @@
2057 Each block that can detect fault condition should have a trigger output. @@
2058 High-power output provides current flow as an input to the model.
2059
2060 %tex% ''' \end{multicols}
2061
2062
2063
2064
2065
2066
2067
2068
2069 === C MEX S-Functions ===[c_mex_s_functions]
2070
2071 %DONE
2072
2073 All of the blocks are implemented as a C Mex S-Function coded by hand. In the this section the 
2074 approach taken is explained.
2075
2076 C-MEX S-Function:
2077  - C : Implemented in C language. Other options are Fortran and Matlab language itself.
2078  - MEX: Matlab Executable. They are compiled by Matlab GCC wrapper called MEX.
2079  - S-Function: System Function, as opposed to standard functions, or user functions.
2080
2081
2082 A C-MEX S-Function is a structured C file that includes the following mandatory callbacks:
2083
2084 + ``mdlInitializeSizes``: @@
2085   Specify the number of inputs, outputs, states, parameters, and other characteristics of the C 
2086   MEX S-function.
2087 + ``mdlInitializeSampleTimes``: @@
2088   Specify the sample rates at which this C MEX S-function operates.
2089 + ``mdlOutputs``: @@
2090   Compute the signals that this block emits.
2091 + ``mdlTerminate``: @@
2092   Perform any actions required at termination of the simulation.
2093
2094
2095 Plus many more optional callbacks. Relevant optional callbacks are:
2096
2097 + ``mdlCheckParameters``: @@
2098   Check the validity of a C MEX S-function's parameters.
2099 + ``mdlRTW``: @@
2100   Generate code generation data for a C MEX S-function.
2101 + ``mdlSetWorkWidths``: @@
2102   Specify the sizes of the work vectors and create the run-time parameters required by the C MEX 
2103   S-function.
2104 + ``mdlStart``: @@
2105   Initialize the state vectors of the C MEX S-function.
2106
2107
2108 A complete list of callbacks can be found in:
2109
2110         http://www.mathworks.com/help/simulink/create-cc-s-functions.html
2111
2112 NEWPAGE
2113 The way a C-MEX S-Function participates in a Simulink simulation is shown by the following diagram:
2114
2115 %tex% ''' \begin{figure}[H]\begin{center}
2116 [250-sfunctions_process.png]
2117 %tex% ''' \caption{Simulation cycle of a S-Function.}\end{center}\end{figure}
2118
2119 In general, a S-Function can perform calculations and inputs and outputs for simulation. Because 
2120 the blocks implemented for this project are for hardware peripherals control and IO the blocks are 
2121 implemented as pure sink or pure source. That is, the S-Function is a descriptor of the block but
2122 does not any calculation, input or output for simulation. 
2123
2124 The S-Functions required could be implemented in several ways:
2125
2126 + Writing the S-Function. @@
2127   Using this method, the user hand write a new C S-Function and associated TLC file. This method 
2128   requires the most knowledge about the structure of a C S-Function.
2129 + Using an S-Function Builder block. @@
2130   Using this method, the user enter the characteristics of the S-function into a block dialog. This 
2131   method does not require any knowledge about writing S-Functions. However, a basic understanding 
2132   of the structure of an S-Function can make the S-Function Builder dialog box easier to use.
2133 + Using the Legacy Code Tool (LCT). @@
2134   Using this command line method, the user define the characteristics of your S-function in a data 
2135   structure in the MATLAB workspace. This method requires the least amount of knowledge about 
2136   S-Functions.
2137
2138
2139 From the above, the LCT is a tool that can be called within Matlab workshop that allows to generate 
2140 source code for S-Functions given the descriptor of a C function call. This approach is used by
2141 most of the other targets reviewed for this project. The descriptor is a Matlab file with 
2142 definitions like the following:
2143
2144 NEWPAGE
2145 {{{ plain
2146 %% GPIO Write
2147 % Populate legacy_code structure with information
2148 GPIOWrite = legacy_code('initialize');
2149 GPIOWrite.SFunctionName = 'sfun_GPIOWrite';
2150 GPIOWrite.HeaderFiles = {'gpiolct.h'};
2151 GPIOWrite.SourceFiles = {'gpiolct.c'};
2152 GPIOWrite.OutputFcnSpec = 'GPIOWrite(uint32 p1, uint8 u1, uint8 u2)';
2153 % Support calling from within For-Each subsystem
2154 GPIOWrite.Options.supportsMultipleExecInstances = true;
2155 }}}
2156
2157 The interface and implementation files specified should hold the declaration and implementation of
2158 the ``OutputFcnSpec`` function. This tool will generate a simple S-Function that will input and 
2159 output the values required by that function. This approach was **not** for this project, mainly 
2160 because:
2161
2162 - The RPP Library requires that after some actions (like setting one LOUT output) the changes are 
2163   committed to the hardware, or before some other actions (like getting the value from DIN using 
2164   the fixed threshold) the values cached are updated. And the implementation of a wrapper function
2165   that would update or commit the changes wasn't considered because of the efficiency impact it
2166   would have.
2167
2168 - Furthermore, the error handling of the function call is not considered, and for some blocks 
2169   (like MOUT and HOUT) the diagnostic handling is mandatory.
2170
2171 - Also, the dialog parameters of the S-Function cannot be validated otherwise than data type 
2172   (cannot validate range, for example). 
2173
2174 - For future improvements the LCT cannot generate code for simulation, and a lot of S-Function 
2175   options cannot not be fine tuned. 
2176
2177 - Finally, the generated code is very obscure, hard to read and to maintain in case the above 
2178   functionality had to be implemented on top of the generated code.
2179
2180
2181 Similarly the hand written S-Functions shares a large amount of code like parameters scalar, data 
2182 type and range validation, standard options for this kind of blocks, unused functions, among other. 
2183 Because of this a mini framework for writing S-Functions for RPP was implemented in the form of two 
2184 files that are directly included at the beginning and end of the S-Function implementation: 
2185 ``header.c`` and  ``trailer.c``. 
2186
2187 This mini-framework reduces the amount of required code for each S-Function considerably, making 
2188 easier to maintain and adapt. Because each S-Function is a program by itself there is no need to 
2189 use interface files and the files are directly included.
2190
2191 NEWPAGE
2192 The final form of the S-Function is a C file of around 100 lines of code with the following layout:
2193
2194 - Define S-Function name ``S_FUNCTION_NAME``.
2195
2196 - Include header file ``header.c``.
2197
2198 - In ``mdlInitializeSizes`` define:
2199  - Number of //dialog// parameter.
2200  - Number of input ports.
2201   - Data type of each input port.
2202  - Number of output ports.
2203   - Data type of each output port.
2204  - Standard options for driver blocks.
2205
2206 - In ``mdlCheckParameters``:
2207  - Check data type of each parameter.
2208  - Check range, if applicable, of each parameter.
2209
2210 - In ``mdlSetWorkWidths``:
2211  - Map //dialog// parameter to //runtime// parameters.
2212   - Data type of each //runtime// parameter.
2213
2214 - Define symbols for unused functions.
2215
2216 - Include trailer file ``trailer.c``.
2217
2218
2219 The C-MEX S-Function implemented can be compile with the following command:
2220
2221 {{{ bash
2222 <matlabroot>/bin/mex sfunction_{mnemonic}.c
2223 }}}
2224
2225 As noted the standard is to always prefix S-Function with ``sfunction_`` and use lower case 
2226 mnemonic of the block.
2227
2228 Also a script called ``compile_blocks.m`` is included that allows all ``sfunctions_*.c`` to be fed 
2229 to the ``mex`` compiler so all S-Functions are compiled at once. To use this script, in Matlab do:
2230
2231 {{{ plain
2232 cd <repo>/rpp/blocks/
2233 compile_blocks()
2234 }}}
2235
2236 NEWPAGE
2237
2238 === Target Language Compiler files ===[target_language_compiler_files]
2239
2240 %DONE
2241
2242 C code generated from a Simulink model is placed on a file called ``<modelname>.c`` along with 
2243 other support files in a folder called ``<modelname>_<target>/``. For example, the source code
2244 generated for model ``foobar`` will be placed in current Matlab directory ``foobar_rpp/foobar.c``.
2245
2246 The file ``<modelname>.c`` has 3 main functions:
2247
2248 - ``void <modelname>_step(void)``: @@
2249   This function recalculates all the outputs of the blocks and should be called once per step. This
2250   is the main working function.
2251 - ``void <modelname>_initialize(void)``: @@
2252   This function is called only once before the first step is issued. Default values for blocks IOs
2253   should be placed here.
2254 - ``void <modelname>_terminate(void)``: @@
2255   This function is called when terminating the model. This should be used to free memory of revert 
2256   other operations made on the initialization function. With current implementation this function
2257   should never be called unless an errors is detected and in most models it is empty.
2258
2259
2260 In order to generate code for each one of those functions each S-Function implement a TLC file
2261 for //inlining// the S-Function on the generated code. The TLC files are files that describe how to 
2262 generate code for a specific C-MEX S-Function block. They are programmed using TLC own language and 
2263 include C code within TLC instructions, just like LaTeX files include normal text in between LaTeX 
2264 macros.
2265
2266 TLC files are located under ``<repo>/rpp/blocks/tlc_c/`` directory. For a diagram on how TLC files 
2267 work see [Code generation process #code_generation_process] section.
2268
2269 The standard for a TLC file is to be located under the ``tlc_c`` subfolder from where the 
2270 S-Function is located and to use the very exact file name as the S-Function but with the ``.tlc``
2271 extension:
2272
2273 ``sfunction_foo.c`` -> ``tlc_c/sfunction_foo.tlc``
2274
2275 The TLC files implemented for this project use 3 hook functions in particular (other are available, 
2276 see TLC reference documentation):
2277
2278 - ``BlockTypeSetup``: @@
2279   BlockTypeSetup executes once per block type before code generation begins.
2280   This function can be used to include elements required by this block type, like includes or
2281   definitions.
2282
2283 - ``Start``: @@
2284   Code here will be placed in the ``void <modelname>_initialize(void)``. Code placed here will
2285   execute only once.
2286
2287 - ``Outputs``: @@
2288   Code here will be placed in the ``void <modelname>_step(void)`` function. Should be used to 
2289   get the inputs o a block and/or to set the outputs of that block.
2290
2291
2292 The general layout of the TLC files implemented for this project are:
2293
2294 - In ``BlockTypeSetup``: @@
2295   Call common function ``%<RppCommonBlockTypeSetup(block, system)>`` that will include the 
2296   ``rpp/rpp.h`` header file (can be called multiple times but header is included only once).
2297
2298 - ``Start``: @@
2299   Call setup routines from RPP Layer for the specific block type, like HBR enable, DIN pin setup, 
2300   AOUT value initialization, SCI baud rate setup, among others.
2301
2302 - ``Outputs``: @@
2303   Call common IO routines from RPP Layer, like DIN read, AOUT set, etc. Success of this functions
2304   is checked and in case of failure error is reported to the block using ErrFlag.
2305
2306
2307 NEWPAGE
2308
2309 == Subdirectory  content description ==[subdirectory__content_description]
2310
2311 %DONE
2312
2313 -> ``header.c`` and ``trailer.c``
2314
2315 RPP framework for simple S-Functions.
2316
2317 This files are included at the head and tail of each S-Function file. They include refactored and
2318 commonly repeated structures that pollute S-Functions implementations. They include basic includes,
2319 required definitions, macro definitions, common functions implementations and documentation on
2320 optional functions and commented prototypes for optional model calls/hooks.
2321
2322 - __Reference:__
2323  - See header of those files.
2324
2325
2326 -> ``sfunction_{mnemonic}.c``
2327
2328 C-MEX S-Function implementation for {mnemonic} block.
2329
2330 This file implements the {mnemonic} block using C-MEX S-Function API. See the reference for 
2331 information about the S-Function API.
2332
2333 - __Reference:__
2334  - ``<repo>/refs/sfunctions.pdf``
2335
2336
2337 -> ``tlc_c/sfunction_{mnemonic}.tlc``
2338
2339 Target Language Compiler (TLC) file for {mnemonic} block.
2340
2341 This file implements the C code inlining for {mnemonic} block. See the reference for information 
2342 about the TLC API.
2343
2344 - __Reference:__
2345  - ``<repo>/refs/rtw_tlc.pdf``
2346
2347
2348 -> ``tlc_c/common.tlc``
2349
2350 Common TLC functions.
2351
2352 This file implements common TLC functions used by all the blocks.
2353
2354 - __Reference:__
2355  - None.
2356
2357
2358 NEWPAGE
2359 -> ``slblocks.m``
2360
2361 Simulink library control file.
2362
2363 This file allows a group of blocks to be integrated into the Simulink Library and Simulink Library
2364 Browser. This file is required by Simulink in order to interpret this folder as a block library.
2365 For information about this file see the references.
2366
2367 - __Reference:__
2368  - ``<repo>/refs/rtw_ug.pdf`` p. 1127
2369
2370
2371 -> ``rpp_lib.slx``
2372
2373 RPP Simulink block library.
2374
2375 Simulink block library that includes all the blocks. This file is referenced by ``slblocks.m``
2376
2377 - __Reference:__
2378  - None.
2379
2380
2381 -> compile_blocks.m
2382
2383 Blocks compilation script.
2384
2385 This script compiles all the sfunction blocks to MEX executables. This script is called by the
2386 ``rpp_setup()`` function in order make all the blocks available to the Simulink environment or it
2387 can be called independently when developing S-Functions.
2388
2389 - __Reference:__
2390  - None.
2391
2392
2393 NEWPAGE
2394
2395 == Block Library Reference ==[block_library_reference]
2396
2397 %DONE
2398
2399 This section describes each one of the Simulink blocks implements as part of this project:
2400
2401 %tex% ''' \begin{figure}[H]\advance\leftskip-1cm
2402 [530-block_library.png]
2403 %tex% ''' \caption{Simulink RPP Block Library.}\end{figure}
2404
2405 NEWPAGE
2406
2407 === DIN Digital Input block ===[din_digital_input_block]
2408
2409 %DONE
2410
2411 ```
2412     Inputs      : 0
2413         None
2414
2415     Outputs     : 2
2416         bool    Digital Input
2417         bool    ErrFlag
2418
2419     Parameters  : 2
2420         uint8   Pin number [1-16]
2421         bool    Use variable threshold
2422 ```
2423
2424 This block allows to read the digital inputs on the RPP board. The variable threshold check change 
2425 the read mode of the pin. The ErrFlag should raise if ``rpp_din_update()`` or ``rpp_din_get()`` 
2426 returns error. ``rpp_din_update()`` is called just by the first DIN block in the model and thus 
2427 only the first block could raise the flag because of this. In case an errors occurs the return 
2428 value will always be LOW (0). Because the ErrFlag should never set, once set the following steps 
2429 will never clear it back.
2430
2431
2432 %tex% ''' \begin{multicols}{3}
2433 - **Tested**:
2434  - Changing the pin.
2435  - Compilation and general use.
2436  - Using variable threshold.
2437
2438
2439 %tex% ''' \vfill\columnbreak
2440 - **Untested**:
2441  - Faulty situation for the ErrFlag to set.
2442
2443
2444 %tex% ''' \vfill\columnbreak
2445 - **Not working**:
2446
2447
2448 %tex% ''' \end{multicols}
2449
2450
2451 **RPP API functions used:**
2452 - ``rpp_din_setup()``.
2453 - ``rpp_din_update()``.
2454 - ``rpp_din_get()``.
2455
2456
2457 **Relevant demos:**
2458 - ``digital_passthrough``.
2459 - ``hbridge_digital_control``.
2460
2461
2462 NEWPAGE
2463
2464 === LOUT Digital Output block ===[lout_digital_output_block]
2465
2466 %DONE
2467
2468 ```
2469     Inputs      : 1
2470         bool    Digital Output
2471
2472     Outputs     : 1
2473         bool    ErrFlag
2474
2475     Parameters  : 1
2476         uint8   Pin number [1-8]
2477 ```
2478
2479 This block allows to write to the digital outputs on the RPP board. The ErrFlag should raise if 
2480 ``rpp_lout_set()`` or ``rpp_lout_update()`` returns error. Because the ErrFlag should never set, 
2481 once set the following steps will never clear it back. ``rpp_lout_update()`` is called on each 
2482 block, which is not the most efficient but guaranties consistent behavior.
2483
2484
2485 **Status:**
2486 %tex% ''' \begin{multicols}{3}
2487 - **Tested**:
2488  - Changing the pin.
2489  - Compilation and general use.
2490
2491
2492 %tex% ''' \vfill\columnbreak
2493 - **Untested**:
2494  - Faulty situation for the ErrFlag to set.
2495
2496
2497 %tex% ''' \vfill\columnbreak
2498 - **Not working**:
2499
2500
2501 %tex% ''' \end{multicols}
2502
2503
2504 **RPP API functions used:**
2505 - ``rpp_lout_set()``.
2506 - ``rpp_lout_update()``.
2507
2508
2509 **Relevant demos:**
2510 - ``digital_passthrough``.
2511 - ``led_blink_all``.
2512 - ``led_blink``.
2513
2514
2515 NEWPAGE
2516
2517 === AIN Analog Input block ===[ain_analog_input_block]
2518
2519 %DONE
2520
2521 ```
2522     Inputs      : 0
2523         None
2524
2525     Outputs     : 2
2526         uint16  Analog Input
2527         bool    ErrFlag
2528
2529     Parameters  : 1
2530         uint8   Pin number [1-12]
2531 ```
2532
2533 This block allows to read the analog inputs on the RPP board. The ErrFlag should if raise 
2534 ``rpp_ain_update()`` or ``rpp_ain_get()`` returns error. ``rpp_ain_update()`` is called just by the 
2535 first DIN block in the model and thus only the first block could raise the flag because of this. 
2536 In case an errors occurs the return value will always be 0. Because the ErrFlag should never set, 
2537 once set the following steps will never clear it back.
2538
2539
2540 **Status:**
2541 %tex% ''' \begin{multicols}{3}
2542 - **Tested**:
2543  - Changing the pin.
2544  - Compilation and general use.
2545
2546
2547 %tex% ''' \vfill\columnbreak
2548 - **Untested**:
2549  - Faulty situation for the ErrFlag to set.
2550
2551
2552 %tex% ''' \vfill\columnbreak
2553 - **Not working**:
2554
2555
2556 %tex% ''' \end{multicols}
2557
2558
2559 **RPP API functions used:**
2560 - ``rpp_ain_update()``.
2561 - ``rpp_ain_get()``.
2562
2563
2564 **Relevant demos:**
2565 - ``analog_passthrough``.
2566 - ``hbridge_analog_control``.
2567 - ``log_analog_input``.
2568
2569
2570 NEWPAGE
2571
2572 === AOUT Analog Output block ===[aout_analog_output_block]
2573
2574 %DONE
2575
2576 ```
2577     Inputs      : 1
2578         uint16  Analog Output
2579
2580     Outputs     : 1
2581         bool    ErrFlag
2582
2583     Parameters  : 1
2584         uint8   Pin number [1-4]
2585         bool    UseVoltage
2586 ```
2587
2588 This block allows to write to the analog outputs on the RPP board. The UseVoltage flag allows the 
2589 user to configure if block inputs should be interpreted as raw DAC value or millivolts. The ErrFlag 
2590 should raise if ``rpp_aout_update()`` or ``rpp_aout_set()`` (or ``rpp_aout_set_voltage()`` 
2591 depending on block configuration) returns error. Because the ErrFlag should never set, once set the 
2592 following steps will never clear it back.
2593
2594 ``rpp_aout_update()`` is called on each block but the implementation provides this to be efficient.
2595
2596 There is a know bug on the RPP Library, check ``rpp_aout_update()`` on the RPP API for details. 
2597 Because of this, the outputs of the DACs are initialized on the first step of the model and not on 
2598 the model initialization.
2599
2600
2601 **Status:**
2602 %tex% ''' \begin{multicols}{3}
2603 - **Tested**:
2604  - Changing the pin.
2605  - Changing voltage/value flag.
2606  - Compilation and general use.
2607
2608
2609 %tex% ''' \vfill\columnbreak
2610 - **Untested**:
2611  - Faulty situation for the ErrFlag to set.
2612
2613
2614 %tex% ''' \vfill\columnbreak
2615 - **Not working**:
2616  - Initializing DACs on model's initialization.
2617
2618
2619 %tex% ''' \end{multicols}
2620
2621
2622 **RPP API functions used:**
2623 - ``rpp_aout_setup()``.
2624 - ``rpp_aout_set()``, or
2625 - ``rpp_aout_set_voltage()``.
2626 - ``rpp_aout_update()``.
2627
2628
2629 **Relevant demos:**
2630 - ``analog_passthrough``.
2631 - ``analog_sinewave``.
2632
2633
2634 NEWPAGE
2635
2636 === HBR H-Bridge Control block ===[hbr_h_bridge_control_block]
2637
2638 %DONE
2639
2640 ```
2641     Inputs      : 1
2642         double  Control
2643
2644     Outputs     : 1
2645         bool    ErrFlag
2646
2647     Parameters  : 0
2648         None
2649 ```
2650
2651 This block allows to control the H-Bridge on the RPP board. The ErrFlag should raise only if
2652 ``rpp_hbr_control()`` returns error. The H-Bridge is initialized with the default frequency 
2653 (~18kHz). A future improvement could include a parameter to set the frequency. Because the ErrFlag 
2654 should never set, once set the following steps will never clear it back.
2655
2656
2657 **Status:**
2658 %tex% ''' \begin{multicols}{3}
2659 - **Tested**:
2660  - Compilation and general use.
2661
2662
2663 %tex% ''' \vfill\columnbreak
2664 - **Untested**:
2665  - Faulty situation for the ErrFlag to set.
2666
2667
2668 %tex% ''' \vfill\columnbreak
2669 - **Not working**:
2670
2671
2672 %tex% ''' \end{multicols}
2673
2674
2675 **RPP API functions used:**
2676 - ``rpp_hbr_enable()``.
2677 - ``rpp_hbr_control()``.
2678
2679
2680 **Relevant demos:**
2681 - ``hbridge_analog_control``.
2682 - ``hbridge_digital_control``.
2683 - ``hbridge_sinewave_control``.
2684
2685
2686 NEWPAGE
2687
2688 === MOUT Power Output block ===[mout_power_output_block]
2689
2690 %DONE
2691
2692 ```
2693     Inputs      : 1
2694         bool    Power Output
2695
2696     Outputs     : 1
2697         bool    ErrFlag
2698
2699     Parameters  : 1
2700         uint8   Pin number [1-6]
2701 ```
2702
2703 This block allows to write the power outputs (2A) on the RPP board. The ErrFlag should raise only 
2704 if ``rpp_mout_set()``returns error. Note that ``rpp_mout_set()`` returns error only if some bad 
2705 parameter or in case it could detect a faulty condition on the pin in a very very short period of 
2706 time after setting the value, see the function API for details. If the faulty condition persist on 
2707 the next step the call will successfully detect the faulty condition and ErrFlag should set. 
2708 Because the ErrFlag should never set, once set the following steps will never clear it back.
2709
2710
2711 **Status:**
2712 %tex% ''' \begin{multicols}{3}
2713 - **Tested**:
2714  - Changing the pin.
2715  - Compilation and general use.
2716
2717
2718 %tex% ''' \vfill\columnbreak
2719 - **Untested**:
2720  - Faulty situation for the ErrFlag to set.
2721
2722
2723 %tex% ''' \vfill\columnbreak
2724 - **Not working**:
2725
2726
2727 %tex% ''' \end{multicols}
2728
2729
2730 **RPP API functions used:**
2731 - ``rpp_mout_set()``.
2732
2733
2734 **Relevant demos:**
2735 - ``power_toggle``.
2736
2737
2738 NEWPAGE
2739
2740 === SCIR Serial Comm. Interface Receive ===[scir_serial_comm_interface_receive]
2741
2742 %DONE
2743
2744 ```
2745     Inputs      : 0
2746         None
2747
2748     Outputs     : 2
2749         uint8   Data
2750         bool    ErrFlag
2751
2752     Parameters  : 0
2753         None
2754 ```
2755
2756 This block allows to receive a byte from the SCI. The ErrFlag should raise if ``rpp_sci_read_nb()``
2757 doesn't succeed. The behavior of the ErrFlag is different from others blocks in that this block 
2758 will set or clear the flag if the call fails of success at each step. Note that this block uses the
2759 non-blocking call to read the SCI and thus will never cause an overrun.
2760
2761
2762 **Status:**
2763 %tex% ''' \begin{multicols}{3}
2764 - **Tested**:
2765  - Receiving data.
2766  - Compilation and general use.
2767  - Faulty situation for the ErrFlag to set.
2768
2769
2770 %tex% ''' \vfill\columnbreak
2771 - **Untested**:
2772
2773
2774 %tex% ''' \vfill\columnbreak
2775 - **Not working**:
2776
2777
2778 %tex% ''' \end{multicols}
2779
2780
2781 **RPP API functions used:**
2782 - ``rpp_sci_read_nb()``.
2783
2784
2785 **Relevant demos:**
2786 - ``echo_char``.
2787
2788
2789 NEWPAGE
2790
2791 === SCIS Serial Comm. Interface Send ===[scis_serial_comm_interface_send]
2792
2793 %DONE
2794
2795 ```
2796     Inputs      : 1
2797         uint8   Data
2798
2799     Outputs     : 1
2800         bool    ErrFlag
2801
2802     Parameters  : 2
2803         bool    UsePrintf
2804         string  PrintFormat [SETTING]
2805 ```
2806
2807 This block allows to send a byte to the SCI or to print a formatted string that uses that byte. The
2808 UsePrintf flag allows to user to select ``rpp_sci_write_nb()`` (raw send) or ``rpp_sci_printf()``
2809 (formatted print) as the function the block should use on code generation. If UsePrintf is set the
2810 PrintFormat string parameters SETTING is used as the format specifier. Note that this value is
2811 inserted raw between quotes on code generation and thus there is no validation on it. User should
2812 always put any valid integer specifier for the value on the input of the block.
2813
2814 The behavior of this block depends if UsePrintf is set or not. If set, the call ``rpp_sci_printf()``
2815 (a blocking call) could potentially overrun the step. Also, the ErrFlag will set only if
2816 ``rpp_sci_printf()`` returns an error, and because it should never set, once set it will never
2817 clear back. On the contrary, if UsePrintf is clear, the call ``rpp_sci_write_nb()`` (non-blocking)
2818 is used and thus the step cannot be overrun, but because is a best-effort call it cannot guarantee 
2819 that all the data will be sent. In the case that not all data could be sent, the ErrFlag will set, 
2820 but it will clear back if the next step is able to send all it's data (which with the current 
2821 implementation is just one byte).
2822
2823 A possible future improvement for this block is to allow input to be non-scalar so user can print a 
2824 whole string in one step using raw non-blocking write. This is currently possible if input 
2825 configuration is adapted in S-Function and TLC. The problem this could pose is is that for printf 
2826 user should include specifiers for all the cells in the non-scalar input, and if unknown, then 
2827 printf cannot be used.
2828
2829
2830 **Status:**
2831 %tex% ''' \begin{multicols}{3}
2832 - **Tested**:
2833  - Sending data.
2834  - Compilation and general use.
2835
2836
2837 %tex% ''' \vfill\columnbreak
2838 - **Untested**:
2839  - Faulty situation for the ErrFlag to set.
2840
2841
2842 %tex% ''' \vfill\columnbreak
2843 - **Not working**:
2844
2845
2846 %tex% ''' \end{multicols}
2847
2848
2849 **RPP API functions used:**
2850 - ``rpp_sci_write_nb()``, or ``rpp_sci_printf()``.
2851
2852
2853 **Relevant demos:**
2854 - ``echo_char`` and ``hello_world``.
2855
2856
2857 NEWPAGE
2858
2859 === SCIC Serial Comm. Interface Configure ===[scic_serial_comm_interface_configure]
2860
2861 %DONE
2862
2863 ```
2864     Inputs      : 0
2865         None
2866
2867     Outputs     : 0
2868         None
2869
2870     Parameters  : 1
2871         uint32  Baud rate
2872 ```
2873
2874 This block allows to configure the baud rate of the SCI. There should only one block of this type 
2875 per model, and this requirement is not validated, but the inclusion of several blocks is harmless 
2876 and will just produce the baud rate to be changed several times, being the final baud rate to be 
2877 the one of the last executed block. This block just executes on model initialization and not on 
2878 each step.
2879
2880
2881 **Status:**
2882 %tex% ''' \begin{multicols}{3}
2883 - **Tested**:
2884  - Changing baud rate.
2885  - Compilation and general use.
2886
2887
2888 %tex% ''' \vfill\columnbreak
2889 - **Untested**:
2890  - Using more than one block in a model.
2891
2892
2893 %tex% ''' \vfill\columnbreak
2894 - **Not working**:
2895
2896
2897 %tex% ''' \end{multicols}
2898
2899
2900 **RPP API functions used:**
2901 - ``rpp_sci_setup()``.
2902
2903
2904 **Relevant demos:**
2905 - ``echo_char``.
2906 - ``hello_world``.
2907
2908
2909 NEWPAGE
2910
2911 === SDRW SD-RAM Write ===[sdrw_sd_ram_write]
2912
2913 %DONE
2914
2915 ```
2916     Inputs      : 1
2917         double  Data
2918
2919     Outputs     : 1
2920         bool    ErrFlag
2921
2922     Parameters  : 2
2923         uint8   Block ID
2924         string  PrintFormat [SETTING]
2925 ```
2926
2927 This block allows to log a double value to the SD-RAM. User needs to provide a valid PrintFormat 
2928 string to format and register the double value on the log. The PrintFormat string should include 
2929 two specifiers:
2930
2931 - For the block ID. Any valid integer specifier.
2932 - For the value to log. Any valid double specifier.
2933
2934
2935 Note that the value of PrintFormat is inserted raw between quotes on code generation and thus there 
2936 is no validation on it. Error to provide a valid PrintFormat could generate compilation errors on 
2937 even run-time errors (normally this generates a warning on compile time). Note that the function 
2938 for logging used is ``rpp_sdr_printf()``, which is a blocking call, and can potentially overrun the 
2939 step. The ErrFlag will set if ``rpp_sdr_printf()`` returns an error (for example out of memory), 
2940 but will clear back if the next step the call to this function is successful.
2941
2942
2943 **Status:**
2944 %tex% ''' \begin{multicols}{3}
2945 - **Tested**:
2946  - Logging data.
2947  - Compilation and general use.
2948
2949
2950 %tex% ''' \vfill\columnbreak
2951 - **Untested**:
2952  - Faulty situation for the ErrFlag to set.
2953
2954
2955 %tex% ''' \vfill\columnbreak
2956 - **Not working**:
2957
2958
2959 %tex% ''' \end{multicols}
2960
2961
2962 **RPP API functions used:**
2963 - ``rpp_sdr_printf()``.
2964
2965
2966 **Relevant demos:**
2967 - ``log_analog_input``.
2968
2969
2970 NEWPAGE
2971
2972 = Simulink Demos Library =[simulink_demos_library]
2973
2974 %DONE
2975
2976 The Simulink RPP Demo Library is a set of Simulink models that use blocks from the Simulink RPP
2977 Block Library and generates code using the Simulink RPP Target.
2978
2979 == Description ==[description]
2980
2981 %DONE
2982
2983 This demos library is used as a test suite for the Simulink RPP Block Library but they are also
2984 intended to show basic programs built using it. Because of this, the demos try to use more than one
2985 type of block and more than one block per block type.
2986
2987 The following table shows the current status of the demos:
2988
2989 || Name                         | Implemented | Tested   |
2990  | analog_passthrough           |     YES     |  SUCCESS |
2991  | analog_sinewave              |     YES     |  SUCCESS |
2992  | digital_passthrough          |     YES     |  SUCCESS |
2993  | echo_char                    |     YES     |  SUCCESS |
2994  | hbridge_analog_control       |     YES     |  SUCCESS |
2995  | hbridge_digital_control      |     YES     |  SUCCESS |
2996  | hbridge_sinewave_control     |     YES     |  SUCCESS |
2997  | hello_world                  |     YES     |  SUCCESS |
2998  | led_blink_all                |     YES     |  SUCCESS |
2999  | led_blink                    |     YES     |  SUCCESS |
3000  | log_analog_input             |     YES     |  SUCCESS |
3001  | power_toggle                 |     YES     |  SUCCESS |
3002
3003 In the reference below you can find a complete description for each of the demos.
3004
3005 == Subdirectory  content description ==[subdirectory__content_description]
3006
3007 %DONE
3008
3009 -> ``{demo}.slx``
3010
3011 A Simulink demo.
3012
3013 This subdirectory just includes all the Simulink demos described in the following section.
3014
3015 NEWPAGE
3016
3017 == Demos Reference ==[demos_reference]
3018
3019 %DONE
3020
3021 This section describes the demos implemented as part of this project that uses the Simulink RRP
3022 Block Library and generates code using the RPP Simulink Target.
3023
3024 === Analog pass-through ===[analog_pass_through]
3025
3026 %DONE
3027
3028 %tex% ''' \begin{figure}[H]\begin{center}
3029 [450-demo_analog_passthrough.png]
3030 %tex% ''' \caption{Analog Passthrough Simulink demo for RPP.}\end{center}\end{figure}
3031
3032 **Description:**
3033
3034 This demo will read analog input 1 and write it to analog output 1.
3035
3036 In laboratory the minimum read value for analog input a 0 volts is 107. The maximum read at 12
3037 volts is 2478. The map subsystem will map the input domain (AIN)``[110, 2400]`` to the output domain
3038 (AOUT)``[0, 4095]``.
3039
3040 NEWPAGE
3041
3042 === Analog sinewave ===[analog_sinewave]
3043
3044 %DONE
3045
3046 %tex% ''' \begin{figure}[H]\begin{center}
3047 [450-demo_analog_sinewave.png]
3048 %tex% ''' \caption{Analog Sinewave Simulink demo for RPP.}\end{center}\end{figure}
3049
3050 **Description:**
3051
3052 This demo will generate a sinewave on analog output 1. Siwave is 10Hz and sampling rate is set to
3053 1000Hz (driven from Simulink step of 1ms, same as operating system). Amplitude is set to use AOUT
3054 full range [0-4095] which means output amplitude will be [0-12] volts.
3055
3056 The Software oscilloscope shown should match an external one connected to AOUT 1.
3057
3058 Note that the driver configuration of the MCP4922 is set to unbuffered (which should eventually
3059 be changed to buffered) and thus the last resolution millivolts are lost.
3060
3061 NEWPAGE
3062
3063 === Digital pass-through ===[digital_pass_through]
3064
3065 %DONE
3066
3067 %tex% ''' \begin{figure}[H]\begin{center}
3068 [400-demo_digital_passthrough.png]
3069 %tex% ''' \caption{Digital Pass-through Simulink demo for RPP.}\end{center}\end{figure}
3070
3071 **Description:**
3072
3073 This demo will directly pass the digital values read on DIN [1-8] to LOUT [1-8], and thus acting
3074 as a digital pass-through or gateway.
3075
3076 Also note that all the ErrFlag are aggregated on a global ErrFlag.
3077
3078 NEWPAGE
3079
3080 === Echo char ===[echo_char]
3081
3082 %DONE
3083
3084 %tex% ''' \begin{figure}[H]\begin{center}
3085 [450-demo_echo_char.png]
3086 %tex% ''' \caption{Echo Character Simulink demo for RPP.}\end{center}\end{figure}
3087
3088 **Description:**
3089
3090 This demo will echo twice (print back) any character received through the Serial Communication
3091 Interface (9600-8-N-1).
3092
3093 Note that the send subsystem is implemented a as //triggered// subsystem and will execute only
3094 if data is received, that is, Serial Receive output is non-negative. Negative values are errors.
3095
3096 NEWPAGE
3097
3098 === H-bridge analog control ===[h_bridge_analog_control]
3099
3100 %DONE
3101
3102 %tex% ''' \begin{figure}[H]\begin{center}
3103 [450-demo_hbridge_analog_control.png]
3104 %tex% ''' \caption{H-Bridge Analog Control Simulink demo for RPP.}\end{center}\end{figure}
3105
3106 **Description:**
3107
3108 This demo will read values from the analog input, map them, and control the H-Bridge. This allows
3109 a motor connected to the H-Bridge to be controlled with a potentiometer connected to Analog Input 1.
3110
3111 Setting the potentiometer to output around 6 volts will stop the motor. Less (or greater) than 6
3112 volts will trigger the motor in one sense (or in the other sense) and speed proportional with 1%
3113 resolution.
3114
3115 In laboratory the minimum read value for analog input is 107 at 0 volts. The maximum read at 12 volts
3116 is 2478. The map subsystem will map the input domain (AIN)``[110, 2400]`` to the output domain
3117 (HBR)``[-1.0, 1.0]``.
3118
3119 NEWPAGE
3120
3121 === H-bridge digital control ===[h_bridge_digital_control]
3122
3123 %DONE
3124
3125 %tex% ''' \begin{figure}[H]\begin{center}
3126 [450-demo_hbridge_digital_control.png]
3127 %tex% ''' \caption{H-Bridge Digital Control Simulink demo for RPP.}\end{center}\end{figure}
3128
3129 **Description:**
3130
3131 This demo toggle the H-Bridge from stop to full speed in one direction using digital input 1.
3132 So basically is a ON/OFF switch on DIN 1 for a motor connected on the HBR. Note the data type
3133 conversion because the output of the DIN is a boolean and the input to the HBR is a double.
3134
3135 NEWPAGE
3136
3137 === H-bridge sine wave control ===[h_bridge_sine_wave_control]
3138
3139 %DONE
3140
3141 %tex% ''' \begin{figure}[H]\begin{center}
3142 [300-demo_hbridge_sinewave_control.png]
3143 %tex% ''' \caption{H-Bridge Sinewave Control Simulink demo for RPP.}\end{center}\end{figure}
3144
3145 **Description:**
3146
3147 This demo will generate a sine wave to control the H-Bridge. Sine wave is one period per 20
3148 seconds or 0.05Hz. Sampling rate is 20Hz or 100 samples per 1/4 of period (for 1% speed
3149 resolution change).
3150
3151 Note that the Software oscilloscope should is not the output of the H-Bridge, the H-Bridge will
3152 change current sense and the duty cycle of the pulse that drive it (PWM), it does not output
3153 analog values. The Software oscilloscope just shows what the input to the HBR block is.
3154
3155 NEWPAGE
3156
3157 === Hello world ===[hello_world]
3158
3159 %DONE
3160
3161 %tex% ''' \begin{figure}[H]\begin{center}
3162 [450-demo_hello_world.png]
3163 %tex% ''' \caption{Hello World Simulink demo for RPP.}\end{center}\end{figure}
3164
3165 **Description:**
3166
3167 This demo will print ``"Hello Simulink"`` to the Serial Communication Interface (9600-8-N-1) one
3168 character per second. The output speed is driven by the Simulink model step which is set to one
3169 second.
3170
3171 NEWPAGE
3172
3173 === LED blink ===[led_blink]
3174
3175 %DONE
3176
3177 %tex% ''' \begin{figure}[H]\begin{center}
3178 [450-demo_led_blink.png]
3179 %tex% ''' \caption{LED Blink Simulink demo for RPP.}\end{center}\end{figure}
3180
3181 **Description:**
3182
3183 This the simplest demo of all that shows the basics of using the RPP target and blocks. The
3184 goal of this demo is to show the configuration of the model (not shown on the picture above),
3185 that is, how the RPP Simulink Coder Target is setup, general model setup and step setup.
3186
3187 This demo will toggle each second a LED connected on LOUT 1. The timing is set by the Simulink
3188 model step which is set to 1 second.
3189
3190 NEWPAGE
3191
3192 === LED blink all ===[led_blink_all]
3193
3194 %DONE
3195
3196 %tex% ''' \begin{figure}[H]\begin{center}
3197 [350-demo_led_blink_all.png]
3198 %tex% ''' \caption{LED Blink All Simulink demo for RPP.}\end{center}\end{figure}
3199
3200 **Description:**
3201
3202 This demo will toggle all LEDs connected to the LOUT port. Even outputs pins will be negated.
3203 Toggle will happen each second. The timing is driven by Simulink model step configuration that
3204 is set to 1 second. All blocks ErrFlags are aggregated into one global ErrFlag.
3205
3206 NEWPAGE
3207
3208 === Log analog input ===[log_analog_input]
3209
3210 %DONE
3211
3212 %tex% ''' \begin{figure}[H]\begin{center}
3213 [450-demo_log_analog_input.png]
3214 %tex% ''' \caption{Log Analog Input Simulink demo for RPP.}\end{center}\end{figure}
3215
3216 **Description:**
3217
3218 This demo will log once per second the value read on the analog input 1. User can read the log
3219 using the SCI logging integrated command processor (9600-8-N-1). Logging block ID set to 1. The
3220 timing is driven by Simulink model step configuration that is set to 1 second.
3221
3222 NEWPAGE
3223
3224 === Power toggle ===[power_toggle]
3225
3226 %DONE
3227
3228 %tex% ''' \begin{figure}[H]\begin{center}
3229 [300-demo_power_toggle.png]
3230 %tex% ''' \caption{Power Toggle Simulink demo for RPP.}\end{center}\end{figure}
3231
3232 **Description:**
3233
3234 This demo will toggle the power output once per second. If an error is detected on at least one of
3235 the outputs a generic error message is printed to the serial line. The timing is driven by Simulink
3236 model step configuration that is set to 1 second. Power outputs can drive a load up to 2A, so please
3237 take into account required safety considerations.
3238
3239 NEWPAGE
3240
3241 = Glossary =[glossary]
3242
3243 %DONE
3244
3245 : ADC
3246   //Analog to Digital Converter.// @@
3247   Hardware circuitry that converts a continuous physical quantity (usually voltage) to a
3248   digital number that represents the quantity's amplitude.
3249
3250 : AIN
3251   //Analog Input.// @@
3252   Mnemonic to refer to or something related to the analog input (ADC) hardware module.
3253
3254 : AOUT
3255   //Analog Output.// @@
3256   Mnemonic to refer to or something related to the analog output (DAC) hardware module.
3257
3258 : CAN
3259   //Controller Area Network.// @@
3260   The CAN Bus is a vehicle bus standard designed to allow microcontrollers and devices to
3261   communicate with each other within a vehicle without a host computer.
3262   In this project it is also used as mnemonic to refer to or something related to the CAN
3263   hardware module.
3264
3265 : CGT
3266   //Code Generation Tools.// @@
3267   Name given to the tool set produced by Texas Instruments used to compile, link, optimize,
3268   assemble, archive, among others. In this project is normally used as synonym for
3269   ``Texas Instruments ARM compiler and linker."
3270
3271 : DAC
3272   //Digital to Analog Converter.// @@
3273   Hardware circuitry that converts a digital (usually binary) code to an analog signal
3274   (current, voltage, or electric charge).
3275
3276 : DIN
3277   //Digital Input.// @@
3278   Mnemonic to refer to or something related to the digital input hardware module.
3279
3280 : ECU
3281   //Engine Control Unit.// @@
3282   A type of electronic control unit that controls a series of actuators on an internal combustion
3283   engine to ensure the optimum running.
3284
3285 : ETH
3286   //Ethernet.// @@
3287   Mnemonic to refer to or something related to the Ethernet hardware module.
3288
3289 : FR
3290   //FlexRay.// @@
3291   FlexRay is an automotive network communications protocol developed to govern on-board automotive
3292   computing.
3293   In this project it is also used as mnemonic to refer to or something related to the FlexRay
3294   hardware module.
3295
3296 : GPIO
3297   //General Purpose Input/Output.// @@
3298   Generic pin on a chip whose behavior (including whether it is an input or output pin) can be
3299   controlled (programmed) by the user at run time.
3300
3301 : HBR
3302   //H-Bridge.// @@
3303   Mnemonic to refer to or something related to the H-Bridge hardware module. A H-Bridge is
3304   an electronic circuit that enables a voltage to be applied across a load in either direction.
3305
3306 : HOUT
3307   //High-Power Output.// @@
3308   Mnemonic to refer to or something related to the 10A, PWM, with current sensing, high-power
3309   output hardware module.
3310
3311 : IDE
3312   //Integrated Development Environment.// @@
3313   An IDE is a Software application that provides comprehensive facilities to computer programmers
3314   for software development.
3315
3316 : LCT
3317   //Legacy Code Tool.// @@
3318   Matlab tool that allows to generate source code for S-Functions given the descriptor of a C 
3319   function call.
3320
3321 : LIN
3322   //Local Interconnect Network.// @@
3323   The LIN is a serial network protocol used for communication between components in vehicles.
3324   In this project it is also used as mnemonic to refer to or something related to the LIN
3325   hardware module.
3326
3327 : LOUT
3328   //Logic Output.// @@
3329   Mnemonic to refer to or something related to the digital output hardware module.
3330   It is logic output (100mA), as opposed to power outputs (2A, 10A).
3331
3332 : MBD
3333   //Model-Based Design.// @@
3334   Model-Based Design (MBD) is a mathematical and visual method of addressing problems associated
3335   with designing complex control, signal processing and communication systems.
3336
3337 : MEX
3338   //Matlab Executable.// @@
3339   Type of binary executable that can be called within Matlab. In this document the common term
3340   used is `C MEX S-Function", which means Matlab executable written in C that implements a system
3341   function.
3342
3343 : MOUT
3344   //(Motor) Power Output.// @@
3345   Mnemonic to refer to or something related to the 2A push/pull power output hardware module.
3346
3347 : PWM
3348   //Pulse-width modulation.// @@
3349   Technique for getting analog results with digital means. Digital control is used to create a
3350   square wave, a signal switched between on and off. This on-off pattern can simulate voltages
3351   in between full on and off by changing the portion of the time the signal spends on versus
3352   the time that the signal spends off. The duration of ``on time" is called the pulse width or
3353   //duty cycle//.
3354
3355 : RPP
3356   //Rapid Prototyping Platform.// @@
3357   Name of the automotive hardware board. Also generic term to define something related
3358   to the board, like the RPP Library, RPP Layer, RPP API, etc.
3359
3360 : SCI
3361   //Serial Communication Interface.// @@
3362   Serial Interface for communication through hardware's UART using communication standard RS-232.
3363   In this project it is also used as mnemonic to refer to or something related to the Serial
3364   Communication Interface hardware module.
3365
3366 : SDC
3367   //SD-Card.// @@
3368   Mnemonic to refer to or something related to the SD-Card hardware module.
3369
3370 : SDR
3371   //SD-RAM.// @@
3372   Mnemonic to refer to or something related to the SD-RAM hardware module for logging.
3373
3374 : TLC
3375   //Target Language Compiler.// @@
3376   Technology and language used to generate code in Matlab/Simulink.
3377
3378 : UART
3379   //Universal Asynchronous Receiver/Transmitter.// @@
3380   Hardware circuitry that translates data between parallel and serial forms.
3381
3382
3383
3384 NEWPAGE
3385
3386 = References =[references]
3387
3388 %DONE
3389
3390 - Horn, M. (2013). //Software obsluhující periferie a flexray na automobilové rídicí jednotce//.
3391   (Unpublished master's thesis, Czech Technical University in Prague, Prague, Czech Republic).
3392
3393 - //Model-based design//. (n.d.). In Wikipedia. Retrieved March 10, 2013, from @@
3394   http://en.wikipedia.org/wiki/Model-based_design
3395
3396 - (2012). //ARM Assembly Language Tools//. Texas Instruments.
3397
3398 - (2012). //ARM Optimizing C/C++ Compiler//. Texas Instruments.
3399
3400 - (2013). //Embedded Coder - Reference//. MathWorks.
3401
3402 - (2013). //Embedded Coder - User's Guide//. MathWorks.
3403
3404 - Barry, R. (2009). //Using the FreeRTOS real time kernel - A practical guide//.
3405
3406 - (2013). //Simulink Coder - Reference//. MathWorks.
3407
3408 - (2013). //Simulink - Target Language Compiler//. MathWorks.
3409
3410 - (2013). //Simulink Coder - User's Guide//. MathWorks.
3411
3412 - (2013). //Simulink - Developing S-Functions//. MathWorks.
3413
3414 - (2012). //TMS570LS31x/21x 16/32-Bit RISC Flash Microcontroller - Technical Reference Manual//.
3415   Texas Instruments.
3416
3417
3418 NEWPAGE
3419
3420 = Appendix A: Notes on FreeRTOS memory management =[appendix_a_notes_on_freertos_memory_management]
3421
3422 %DONE
3423
3424 FreeRTOS provides 4 different (at the time of this writing) memory management implementations.
3425 On vanilla distribution of FreeRTOS these can be found in
3426 ``<FreeRTOSRoot>/FreeRTOS/Source/portable/MemMang`` with the names ``heap_1.c``, ``heap_2.c``,
3427 ``heap_3.c`` and ``heap_4.c``. The user is supposed to choose one and rename it to ``heap.c``
3428 and include it in the port for the target processor. Memory management implementation of each file
3429 is explained in depth in:
3430
3431         [Memory Management http://www.freertos.org/a00111.html]
3432
3433 The above is a must read documentation. In summary:
3434
3435 -> ``heap_1.c``
3436
3437 - Use a static allocated array for memory and thus will be placed on the ``.bss`` section.
3438 - Subdivides the array into smaller blocks as RAM is requested.
3439 - Memory cannot be freed.
3440 - Array is as large as ``configTOTAL_HEAP_SIZE`` option in ``FreeRTOSConfig.h``.
3441
3442
3443 -> ``heap_2.c``
3444
3445 - Use a static allocated array for memory and thus will be placed on the ``.bss`` section.
3446 - Uses a best fit algorithm and allows previously allocated blocks to be freed.
3447 - It does **not** however combine adjacent free blocks into a single large block.
3448 - Array is as large as ``configTOTAL_HEAP_SIZE`` option in ``FreeRTOSConfig.h``.
3449
3450
3451 -> ``heap_3.c``
3452
3453 - Wrapper around standard C library ``malloc()`` and ``free()``.
3454 - Wrapper makes ``malloc()`` and ``free()`` functions thread safe.
3455 - Memory is as large as defined in linker for C system heap.
3456 - ``configTOTAL_HEAP_SIZE`` option in ``FreeRTOSConfig.h`` is ignored.
3457
3458
3459 -> ``heap_4.c``
3460
3461 - Use a static allocated array for memory and thus will be placed on the ``.bss`` section.
3462 - Uses a first fit algorithm.
3463 - It **does** combine adjacent free memory blocks into a single large block (it does include a
3464   coalescence algorithm).
3465 - Array is as large as ``configTOTAL_HEAP_SIZE`` option in ``FreeRTOSConfig.h``.
3466
3467
3468 Not all kernels available for the RPP C Library use the same implementation. This is what each
3469 kernel is currently configured to use:
3470
3471 ||        Kernel |               Origin                |  Implementation  |
3472  |   6.0.4 Posix |    Simulator from OpenPilot.org     |   ``heap_3.c``   |
3473  |  7.0.2 TMS570 |              HalCoGen               |   ``heap_1.c``   |
3474  |  7.4.0 TMS570 |              HalCoGen               |   ``heap_4.c``   |
3475  |  7.4.2 TMS570 |  Adapted from vanilla distribution  |   ``heap_4.c``   |
3476
3477 The relevant implications of this are:
3478
3479 - If a kernel with ``heap_3.c`` is used the Simulink model //C system heap size// and
3480   //Model step task stack size// should be tightly related and the first should be large enough to
3481   allocate system tasks and the stack for the stepping task.
3482
3483 - If a kernel with ``heap_1.c`` is used the programs should not delete tasks, queues or semaphores.
3484   If the application spawn and deletes tasks it will eventually deplete the memory available. This
3485   is the case with the //rpp-test-suite//. Note that failure to allocated memory from the array
3486   will trigger the //Malloc Failed Hook Function// ``vApplicationMallocFailedHook()``, even if the
3487   implementation doesn't use the C system ``malloc()`` function. @@
3488   Also, //Model step task stack size// should never be set larger than ``configTOTAL_HEAP_SIZE``
3489   option in ``FreeRTOSConfig.h``. Currently the RPP Target doesn't include a GUI option for setting
3490   ``configTOTAL_HEAP_SIZE`` because the library is statically linked and thus memory will be of the
3491   size specified when built. The RPP Target **doesn't** check that the requested memory for the
3492   step task is less than the ``configTOTAL_HEAP_SIZE``, and if greater then the application will
3493   fail at runtime and trigger the //Malloc Failed Hook Function//.
3494
3495
3496 NEWPAGE
3497
3498 = Appendix B: Known operating-system dependent files =[appendix_b_known_operating_system_dependent_files]
3499
3500 %DONE
3501
3502 This project was developed on a GNU/Linux operating system. No test for cross-platform
3503 interoperability was performed on the code developed. Although care was taken to try to provide
3504 platform independent code and tools this are the elements that are know to be Linux dependent:
3505
3506 - LCM1 hardware control tool ``lmc1.py``. @@
3507   This tool is both GUI and command line capable, the following just affects the GUI part. @@
3508   Command line should be usable under Windows systems.
3509
3510   __Cause__: Serial port search algorithm is Linux dependent and Gtk 3.0 dynamic Python bindings
3511              are not yet available on other operating systems.
3512
3513 - TI CGT support file for RPP Simulink Target ``target_tools.mk``.
3514
3515   __Cause__: Use UNIX path separator ``/``.
3516
3517 - Simulink RPP Target download script ``rpp_download.m``.
3518
3519   __Cause__: Use UNIX path separator ``/``.
3520
3521 - Simulink RPP Target install script ``rpp_setup.m``.
3522
3523   __Cause__: Use UNIX path separator ``/``.
3524
3525 - Simulink RPP Block Library block compilation script ``compile_blocks.m``.
3526
3527   __Cause__: Call Matlab MEX executable with Unix name.
3528
3529 - All CCS projects under ``<repo>/rpp/lib/apps/``.
3530   __Cause__: Paths are configure using UNIX path separator ``/``.
3531
3532
3533