Home
rtmc9s12-Target - University of Adelaide
Contents
1. es 9 e BEE RF mode Rx double top centre RF channel 12 Client 1 0 4 double top right Server address Oxe7e7e7e 0 T Client address Oxc2c2c2c2 owes double User channel 0 double bottom centre Elements 5 CET o Data type uint8 Selector H double bottom left Sample rate 0 1 s double 3 double top left 4 double centre double bottom right double RF mode TX Display RF channel 12 Client 1 Server address Oxe7efefe7 Client address 0xc2c2c2c2 User channel 1 Elements 5 Data type uint8 Sample rate 0 1 s r Comms Client 100 FixedStepDiscrete Figure 4 33 Sample model RFComm client RXTX formatted noExt mdl When experimenting with the remaining RF sample models try to find matching server and client models and run them according to what is implied by their file name External mode normal mode etc Note that some models have associated m file scripts which send data to the corresponding FreePort blocks The underlying code is fairly robust taking care of temporary loss of transmission receiver out of range resending of erroneous data packages etc The RF interface thus provides an inexpensive yet reliable means of communication between microcontrollers Using antennas we have managed to achieve a total range of around 80 meters FW 08 07 64 rtmc9s12 Target A Simulink Real Time Target for 9512 microcontrollers 4 9 Fuzzy control The 9512 microcontroller has an interesti
2. E scope 2558 0205 adt A Time offset 50 1 Figure 3 15 On the fly parameter tuning Changing the amplitude FW 08 07 37 rtmc9s12 Target A Simulink Real Time Target for 9512 microcontrollers Another way to control the data logging process is the push button Cancel trigger on the External Mode Control Panel Hitting this button stops all upload of log data the label of the Cancel trigger push button changes to Arm trigger Figure 3 16 Notice that the controller continues to execute the real time code and host and target remain connected The effect of Cancel trigger is best compared to that of a pause button To resume data logging click on Arm trigger Furthermore it is possible to disconnect from the target while keeping it running This is useful when an experiment runs for a long time and does not require permanent supervision Once disconnected the host computer can be switched off and back on without disturbing the currently running program on the microcontroller To resume control simply reconnect E test External Mode Control Panel m Connection and triggering Stop Real Time Code Arm Trigger Floating scope Enable data uploading Duration Parameter tuning Batch download Contiquration Signal amp Triggering Data Archiving Figure 3 16 Cancel trigger and Arm trigger Remarks 1 As it can never be guaranteed that the serial link between host and target remains active all
3. AEN T GEE Ora ea Seooosnnosconstosncos bonoerdosressi m ME n EE oo PS pee PENES e Pee E i s g as asp a e a A EE gt 1 400 o eee ae E o ee a 1 4 A LO Et a et Ce ne ree Cee oe EET i i 200 400 600 800 1000 1200 1400 1600 x position Figure 4 37 Robot control exercise using an rtmc9s12 Target fuzzy controller FW 08 07 68 rtmc9s12 Target A Simulink Real Time Target for 9512 microcontrollers 4 10 Timer blocks The latest addition to the toolbox is a set of timer blocks Each of the 8 timer channels can be configured in Output Compare mode OC signal generation or Input Capture mode IC time measurements 4 10 1 Output Compare mode OC In the past signal generation had to be performed either using the PWM unit or through General Purpose Input Output pins GPIO The former is suitable when the rate of the output signals needs to be much higher than the update rate of the model e g when driving small DC motors with signals in the kHz region while running the model at as little as 100 ms 10 Hz However when the period duty cycle of the PWM needs to be adjustable with 16 bit resolution only 4 separate channels can be configured Using GPIO pins on the other hand does not impose any limitation on the achievable resolution However a GPIO pin can only be set reset once every simulation cycle The maximum achievable rate on GPIO outputs is therefore limited by the base sample period of
4. FreePorlomims TX Transmit elements Comm part CO Haudrate 115200 bps Channel 1 Data type single Sample rate 0 1 s FreePartcamrms Ta 1 1 2 2 3 3 4 4 5 5 B 5 7 7 User data Receive 2 elementis Comm port COM Haudrate 115200 bps Channel 3 Data type ints sample rate 0 1 s FreePornlomms Rx1 Display T224337 440 FixedStepDiscrete Figure 4 16 Sample model FreePortComm TXRX mdl host Note When using simultaneous upload and download it is important to start the host model first then the target model This is because the S Function underlying the host sided FreePortComms_RX block flushes the reception buffer when it is started If the target model is already running by the time the host model is started it can happen that this flushing of the buffer on the host leads to the discarding of valid data bytes As the FreePort system does not yet implement a proper host target synchronization mechanism it can happen that the data packet contents are misinterpreted In this case the FreePortComms_RX block is likely to emit garbage Note that this particularity only happens with host models which include both FreePort receive as well as FreePort send blocks FW 08 07 50 rtmc9s12 Target A Simulink Real Time Target for 9512 microcontrollers 4 7 4 Download of unformatted data to the target The target model FreePortComm RX simple3 mdl and the corresponding host model FreePortComm TX simple3 mdl demon
5. FW 08 07 3 rtmc9s12 Target A Simulink Real Time Target for 9512 microcontrollers 1 Introduction and Background 1 1 Introduction rtm9S12 Target is a MATLAB Simulink toolbox for real time control using Freescale 9512 microcontrollers The toolbox turns regular Simulink models block diagrams into real time executable code In addition to the normal Simulink blocks a number of special function blocks are provided giving high level access to most hardware units of the microcontroller The controller can thus be programmed without the need for low level coding in C C or assembler The usually very time consuming testing and debugging of these programs can therefore be reduced to a minimum At the moment rtmc9s12 Target provides access to all 16 channels of the two A D converter units ATDO ATD1 the majority of the general purpose digital I O lines GPIO the eight 8 bit channels of the PWM unit four channels in 16 bit operation the 8 channels of the timer unit in output compare mode OC signal generation as well as in input capture mode IC event detection time measurements and both serial port interfaces SCIO SCI1 line speed up to 115 2 kBit s In addition there are blocks for serially loaded D A converters connected to the SPI and or the I C bus of the chip ultrasonic range finder modules e g Devantech SRF04 as well as blocks for wireless communications with other microcontrollers or a host computer The latter have
6. FW 08 07 78 rtmc9s12 Target A Simulink Real Time Target for 9512 microcontrollers Appendix FW 08 07 79 rtmc9s12 Target A Simulink Real Time Target for 9512 microcontrollers FW 08 07 80 rtmc9s12 Target A Simulink Real Time Target for 9512 microcontrollers Appendix A Possible things to do The following list of things to do is by far not complete At this stage August 2007 it is unlikely that any of it will ever be addressed by myself 1 Enabling communication using the CAN bus 2 Host to host communication using a backbone network e g Ethernet etc FW 08 07 81
7. be instructed to present any of 16 memory pages 16 kByte each gt 16 x 16 kByte 256 kByte this applies to the MC9S12DP_256 B C in this memory window Setting FW 08 07 20 rtmc9s12 Target A Simulink Real Time Target for 9512 microcontrollers the Memory map parameter to Flash_banked instructs the compiler to build code that makes use of this memory swapping mechanism Note The memory model Flash_banked should only be used if absolutely necessary It seems that at the writing of this document the generated code does not run as reliably as when using the Flash_flat memory model Support for the banked memory model has never been tested properly External Mode communications between host and target appear to get stuck too easily for reliable operation The Compile Download and Run checkbox is selected by default This option enables a all in one build process which also downloads the generated binary code to the target where it is started The compiler CodeWarrior as well as the debugger Hiware used to download the code are closed automatically at the end of the build process The External Mode checkbox enables or disables the background communication interface for process data logging and on the fly parameter tuning The External Mode interface is very useful during the design phase of a controller However once all parameter values have been found it is often more appropriate to run the target in standalone mode release vers
8. e Makefile configuration oe Comments uk Symbols enerate makehle Build pracess e Custom Code Make command Template makefile p mes 2 code gener i mc3s12 code gener mc8s12 code gener Custom storage class C Ignore custom storage classes Generate code only Build Apply Figure 2 10 Target configuration page of r mc9s12 Target The three target specific options pages mc9s12 code generation become accessible after the system target file mc9s12 tlc has been selected using the System target file browser Figure 2 11 W System target file browser Servo_PWM System target file Description asap2 tlc ASAM ASAP2 Data De ert tlc Real Time Workshop ert tlc Real Time Workshop ert tlc Real Time Workshop ert tlc Visual C C Proje ert shrlib tlc Real Time Workshop grt tlic Generic Real Time grt tlc Visual C C Proje grt _nalloc tic Generic Real Time grt malloc tlc Visual C C Proje mc9s12 tlc rtmc9s12 Target fo ONT J Full name C Eigene DateiensFrank rtmc8512 Cw R14 bin mc8s12 tlc Template make file mc3s12 tmf Make command make rtw Figure 2 11 System target file browser mc9s12 tlc FW 08 07 19 rtmc9s12 Target A Simulink Real Time Target for 9512 microcontrollers 24 Configuration Parameters Servo_PWM Configuration Active Select i Caner Target platform Dragon 12 Z Data Import E part Memory model Flash flat O plimizati T uen TM
9. no time needs to be wasted with familiarizing oneself with a new software development environment compiler debugger or microcontroller specific details such as hardware registers memory models startup files etc By reducing this development time the focus of the exercise can be shifted from low level development to system level control engineering This opens the door to realistic real world control applications e g robot control using machine vision process control experiments intelligent system of multiple autonomous mobile robots etc FW 08 07 6 rtmc9s12 Target A Simulink Real Time Target for 9512 microcontrollers The heart of the robots used in Glasgow was a Phytec phyCORE 167 single board computer This platform while reasonably powerful had one major drawback Access to the controller signals was only possibly through connectors with a very small footprint Molex This made it rather difficult for the university workshop to build interface boards for different applications It was therefore decided to redevelop the toolbox for Freescale 9512 microcontrollers The latter while probably less powerful than the C167 is a widely used microcontroller for which the marked offers a large number of development boards In addition most compilers for the C167 were found to be rather expensive Metrowerks CodeWarrior on the other hand is a relatively easy to use compiler package offered at a reasonably small price as little as US 99
10. uint Sample rate 0 1 s RF mode TX RF channel 12 Client 3 Server address xe e e e7 Client address 0xc2c2c2c2 User channel Bements 1 Data type uint Sample rate 0 1 s rf Comms Serveri rfComms_Server2 RF mode Tx RF channel 12 Client 5 Server address Oxe efefe Client address Dxc2c2c2c2 User channel Bements 1 Data type uintS Sample rate 0 1 s r Comms Server FixedStepDiscrete Figure 4 29 Sample model RFComm server TX counter 5clients noExt FW 08 07 61 rtmc9s12 Target A Simulink Real Time Target for 9512 microcontrollers E RFComm_ctient_RX_PTH_client1 ole File Edit view Simulation Format Tools Help Dlg MES inf Normal EE g 2 be Ec mm RF mode Rx RF channel 12 Client 1 D Server address xe e Tere m n deuBlo ci Client address Dxc2c2c2c2 ouble User channel Elements 1 o gr double top right Sample rate 0 1 s double bottom centre double 5 double 3 ri comms Client i double bottom left 14 double top left mt E double centre server communicates simultaneously this is client number 1 Display FixedStepDiscrete Figure 4 30 Sample model RFComm_client_RX_PTH_client1 mdl 4 8 3 Other RFComms models The remaining RFComm server and RFComm client models should make it easy to experiment with the radio modules The names of these models give an indication of what a model is trying to achieve For example server model RFComm
11. 08 07 16 rtmc9s12 Target A Simulink Real Time Target for 9512 microcontrollers Wh Sink Block Parameters Digital Output Subsystem mask Parameters Port see hardware manuals for valid options Part T Pin see hardware manuals for valid options 26 Sample time 0 00 On threshold Yor 3 5 Off threshold ott 2 App Figure 2 8 Parameters of the block Digital output 2 2 8 D A Converter unit DAC Analogue output signals can be generated using two external D A converters DACO DAC1 connected to the IC bus of the controller Two serially loaded Analog Devices D A converters AD5311 have been included on the protective circuit board we use in our laboratory They are loaded through the IC bus interface of the MC9S12 and output DC voltages between 0 and 5 volts The block parameters are Sample time DAC channel and Saturation level Figure 2 9 The latter is used to define the correspondence between block input signal level and the full scale output of the DAC FW 08 07 17 rtmc9s12 Target A Simulink Real Time Target for 9512 microcontrollers Ta Sink Block Parameters D to 4 Converter Subsystem mask Parameters Sample time 0 01 DAC channel O Saturation level Black input 5 Figure 2 9 Parameters of the block D to A converter 2 2 9 On board D A Converter unit On board DAC Revision E of the Dragon 12 board now comes with a pair of D A converters connected to the SPI int
12. Compile download and run zi Diagnostics Sample Time External mode Dt Data Validity External Made use static memory allocation Type E i E dai ipd External Mode available memory bytes 9000 Connectivity p Compatibility External Mode target reception buffer size bytes 1 000 i Madel Referencing 3 Har doe renent External Mode target transmission buffer size bytes 2000 2s Model Referencing External Made upload download FIFO butter size bytes 300 a Peak TIME n External Mode allocate FIFO buffers in batches of 5 p Comments aa Symbols External mode display an empty space indicator 8 gt 0 on the segment display gt Custom Code External mode display communication state variables on port T EE Debu EN x Eo Extemal Mode communication speed 115200 hd medal 2 code gener External mode Auto update status bar clack Extemal Mode host sided communication port COMe External Mode target sided communication port SET Figure 2 12 Configuration Parameters for rtmc9s12 Target The first of the three target specific option pages is shown in Figure 2 12 It allows the Target platform to be chosen Five different targets are supported at present Dragon 12 this also works with the new Dragon 12 Plus boards MiniDragon UofA Mobile Robot a MiniDragon based mobile robot system used at the University of Adelaide similar to the MiniDragon target but with the default communication ports set as for the D
13. PWM2_PC mdl The latter runs on the host in normal simulation mode Changing the values of either of the slider gains initiates a download through the associated FreePort communication channel The host sided model can be started stopped modified at all times It is truly independent of the target model FW 08 07 43 rtmc9s12 Target File Edit View Simulation Format Tools D cm E e Receive 2 elementis Comm part SCIL Baudrate 115200 bps Channel O Data type single sample rate 0 1 s FreePortComms Rx Z ero Order Hold Zero Order Hold A Simulink Real Time Target for 9512 microcontrollers w inf External EE d FWh A 16 bit Pulse pin PTP 1 Sign pin PTH 1 L3 Period 0 5 5 Saturation 5 Sespae Pulse width modulation F M B 16 bit Pulse nin PTP 3 Sign pin PTH 2 L3 Period 0 5 5 Saturation 5 Pulse width modulation Figure 4 7 Sample model PWM2 mdl i PWM2_pc File Edit View Simulation Format Tools Constant Constant JE int Noma l EZ Transmit 2 elementis Comm port Cahid Haudrate 115200 bps Channel O Data type single sample rate 0 1 s FreePortlomms TX Variable sStepDiscrete Figure 4 8 Host end of the user communication PWM2_pc mdl FW 08 07 44 rtmc9s12 Target A Simulink Real Time Target for 9512 microcontrollers The use of the optional monitoring output of the Pulse width modulation block is shown in Figure 4 9 Note that Figure 4 9 also show
14. block in Input Capture mode Ta Source Block Parameters Timer Subsystem mask Parameters Timer channel Channel 3 Timer mode Input Capture Timer base pernod seconds 0 3 Sample time 0 1 x Figure 4 41 Block parameters timer block in IC mode 4 11 Toggle a pin of PORTB 4 11 1 Toggling a pin of PORTB in External Mode The model TogPort mdl is a simple test model which can be used to toggle an I O pin of the microcontroller The model uses a digital square wave block to produce an on off sequence on PORTB pin 0 On the Dragon 12 development board this pin is associated with one of the on board LEDs The model should therefore make this LED flash with a period of 1 second 0 5 s on 0 5 s off Both frequency as well as duty cycle of this pulse sequence can be changed on the fly external mode FW 08 07 72 rtmc9s12 Target A Simulink Real Time Target for 9512 microcontrollers File Edit View Simulation Format Tools Help D Hg i inf External EJ gt Control an LED on the Dragonl PORTE pm X 0 gt LED off 1 gt LED on MI E PORTH Pins Pulse Zero rder ae Generator Hold Digital output LOO ode 1 Figure 4 42 Sample model TogPort mdl 4 11 1 Toggling a pin of PORTB in standalone mode The model TogPortNoCom mdl is a simple test model which runs as standalone program i e without the use of the External Mode communication interface Consequently the generated executable is
15. feature is only useful when the block sample time is much shorter than the PWM period here we work with a sample time of 10 ms and a pulse period of 100 ms This means that the resolution of the monitored PWM signal is not too high FW 08 07 42 rtmc9s12 Target A Simulink Real Time Target for 9512 microcontrollers W pwn Joy File Edit View Simulation Format Tools Help HA E Test program Pulse Width Modulation PWM The pulse pin always port PIP carries the PWM signal the sign pin indicates the direction forward reverse F urhd A 16 bit Pulse pin PTP 1 Sign pin PTH 1 Period 1 2 Slider Saturation 5 Ei Pulse width madulatian Figure 4 6 Sample model PWM mdl 4 6 Pulse Width Modulation PWM with FreePort communications Model PWM2 mdl Figure 4 7 and the corresponding host model PWM2 PC mdl Figure 4 8 demonstrate how easy it is to set up a remote controlled robot control system The target model PWM2 mdl has two PWM output channels 16 bit resolution pulse pins PTP 1 and PTP 3 For demonstration purposes the PWM period has been set to a rather long interval of 0 5 s Background monitoring is performed at a rate of 10 times per second The duty cycle of both channels is controlled by a signal which is sent from the host through a FreePort download block FreePortComms RX The host sided end of this communication channel is a FreePortComms TX block in a second independent Simulink model
16. for instance follow a reflecting track on the ground or be navigated using a vision based control system Each group was handed a simple frame for a differential drive mobile robot including a 2 channel H bridge motor driver circuit and a breadboard area for additional circuitry such as photo detectors or sonar range finders Figure 1 1 shows a similar robot developed by the School of Mechanical Engineering University of Adelaide Australia Figure 1 1 Front wheel driven mobile robot University of Adelaide robotics group The students generally liked this exercise because of its integral nature combining many aspects from a variety of areas control engineering programming electronics communications and project management However it soon became apparent that the 5 laboratory sessions 2h per session were insufficient to bring the exercise to a successful and satisfying conclusion Judging the situation from a Control Engineering point of view too much time was wasted with tedious programming tasks and the inevitable debugging of the developed programs To remedy this problem the MATLAB toolbox RTC167 Target was written giving high level access to all essential features of the controller using a customised set of Simulink S Function blocks This completely eliminated the process of having to convert a control algorithm often given in form of a block diagram into a C language program for the microcontroller Using the toolbox
17. led to a reduction in bandwidth available to the exchange of log data and or parameter records between host and target With the present release of rtmc9s12 Target the User Communication interface has been discontinued and can thus no longer be used Use the FreePort communication blocks instead see chapter 2 2 2 2 2 2 FreePort communication blocks Some applications need simple and reliable communications between several microcontroller platforms or between a microcontroller and host based applications other than MATLAB This need is catered for by the FreePort communication blocks of the toolbox These blocks allow the transmission reception of short formatted messages through either of the Serial Communication Interfaces of the 9512 SCIO SCI1 unless it is used for External Mode communications The parameters of the FreePort communication blocks are Sample time Communication port Baudrate Channel number Number of elements and Data type A tick box allows the transmission of raw data values Figure 2 2 FW 08 07 10 rtmc9s12 Target A Simulink Real Time Target for 9512 microcontrollers Ta Sink Block Parameters FreePortComms TX Subsystem mask Parameters Sample time 0 1 Communication port S CI Baudrate 175200 Channel number Humber af elements 2 Data Type UINTS Block sends raw data Brel Figure 2 2 Parameters of the block FreePortComms TX The sample time specifies the rate at which th
18. library presently 265 files During the build process the CodeWarrior IDE should open up and the generated source code should get compiled Figure 3 6 The two warnings indicating the conversion from floating point numbers to unsigned integers can safely be ignored FW 08 07 30 rtmc9s12 Target A Simulink Real Time Target for 9512 microcontrollers E E ES T Era Project rtw_dp256_flash_flatmep Target rtw_dp256_flash_flat Stop File Task File Count Line Count mc main c Compiling 6 D 27 Uer EN Files Link Order Targets File Code Data w ttw_filelist mpf n a nia m m Debugger Cmd Files D 0 a H Prm D 0 m w FQ Sources 22 oe Y 1 Startup Code 57 596 m 5 Libraries 0 0 m Figure 3 6 MATLAB generates a fully functional CodeWarrior project The fully linked binary code is then downloaded into the FLASH ROM of the target using the Hiware debugger Figure 3 7 Upon completion of this download the code is started and both Hiware as well as the CodeWarrior IDE are closed B True Time Simulator Real Time Debugger C Eigene DateieniMATLAB Mest_mc9512_rtwiMonitor ini MEX File View Run MONITOR HCSI2 Component Source Window Help psa Bla 2 2 gt 2 C031 BSR 49 abs C000 C033 JSR 0x0003 PC C037 BRA 14 abs C029 C039 BGND p T ew Les eu F w a IP C029 PC C0
19. much smaller than is the case for all other sample models approx 4 kByte instead of the typically 17 20 kByte Following the successful download of this program and a subsequent reset of the target hardware the program is automatically launched and runs until the power is switched off 4 13 Simple sonar range finder A basic interface block has been provided for the Devantec SRF04 sonar range finder Figure 4 43 FW 08 07 73 rtmc9s12 Target A Simulink Real Time Target for 9512 microcontrollers Figure 4 43 Sonar range finder Devantec SRF04 The block interface is very simple only requiring specification of the ports and pins used for the triggering of the pulse generator output as well as for the echo received line input Figure 4 44 shows the block diagram of sample model Sonar mal File Edit View Simulation Format Tools Help als des erBjes lo 2 eh Output PTT Fin 0 Input PTT Fin 1 calibrate Distance tm sonar Range Finder 100 odel 2 Figure 4 44 Sample model Sonar servicing a Devantec SRF04 sonar range finder FW 08 07 74 rtmc9s12 Target A Simulink Real Time Target for 9512 microcontrollers 4 13 Miscellaneous sample models As a proof of concept a number of the original MathWorks demo files have been built with rtmc9s12 Target and tested on the Dragon 12 development board 4 13 1 The F14 simulation The model f14 mdl is a direct copy of the
20. only works in conjunction with a real time kernel with a multi threaded task scheduler rtmc9s12 Target currently doesn t support this option FW 08 07 28 rtmc9s12 Target A Simulink Real Time Target for 9512 microcontrollers Set the stop time to inf to force the target to run forever or at least until the power is cut In External Mode the target program can be stopped by the user trough the External Mode Control Panel The completed Solver page should appear as shown in Figure 3 4 5 Configuration Parameters test Configuration Active Select Simulation time Start time 0 0 Stop time 10 0 Data Import Export OS op time j Optimization Diagnostics Sample Time Type Fised step Solver odes Bogacki Shampine Data Validity Type Conversion Connectivity Compatibility T asking mode for periodic sample times SinaleT asking Model Referencing Higher priority value indicates higher task priority p Hardware Implementation Model Referencing Real Time Workshop Comments Symbols Custom Code Solver options Periodic sample time constraint Unconstrained Fixed step size fundamental sample time 0 005 C Automatically handle data transfers between tasks mc8s12 code gener mc3 12 code gener mc8s12 code gener bal Figure 3 4 Simulation parameters Fixed step size solver Close the dialog box using the push button OK and save your model file When run on the targe
21. per seat for educational institutions Like all other Real Time Workshop RTW targets rtmc9s12 Target generates code from a Simulink model block diagram The build process initially turns the block diagram into a series of ANSI C source code files These files are then cross compiled and linked to a single MC9512 executable Once downloaded into the FLASH ROM of the microcontroller the code can be controlled using the graphical user interface of Simulink The build process is fully automated and can be customised through the Real Time Workshop options panel The generation of timing signals and other status information can be configured The options panel also allows the setting of the serial communication parameters host COM port baudrate The present version of rtmc9s12 Target makes use of Metrowerks CodeWarrior Integrated Development Environment www metrowerks com A free evaluation version of this compiler is available on the Metrowerks web page This special HC12 edition is sufficient to build small models up to 12 kByte of executable code up to 32 source code files For more demanding designs the full version of the compiler is required Inexpensive licenses are available to educational institutions The current version of rtmc9s12 Target has been developed and tested on MATLAB 7 4 R2007a The remainder of this document presents a detailed description of the installation and use of rtmc9s12 Target At The University of
22. the block Digital input The block allows specification of Port Pin number as well as the block sample time Figure 2 7 The available ports are PORTA PORTB PTH PTJ PTM PTP PTS and PTT For each of these ports one or more pins 0 7 can be selected The mask of block Digital Input is adjusted to the number of pins that has been chosen Example specifying pins 2 4 5 7 yields a Digital Input port with 4 block outputs The top most block output corresponds to pin 2 and the bottom most output is pin 7 FW 08 07 15 rtmc9s12 Target A Simulink Real Time Target for 9512 microcontrollers Ta Source Block Parameters Digital Input Subsystem mask Parameters Port see hardware manuals for valid options Port T Fin see hardware manuals for valid options 072 Sample time 0 002 Figure 2 7 Parameters of the block Digital input 2 2 7 Digital output Digital outputs can be programmed using the block Digital output In analogy to the corresponding input block section 2 2 6 this block also allows specification of Port Pin number and Sample time Figure 2 8 In addition to these block parameters a lower and an upper block input signal threshold can be specified On threshold Won and Off Threshold Voff respectively These two levels are used to decide when the block output should become high above Von or low below Voff Setting Von gt Voff allows the programming of a hysteresis FW
23. to all 5 clients and the data transmission via the radio link is not formatted The model also runs in normal mode noExt The corresponding client models are RFComm client RX PTH client mdl to RFComm client RX PTH client5 mdl Figure 4 30 A formatted version exists as well It is important to match the transmission parameters on both ends of a RF link This includes the channel number number of elements data type for formatted transmissions and consists of the number of bytes to be sent received for unformatted transmissions FW 08 07 60 rtmc9s12 Target Figure 4 28 L RFComm server TX counter 5clients noExt File Edit View Simulation Format Tools Help D GE E Comer p1100009 I A Simulink Real Time Target for 9812 microcontrollers Frequency Channel M Using the nRF24L01 in star configuration RF mode TX RF channel 12 Client 1 Server address xe e e e Client address 0xc2c2c2c2 User channel Bements 1 Data type vint8 Sample rate 0 1 s rfComms_Server RF mode Tx RF channel 12 Client 4 Server address Oxe7e7e7ve7 Client address Dxc2c2c2c2 User channel Bements 1 Data type uint8 Sample rate 0 1 s rf Comms Server3 dable op centre double op tight double bollom right double bollom cente double boliom led Display EE RF mode TX RF channel 12 Client 2 Server address Oxe efefe Client address Dxc2c2c2c2 User channel Bements 1 Data type
24. 29 PPAGE 0 SP 4000 CCR SXHINZVC ij Auto Symb Global Local Startup command file is disabled executing Monitor hwe done Monitor hue Preload command file is disabled a For Help press F1 MC9512DP256B idone Monitor hw Figure 3 7 Automatic download to the target using the Hiware debugger FW 08 07 31 rtmc9s12 Target A Simulink Real Time Target for 9512 microcontrollers Note that in our laboratory at the University of Adelaide we use Dragon 12 development boards on which we have installed Motorola s serial monitor see www mecheng adelaide edu au robotics WWW_Devs Dragon12 Dragon12 htm This allows CodeWarrior to download the code into the Flash ROM of the 9512 using its debugger Note that the generated CodeWarrior project can be re opened if the code needs to be inspected and or manual changes are to be made Should the automatic download not be desired de select the option Compile Download and Run on the first of the three target specific options pages and recompile This causes the automatic process to halt after the CodeWarrior project has been built Once the target code is running the LCD display of the Dragon 12 should show the model name test and indicate that the host has not yet connected The External Mode communication interface of rtmc9s12 Target is monitoring the serial line waiting for commands such as Connect and Disconnect Start and Stop etc Thes
25. Adelaide we use Wytec Dragon 12 and MiniDragon development boards www wytec com A number of currently known problems and recommendations for future extensions are listed in Appendix A It is hoped that this contribution will be helpful to many users in education science and research Any comments and feedback on possible flaws within the code of rtmc9s12 Target are welcome and should be directed to Frank Wornle frank wornle adelaide edu au The University of Adelaide school of Mechanical Engineering August 2007 FW 08 07 7 rtmc9s12 Target A Simulink Real Time Target for 9512 microcontrollers 2 The Simulink real time target rftmc9s12 Target 2 1 Installation 2 1 1 Installing rtmc9s12 Target The installation of rtmc9s12 Target is simple Extract the contents of the archive file rimc9S512 CW R 14 zip to a folder of your choice and run the set up setup m script The latter can be found in the main folder of the toolbox and needs to be run from the MATLAB V7 4 R2007a command line Unlike with previous versions of this toolbox it is no longer necessary to specify the location of the cross compiler CodeWarrior Similarly it is no longer required to store all model files in one and the same work directory Models can now be compiled from any accessible location This modification has been introduced to allow students to keep their work on their thumb drives and or network drives The setup script adds the following two fol
26. Ficarinm Tnalhins 1111 to D Converter Digital Input Prez Digital Output FreePortComms Aes FreeFotComma_ Te Fuzzy Controller Ete Pulse Width Modulation Comme Client Comms Server Servo Motor PM Sonar Range Finder Timer LU nit parnm Di amp Ready Figure 3 1 The Simulink library browser Real Time mc9512 Toolbox FW 08 07 26 rtmc9s12 Target A Simulink Real Time Target for 9512 microcontrollers Bitest mE File Edit View Simulation Format Tools Help Ll tl 5 Receive 1 elementis Comm part SCIL Haudrate 115200 bps Channel 0 Data type single Display sample rate 0 2 s FreePorlomms RA m Pulse Generator Figure 3 2 A simple example Real time pulse train and FreePort communication From the Tools menu select Tools Real Time Workshop Options Note that the same page can be opened using the shortcut CTRL E You should be presented with the control window for the Active Configuration Parameter Set If you have used the CTRL E shortcut you may still have to select the Real Time Workshop page Click on the System target file browser button Browse and select the rtmc9s12 Target for Metrowerks CodeWarrior then close the browser dialog box Please note that the entry for rtmc9s12 Target only appears in the System Target File Browser if MATLAB has been able to locate the file mc9512 tlc on its search path This should be the case when rtmc9s12 Target has been instal
27. _error 5 6 mixing Figure 4 34 Inverted pendulum control using FlouLib blocks Fuzzification of the inputs position error 044 and rate of change of the position error d04 er dt can be achieved using a simple text file which is as call up parameter in the SymbFuz block In the case of the inverted pendulum example three linguistic terms are used N negative position errors Z zero ish position errors and P4 positive position errors The input membership functions MSF can be defined as follows E N1 1 1 1 O A cJ Y 9 1 PE D 1 lI J Note that the input scaling gains g g4 have been chosen to arrive at an effective universe of discourse of 1 The output membership functions are defined in a similar way In the inverted pendulum example we have chosen a total of 5 output MSFs Nb FW 08 07 65 rtmc9s12 Target A Simulink Real Time Target for 9512 microcontrollers N4 Z P4 and P2 The effective universe of discourse is mapped onto the normalized range from 1 to 1 An output scaling gain go ensures that the required signal levels are achieved 3 NZ L355 Tub Sele RS N1 Sl 70s 30159 O iy O O OF Dus Pel 0 Obs CEES 1 PA Wu 1 d E Finally the rule base is specified in form of another text file With 2 inputs PD and 5 output membership functions the following rule base can be specified Z N1 Ni Z Z Z AW EL El The shown example produces a linear control surface The fuzzy controller therefore em
28. an one signal are to be monitored and or when working with large parameter sets which frequently need to be downloaded to the target FW 08 07 35 rtmc9s12 Target A Simulink Real Time Target for 9512 microcontrollers E Configuration Parameters test Configuration Active Select i Data Import Esport j Optimization Diagnostics Sample Time Data Validity Type Conversion Connectivity Compatibility j Model Referencing j Hardware Implementation Simulation time Stark time 0 0 Stop time int Solver options Type Fited step Solver discrete no continuous states Periodic sample time constraint Unconstrained Fixed step size fundamental sample time 0 005 Tasking mode for periodic sample times SingleT asking Higher priority value indicates higher task priority C Automatically handle data transfers between tasks Model Referencing Real Time Workshop Comments Symbols Custom Code mc8s12 code gener mcS3s12 code gener mc8s12 code gener bal Figure 3 13 No continuous time states no ODE solver required Note that you may have to change the Scope trigger point to match the chosen time axis range Stop the model execution Simulink automatically disconnects from the target Change the scope setting back to 10 seconds and reconnect to the target Running the target code should cause a square wave to be plotted up to only half the width of the scope 5 seconds before t
29. been written for the Nordic nRF24L01 radio frequency transceiver 2 4 GHz This chip is the heart of a small inexpensive communications module distributed by SparkFun Electronics MiRF v2 less than US 20 range 80 m at 250 kBit s http www sparkfun com commerce product info php products id 05 Additional hardware units can easily be integrated using user supplied s functions or Target Language Code script files tlc The target platform microcontroller can communicate with a host machine personal computer PC through a serial connection RS 232 null modem This allows real time process data to be monitored and control parameters to be tuned on the fly The host to target communication has been based on Simulink s External Mode interface thereby fully integrating rtmc9s12 Target into the Simulink environment This makes it possible to simulate a model on the host normal mode before building real time executable code to be run on the target platform external mode No changes have to be made to the block diagram when switching from normal mode to external mode A useful extension of the External Mode interface has been devised to provide a set of upload and download channels for the optional exchange of user data telegrams between host and target This feature gives the microcontroller access to resources on the host e g PC based data acquisition cards vision systems data bases etc Using the host as a simple information server t
30. blocks of the toolbox This latest addition to the toolbox provides a simple interface for wireless communications using Nordic nRF24L07 radio modules 2 4 GHz maximum data throughput 2 MBit s These powerful little communication modules have been integrated in the easy to use transceiver circuits MIRF v2 distributed by SparkFun less than US 20 2006 In our laboratory we use these transceiver chips on our mobile robots Figure 4 21 Figure 4 21 RF modules on the mobile robots used at The University of Adelaide The software interface to the MiRF v2 modules written by one of our students Stephen Craig in support of a final year project design of an autonomous paraglider has been integrated in a series of blocks for the toolbox The structure of these blocks resembles that of the FreePort communication blocks At present the toolbox supports one radio module per microcontroller The built in transmission layer of these modules allows for bidirectional communications e each module can be used to transmit as well as receive using one of 128 separate RF channels Set up as a transmitter the RF Server block can transmit data to up to 5 clients Figure 4 22 shows the sample model RFComm server TX freePortO 5x2 formatted noExt mdl This model sets up two server transmit TX blocks using logical channels 0 and 1 Per client up to 10 of these logical channels can be chosen These channels resemble the channel number of the FreePor
31. ders to the MATLAB search path variable RTMC9S812 TARGET ROOT gt bin lt RTMC9S12 TARGET ROOT gt mc In addition the setup script modifies a number of XML files which define the template CodeWarrior projects used to build the models under a variety of code generation options Moving the toolbox from one machine to another requires the setup script to be run again to adjust these template project files to the new environment 2 1 2 System heap space With previous releases of this toolbox it was necessary to increase the amount of heap space allowed for by CodeWarrior This is no longer required as the present version of rtmc9s12 Target uses static memory allocation thus not making any use of the heap space of the system 2 1 3 Migrating models from R13 1 to R14 Models which have been generated for and used with the previous release of the toolbox for MATLAB 6 5 1 R13 1 can be converted to the current release using the update9s 12models script At the MATLAB command prompt type gt gt update9S12models lt myModel mdl gt This converts model myModel mdl to the new style Replacing the call up parameter by the name of a folder converts all models found in this folder FW 08 07 8 rtmc9s12 Target A Simulink Real Time Target for 9512 microcontrollers 2 2 The rtmc9s12 Target block set Upon successful installation of rtmc9s12 Target the Simulink library browser should include a new entry called Real Time mc9s12 Toolbox
32. double top right 0 34 N double L double double bottorn right 5 m zal D double bottom centre l double double 3 3 Selector double bottom left q LL Ll double top left double centre double dot Display RF mode RX RF channel 12 Client 1 Server address Oxefe7efe Client address Oxc2c2c2c2 User channel 1 Elements 7 Data type uint8 Sample rate 0 1 s FreePortComms_Tx1 Transmit 7 elements Comm port SCI1 Baudrate 115200 bps Channel 1 Data type uint8 Sample rate 0 1 s r Comms Clienti FixedStepDiscrete Figure 4 25 Sample model RFComm client RX freePortO 5x2 formatted noExt FW 08 07 58 rtmc9s12 Target A Simulink Real Time Target for 9512 microcontrollers Ta RFComm client RX freePort 5x7 formatted PC JE File Edit View Simulation Format Tools Help niEHS I om ini Normal EE pe Receive 5 elementis Comm part COM Haudrate 115200 bps Channel O Data type uinta Sample rate 0 1 s FreePartcamms Rx1 Receive 7 elementis Comm port COM Baudrate 115200 bps Channel 1 Data type uinta sample rate 0 1 s FreePortComms Rx Display T 44 70 720 FixedStepDiscrete Figure 4 26 Host model for RFComm client RX freePortO 5x2 formatted noExt 4 8 2 RFComm Client The models RFComm client MODELNAME mdl are simple test models which can be used to experiment with the radio frequency RF wireless communication blocks of the toolbox The block paramet
33. dow second button from the left see Figure 3 9 Time offset Figure 3 9 Changing the scope display settings The appearing dialog box allows the scope settings to be customised Figure 3 10 Replace the automatically chosen Time range by a fixed value of say 5 seconds Close the dialog box using the OK push button The modified scope settings can be saved using the push button Save current axis settings 6 button from the left within the toolbar of the scope window E sco pe parameters General Data history Tip try right clicking on axes Axes Humber of axes 1 floating scope Time range auta Tick labels bottom axis only se Sampling Decinaion y f Figure 3 10 Adjusting the scope settings FW 08 07 33 rtmc9s12 Target A Simulink Real Time Target for 9512 microcontrollers Re launch the real time code Connect then Start real time code The scope block should now display the trace of the pulse train as produced by the pulse generator The display block should display a value of 0 Upon starting the host model test PC mdl the display block should change to the value which is sent by the host Open the slider gain block and change this value The target should immediately update to the new value E scope amp E fam SA Time offset 10 075 Figure 3 11 Adjusted scope settings As expected the graph of the square wave signal has a period of 2 seconds Figure 3 11 It is worth noting
34. e entire available idle time between subsequent sample steps for upload download Further details about FreePort communication can be found in chapter 2 2 2 35 Configuration Parameters Servo PWM Configuration Active iin Timing signals i Data Import Export Cycle time signal pin 5 j Optimization Diagnostics Sample Time Timing signaling port PORTE Data Validity Type Conversion Connectivity Compatibility j Model Referencing j Hardware Implementation Model Referencing Real Time Workshop Comments Symbols Custom Code Serial reception signal pin 6 C Run upon reset Core Timer Select ATI mc8s12 code gener ee ee UR CM MUS imeal code gener Figure 2 13 Configuration Parameters for rtmc9s12 Target The second page of target specific options Figure 2 13 controls the display of timing signals on a configurable port pin of the microcontroller Access to low level timing information is generally helpful during the setting up of a new control algorithm The exact duration of the control cycle is displayed on the chosen I O pin from where it can be monitored using an oscilloscope In addition to this so called cycle time the controller also displays the activity on the serial reception line RxD This information has proved to come in handy during the debugging of new communication modules To disable the display of timing signals deselect the check box Timing signals Figure 2 14 shows how the timing
35. e block is updated by the timing ISR target sided block or by Simulink host sided block Short sample times reduce the bandwidth which is available for the monitoring of process data and other FreePort data channels The channel number can range from O to 9 It is used to identify corresponding transmit txd and receive rxd blocks on the host and on the target To increase the currently available number of 10 user channels the source code macro MAX FREEPORT CHANNELS should be redefined and all related code sections need to be re compiled e g the S Functions freePortComms_rxd and freePortComms_txd The parameter Number of elements defines the width of the block input transmission and of the block output reception Together with the parameter data type the number of elements defines the size of the communication buffers Each buffer is currently limited to a maximum size of 100 bytes The communication port defines whether a block is used as host block COM1 COMA or as target block SCO and SCI1 The build process performs a check for inadequate port settings such as the use of the same SCI port for both External Mode communications as well as FreePort communications At the writing of this document baudrates ranging from 300 bps to 115200 bps are supported Ticking the box labeled block sends raw data causes the underlying S Function to send unformatted raw data telegrams In this case only the selected number of data b
36. e commands can be sent to the target using the External Control panel From the Tools menu choose the item External Mode Control Panel Figure 3 8 B test External Mode Control Panel E Connection and triggering Floating scope Enable data uploading Duration auto Parameter tuning Batch download Contiquration Signal amp Triggering Data Archiving Figure 3 8 External Mode Control Panel Real Time Workshop assumes a real time target to be an autonomous unit to which a user has to connect before any further interaction can take place Click on the push button Connect to initiate the communication between RTW and the target model code Once connected the LCD display should indicate that the trigger is now armed Start the real time code using the push button Start real time code The LCD display should switch to running Open the Scope block to display the uploaded signal of the Pulse Generator block Note that the scope axis is at its default setting of 10 seconds To change this first stop the real time code by clicking on the Stop real time code FW 08 07 32 rtmc9s12 Target A Simulink Real Time Target for 9512 microcontrollers button of the External Mode Control Panel This is not really required as scope display changes can be made while the target code is running Note that once the target code has been stopped RTW also disconnects from the target Click on the parameters push button of the scope win
37. ed If the target model is already running by the time the host model is started it can happen that this flushing of the buffer on the host leads to the discarding of valid data bytes As the FreePort system does not yet implement a proper host target synchronization mechanism it can happen that the data packet contents are misinterpreted In this case the FreePortComms RX block is likely to emit garbage Note that this particularity only happens with host models which include both FreePort receive as well as FreePort send blocks 2 Using FreePort in parallel to the External Mode interface seems to require the target to be run out of ROM target reset required strange but seems to be the case to prevent the on chip serial monitor from interfering with the FreePort interface SCIO 3 The FreePort communication blocks have been designed to cover a maximum number of situations They can be used for serial communication between 2 hosts e g COM1 on host A to COM on host B COM1 to COM2 on one and the same host loop back operation between a host and a target or between two different targets e g microcontroller A to microcontroller B FW 08 07 53 rtmc9s12 Target A Simulink Real Time Target for 9512 microcontrollers 4 8 Wireless communications 4 8 1 RFComm Server The models RFComm server MODELNAME mdl are a number of simple test models which can be used to experiment with the radio frequency RF wireless communication
38. ed timer channel just imagine the situation where the slowest channel demands an overall resolution of approximately 5 us modulating a signal with a maximum period of 20 us now only allows for 4 discrete steps Figure 4 39 shows the block parameters of the timer block in Output Capture mode iw Sink Block Parameters Timer1 Subsystem mask Parameters Timer channel Channel 1 Timer mode Output Compare Timer base period seconds 0 001 Sample time 0 1 Figure 4 39 Block parameters timer block in OC mode The timer blocks can be used to produce simple driver models for stepper motor driver circuits who might require a pulse sequence and a direction signal as inputs On our mobile robots we are using pairs of stepper motors driven by dedicated stepper motor driver circuit board The command input to this board is a square wave signals whose FW 08 07 70 rtmc9s12 Target A Simulink Real Time Target for 9512 microcontrollers frequency defines how fast the stepper motor sequence is cycled through The timer blocks in OC mode are ideally suited to provide the required command signals 4 10 2 Input Capture mode IC The biggest benefit from adding timer blocks to the toolbox is that it is now possible to perform simple measurements of durations between events At present the timer block in Input Capture IC mode measures the length of the time interval between any two subsequent rising edges on the associated input pin Th
39. el 1 Data type single sample rate 0 1 s FreePorlomms 11 ode45 Figure 4 47 Sample model Robot_pc mdl host 4 13 3 Band limited white noise generator The target model BLNoiseTest mdl is a simple test model to ensure the correct operation of the automatically generated real time libraries This example generates band limited white noise in form of pulses which are monitored at a rate of 20 Hz Ta Bl HoiseTest File Edit View Simulation Format Tools Help External i Test program Band limited white noise PWR 0 1 Step size 0 005 upload frequency 0 05 s Scope Band Limited Zero Order White Hoise Hold Figure 4 48 Sample model BLNoiseTest mdl FW 08 07 77 rtmc9s12 Target A Simulink Real Time Target for 9512 microcontrollers 4 13 4 Generation of a chirp signal frequency wobbling The target model ChirpTest mdl is a simple test model to ensure the correct operation of the automatically generated real time libraries This example generates a sinusoidal oscillation with slowly increasing frequency The frequency is wobbled from 0 1 Hz to 1 Hz over a sweep time of 60 seconds L7 ChirpTest e JJ ES File Edit View Simulation Format Tools Help D e hs E 60 External Test program Continuous time Chip signal source Frequency sweep from 0 1 Hz to 1 Hz in 60 seconds sample rate 5 ms upload every 20 ms 50 Hz Chirp Signal Zero Order Hold Figure 4 49 Sample model ChirpTest mdl
40. erface of the controller These serially loaded DACs can be accessed using the On board DAC blocks of the toolbox Note that the inclusion of the On board DACs in a model causes the exclusion of RF Communication blocks as the latter also use the SPI The block parameters are Sample time DAC channel and Saturation level The latter is used to define the correspondence between block input signal level and the full scale output of the DAC The parameter mask of the On board DAC is identical to that of the lC DAC see Figure 2 9 FW 08 07 18 rtmc9s12 Target A Simulink Real Time Target for 9512 microcontrollers 2 3 Code generation options Real Time Workshop RTW allows a number of options to be specified during the code generation for a particular target platform All RTW options can set through the menu Tools gt Real Time Workshop Options Figure 2 10 shows the target configuration page of rtmc9s12 Target 8 Configuration Parameters Servo PWM Configuration Active Select Target selection E System target file mods 12H Browse Data Import E sport a A on E Optimization Language E ba E Diagnostics Sample Time r Data Validity Generate HTML report Type Conversion m Connectivity Compatibility Include hyperlinks to model Documentation Launch repart automatically j Model Referencing De Hardware Implementation Model Referencing TLC options El RealTime Workshop
41. ers of the client blocks are very similar to those of the server blocks Figure 4 27 The client number now specifies which client this block belongs to FW 08 07 59 rtmc9s12 Target A Simulink Real Time Target for 9512 microcontrollers E Source Block Parameters rfComms Client Subsystem mask Parameters Sample time 0 1 Communication mode 1 lt Aa Reception Ax HF channel number U 127 12 Client number 1 y Server address 4 bytes hexadecimal notation e g see efe Oserererer Client address 4 bytes hexadecimal notation e g Oxcececec Uececececs User channel number 3 0 Humber af elements to be sentrecelved H Data Type UIMTS Block sends receives raw data Black output iz double Figure 4 27 Block parameters of block rfComms Client The nRF24L01 is very versatile Many more configurations are possible One module could for instance be configured to act as a central base station receiving data through up to 6 separate data pipes This might be of interest in applications in which a number of sensors need to be connected to a central hub Figure 4 28 shows the star configuration with a primary receiver and 6 transmitting nodes The same network topology can be used to transmit data to up to 5 different clients Figure 4 29 shows an example RFComm server TX counter 5clients noExt mdl which services 5 clients simultaneously In this example the same information is relayed
42. f clock source RTI TC7 does not really matter FW 08 07 23 rtmc9s12 Target A Simulink Real Time Target for 9512 microcontrollers Figure 2 16 shows the third page of target specific options This page allows options to be set for a variety of aspects of the generated code as well as the build process The rebuilding of the static libraries of the MATLAB blocks can be enforced Other options control the use of the on board LCD display of the Dragon 12 The default setting is on for the Dragon 12 and off for MiniDragon based targets as the latter does not feature an LCD display Option RT logging information debug on SCIO should only be used by developers A number of settings allow the display of target debugging messages on the commonly vacant Serial Communication Interface SCIO Dragon 12 Selecting the MiniDragon board not the UofA Mobile Robot automatically deselects this option as the MiniDragon commonly uses SCIO to communicate with MATLAB any Configuration Parameters Servo PWM Configuration Active Select MAT file variable name modifier rt Data Import E part C Integer code only j Optimization Diagnostics Sample Time Data Validity HT logging information debug on SCIO O Type Conversion Connectivity Compatibility j Model Referencing j Hardware Implementation Model Referencing gt Real Time Workshop Comments L Force rebuild of the static libraries used by the model Use LED di
43. formation about its orientation are supplied from a suitably programmed video grabber unit and sent to the robot using two separate user channels Many more applications can be thought of and put together in minutes including the communication between various mobile robots This opens the FW 08 07 75 rtmc9s12 Target A Simulink Real Time Target for 9512 microcontrollers door to applications using artificial intelligence and the co ordinated collaboration of otherwise autonomous units Ta Robot File Edit D tl g FW 08 07 Receive 2 elementis Comm port SCIU Baudrate 115200 bps Channel 0 Data type single sample rate 0 1 FreePortCoamms Ra Receive 1 elements Comm part SCIU Baudrate 115200 bps Channel 1 Data type single sample rate 0 1 5 FreePartcamms Rx1 View Simulation Format Fh A 16 bit Pulse pin PTP 1 Sign pin PTH 1 Period 0 01 s Saturation 5 Pulse width modulation PY hi B 16 bit Pulse pin PTP 3 Sign pin PTH 2 Period 0 01 5 Saturation 4 Pulse width modulation Figure 4 46 Sample model Robot mdl target rtmc9s12 Target A Simulink Real Time Target for 9512 microcontrollers Bi Ro bot pc File Edit View Simulation Format Tools Help Normal Transmite elements Comm part CO Baudrate 115200 bps Channel 0 Data type single Sample rate 0 1 s thd motor FreePartCarmrmis TX Transmit 1 elementis Comm port COT Baudrate 115200 bps Chann
44. he Freescale 9512 simele multiple channel AD Sample rate 2 ms discarding factor 10 gt 50 uploads per second channel ADE Input Channels Z 4 ADE Input Figure 4 1 Sample model AD 9812 mdl FW 08 07 39 rtmc9s12 Target A Simulink Real Time Target for 9512 microcontrollers 4 2 ADC_DAC mdl 4 2 1 External DAC on the IC bus UofA protective circuit board Model ADC DAC mdl reads ADC channel 2 100 times per second and multiplies the converted value with a sine wave The output of this operation is then sent to the D A Converter on the protective circuit board IC bus DAC channel 0 A saturation block ensures that the DAC input values remain within the valid range 0 5 Note that this model does not use any data upload blocks The External Mode could therefore be switched off to reduce the size of the target executable to approximately 1 3 of its current size ADC DAC Sex File Edit View Simulation Format Tools Help External ADC Input Channel ADC Input Dot Product Saturation D to A Converter Sine Wawe LOO Figure 4 2 Sample model ADC DAC mdl 4 2 2 On board DAC on the Dragon 12 Rev E SPI Model Onboard DAC Dragon12 RevE mdl Figure 4 3 sends a value to channel 0 of the on board DAC on the Dragon 12 board Rev E and later This D A converter is connected to the Serial Peripheral Interface SPI FW 08 07 40 rtmc9s12 Target A Simulink Real Time Target for 9512 microcontro
45. he horizontal trigger is reached This can be explained as follows At the chosen sample rate of 0 005 seconds it takes 2000 samples to reach 10 seconds However the default setting for the trigger is after 1000 data points In our case this mark is reached ever 5 seconds From the External Mode Control panel Figure 3 8 choose Signal amp Triggering Set the Trigger Duration to 2000 Figure 3 14 Close this window and restart the target code Note that this does not require the code to be rebuilt as the modification only affects the host based scope display With the new trigger setting the trace is plotted up to 10 seconds before the trigger point is reached FW 08 07 36 rtmc9s12 Target A Simulink Real Time Target for 9812 microcontrollers A test External Signal tt Triggering Signal selection Block Path X Display test Display a v Select all A Scope test 3cope E Clear All Trigger Signal m Go To Block Trigger Source manual E Mode normal Iw p nn l TE aa Arm when connecting to target Apply Figure 3 14 Configuring the Upload signal trigger Note that most controller parameters can be changed while the controller is running on the fly parameter tuning As an example change the amplitude of the Pulse Generator block The Scope block should immediately reflect the requested change Figure 3 15 shows a jump from an amplitude value of 1 to the new amplitude 2 then 9 then back to 1
46. he microcontroller is given access to an extremely wide range of applications rimc9s12 Target is based on a similar toolbox for Infineon C167 microcontrollers www mecheng adelaide edu au robotics WWW Devs c167Web RTC167 Target htm This predecessor toolbox had been written for a small single board computer featuring the Infineon C167CR LM microcontroller 256 kBytes of external Flash ROM and 256 kBytes of external RAM Phytec phyCORE 167 www phytec com With its relatively large memory the phyCORE 167 allowed for much larger communications buffers than what could be achieved on the Freescale MC9S12DP256 where everything has to fit into the 12 kByte of internal RAM A second advantage of the C167 over the 9512 is its vastly more versatile timing unit 5 independently programmable timers and a FW 08 07 4 rtmc9s12 Target A Simulink Real Time Target for 9512 microcontrollers priority based interrupt system 64 priority levels there are none on the 9512 These differences cause the host target communication system of rtmc9s12 Target to be slightly less robust than that of its predecessor Nevertheless rtmc9s12 Target has been found to perform reasonably well in most applications A large number of sample programs have been included with this toolbox to assist new users with the first few experiments At present r mc9s12 Target can be run on Wytec MiniDragon boards as well as Wytec Dragon 12 and or Dragon 12 Plus boards www evbplus c
47. iables of the External Mode communication system can be displayed on the pins of port T PTT At the University of Adelaide we use a protective circuit board on which the state of port T is visualized using LEDs The display of the External Mode communication state is only useful for developers and fault finding Consequently this option is deselected by default The remaining few options define the communication line speed in bits per second the host sided communication port COM1 COMA4 and the target sided communications port SCIO or SCI1 Option Auto update status bar clock can be selected to enable the display of the current simulation time in the status bar of the model The option is deselected by default as this information is also visible in each of the scope blocks FW 08 07 21 rtmc9s12 Target A Simulink Real Time Target for 9512 microcontrollers and the additional traffic on the serial communication line can thus be avoided It seems that the target runs more smoothly without the clock Note The FreePort communication blocks are independent of the External Mode interface They can be used to upload download short message telegrams currently limited to 100 bytes from to the target When used in parallel to the External Mode communication system FreePort communications may appear somewhat sluggish This is because these telegrams can only be sent once every sample step The External Mode interface on the other hand uses th
48. iated output pin always port T for Timer Note that the factor 2 is due to the fact that the associated interrupt service routine ISR simply toggles the output pin Every time the timer reaches the requested period value the output pin reverses its current state 0 gt 1 1 gt 0 Decreasing the block input signal level from 1 100 of the requested period to values below 1 makes the produced signal become faster as the effective period is now a fraction of the full scale value Block input signals below the threshold given by the resolution switch the associated output to inactive 0 V This can be used to enable disable a timer channel only using 0 off and 1 on as block inputs or to modulate the frequency of the associated channel values between O and 1 Sample model Timer OC 2 mdl Figure 4 38 gives an example of a simple frequency modulation FM system FW 08 07 69 rtmc9s12 Target A Simulink Real Time Target for 9512 microcontrollers Timer OC 2 JE File Edit wiew Simulation Format Tools Help O oe E amp inf Normal EJ Test program Timer Output Compare mode Channel 1 Mode OC Period 0 001 Resolution 4 166 726 006 Repeating Sequence Timer 100 FixedStepDiscrete Figure 4 38 Frequency Modulation FM square wave signal 500 Hz lt gt 10 MHz Note that the limitations of the shared central clock generator see above also limit the resolution of a modulat
49. ievable resolution within each group depends on how similar the individual periods are It is commonly a bad idea to define both very slow and very fast PWM channels within the same group See chapter 4 for an example of a multi channel PWM model FW 08 07 13 rtmc9s12 Target A Simulink Real Time Target for 9512 microcontrollers Ta Sink Block Parameters Pulse Width Modulation Subsystem mask Parameters Sample time 0 01 Resolution 16 bit Pi period 8 bit up to 0 699 e 16 bit up ta 179 2 2 Pulse pin PTP 3 8 bit 16 bit Sign port PTH Sign pin 4 Saturation input level simulated voltage 100 Signal monitoring Figure 2 5 Parameters of the block Pulse width modulation An optional block output can be displayed by ticking the Signal monitoring check box This allows the current state of the PWM output signal to be uploaded to the host Please note that this feature is only useful when the block sample time is much shorter than the PWM period 2 2 5 Servo Motor Pulse Width Modulation unit PWM Servo motors are driven by Pulse Width Modulated PWM signals with a very short duty cycle typically 2 12 These signals can be generated using the Servo Motor Pulse Width Modulation block The current version of rtmc9s12 Target offers 4 to 8 PWM channels depending on the resolution of each individual channel The unit can be configured for up to 4 16 bit PWM channels or up to 8 8 bit channels Block input
50. igured to switch a line high whenever the incoming signal exceeds 3 5 A port line is switched low when the input falls below 2 Port SCIO is the free communication port on the Dragon 12 when using External Mode Without External Mode communications both ports are free The display shown in Figure 4 11 only shows the incoming data when using External Mode communications d FreePortComm EX simple i File Edit View Simulation Format Tools Help E 1 im Lj m HB uU inf External E Receive 5 elementis Comm port 510 Baudrate 115200 bps Channel O Data type uinta sample rate 0 1 s FreePortComms RA Display PTH Digital output FixedStepDiscrete Figure 4 11 Sample model FreePortComm_RX_simple mdl target Figure 4 12 is the corresponding host sided block diagram Note that instead of using a host sided Simulink model the command freePortSend could have been used This is often more convenient especially when the data to be sent is produced by an m file FW 08 07 46 rtmc9s12 Target A Simulink Real Time Target for 9512 microcontrollers Command freePortSend has the following syntax freePortSend 1 115200 0 5 2 12345 This sends data via COM1 at 115200 bps using channel 0 The number of elements to be sent is 5 and they are of type 2 uint8 O single 1 int8 2 uint8 3 int16 4 uint16 5 int32 6 uint32 7 boolean the data values are then numbers 1 5 For an example of how to use comma
51. ion The code size can be reduced significantly when the External Mode option is deselected All other options on this page are only used when the External Mode checkbox is ticked Most of these options have to do with the memory management of the External Mode interface They commonly do not have to be modified by the user The checkbox use Static memory allocation should always be selected It includes a customized memory manager thus substituting the heap space based dynamic memory management routines malloc calloc and free Once static memory management is used the maximum available amount of memory can be specified in option External Mode available memory byte This memory pool is the base container for all communication related buffers e g the target reception buffer the target transmission buffer and the upload download FIFO buffers On the Dragon 12 the current emptiness of the target based transmission buffer can be displayed on the 7 segment display A value of 9 denotes a completely empty upload buffer As the buffer fills the displayed values decrease until they reach 0 A full buffer is represented by The buffer can fill temporarily when the host is busy e g when the user opens a menu in Simulink while the model is running Once this blockage is removed the current contents of the buffer are uploaded to the host and normal operation resumes The display jumps back to 9 Additional state var
52. ion Docks ooo e pp tirar iti appa 10 59 AdxConverter mit AD a 12 2 2 4 Pulse Width Modulation unit PWIM oooccccnnnnnnnnnnnnnnnnnnononnccnccncnnnnnnnnnnnnnnnnononanoos 13 2 2 5 Servo Motor Pulse Width Modulation unit PWM eere 14 2 2 6 Dita el ed a eer 15 Do Dista Opt aiii 16 2 2 8 DA Converter unt DAC a Me Ed 17 2 2 9 On board D A Converter unit On board DAC eene 18 259 Code PenerationuDIDNHS tt ito f dace cedet 19 Building a simple model A mini tutorial eee e eee e eee ee eere eee eene nenne nonne 25 The xample models 2 ivt Eve va Fats evt Dao Cea eo ere bvo ev euo E da Eod eau Gee dia Pru Ee vea ER evi dios 39 dd AD STD dl usitatum A Mee cs M NET ace 39 LV ADC DAS IM erpen 40 4 2 External DAC on the C bus UofA protective circuit board 40 4 2 2 On board DAC on the Dragon 12 Rev E SPI sseseeeeseuuuee 40 OLN TOG IA sterne E DM M KM DM 41 T DOUT TON dauid tmi isdem disi eM LL 42 AS Pulse Width Modulation PWHM s ete ete aet etu as e t CA sea due 42 4 6 Pulse Width Modulation PWM with FreePort communications 43 qu ERGOPORLCODIWIWGCOI LOS a us oci debut A A its 46 4 7 1 simple download of data to the target oocccccccccccccncnnnnnnnnnnnnnnncnnnnnnnnnnininininos 46 4 7 2 Simple upload of data from the target ooococcccncnnnnnnnnnnnnnnnnnnnnnnn
53. is value is then scaled to seconds and presented at the block output All resolution issues introduced above apply to the Input Capture mode as well Figure 4 40 shows the sample model Timer mdl which features timer blocks in both Output Compare as well as Input Capture mode Note that only one of the blocks shows a resolution term The other blocks derive their resolution from the block with the longest period In this case this is the Input Capture block channel 3 requested period 0 3 seconds The specified period of an Input Capture block defines the longest time interval between the two events rising edges Exceeding this period might lead to unpredictable results Using the timer in IC mode should make it a relatively straight forward task to interface to echo pulse sensors such as sonar range finders or optical motor shaft encoders Timer Ja File Edit View Simulation Format Tools Help DEBES inf External EE e Test program Timer Output Compare and Input Capture mode Channel 1 Mode Qc Period 0 3 an off4 Resolution automatic Timers Channel 3 Mode IC Period 0 3 Resolution 5 3333e 006 Display Timers Channel 2 Mode OU Period 0 0001 Resolution automatic Timer 100 odel Figure 4 40 Sample model Timer mdl Output Compare and Input Capture FW 08 07 71 rtmc9s12 Target A Simulink Real Time Target for 9512 microcontrollers Figure 4 41 shows the block parameters of the timer
54. l 13 network whereas the outer robots are clients 1 to 5 of the channel 12 network FW 08 07 57 rtmc9s12 Target A Simulink Real Time Target for 9512 microcontrollers Figure 4 24 Multi robot experiment Figure 4 25 shows the client model which could be used to form the receiving end of this model RFComm client RX freePortO 5x2 formatted noExt It has a very similar structure to that of the above model The first element of the 5 bytes received on logical channel is filtered out and controls the 7 segment display on the MiniDragon board In addition the data is sent through serial communication interface SCI1 to a model running on the host The latter is shown in Figure 4 26 Note that like the FreePort communication blocks the rfComms blocks can be configured to send and receive unformatted data streams In this case all incoming bytes up to 32 are sent without adding a telegram header number of bytes channel number data type a RFComm_c tient_RX_freePort0_5x2_formatted_noExt BAX File Edit View Simulation Format Tools Help Dic B S t BBLS Tl cd nf Normal IE Moi RF mode RX RF channel 12 Client 1 Server address Oxefe7efe Client address 0xc2c2c2c2 User channel O Elements 5 Data type uint8 Sample rate 0 1 s FreePortComms TX Transmit 5 elementis Comm port SCI1 double 5 Baudrate 115200 bps Channel 0 Data type uint8 Sample rate 0 1 s r Comms Client double top centre
55. led using the provided m file script setup m If everything has worked so far the Options dialog box should look like Figure 3 3 FW 08 07 27 rtmc9s12 Target A Simulink Real Time Target for 9512 microcontrollers E Configuration Parameters test Configuration Active Select Target selection System target file mc3s12 He Data Import E sport Ar E ME IONE Optimization Language C T Diagnostics Description rtmc8s12 T arget For Metrowerks Code ariar Sample Time l Data Validity Documentation Type Conversion Generate HTML repart H Connectivity Compatibility i Model Referencing Include hyperlinks ta model Launch report automatically Hardware Implementation Model Referencing Real Time Workshop TLC options Comments Makefile configuration Symbols i Custom Code Generate maketile Build process E Make command mc8s12 code gener mcS3s12 code gener mc8s12 code gener Template makefile Custom storage class Ignore custom storage classes C Generate code only e Figure 3 3 Options dialog box Real Time Workshop Now select the first of the three mc9s12 code generation options pages Figure 2 12 Ensure that the External mode check box is selected and that the communication parameters have been set to 115200 bps and the COM port you are using on your host machine lt may be required to deselect and then re select the External Mode option to make Simulink switch to Exte
56. llers ii Onboard DAC D ragont2RevE JOE File Edit view Simulation Format Tools Help C c E E inf External Ed de Test program Digital to analogue conversion Onboard DACO Onboard DACI DACO Constant i On board D to A Converter Figure 4 3 Sample model Onboard DAC Dragon12RevE mdl 4 3 DigINPort mdl The model Dig NPort md allows monitoring of the state of digital input lines 0 1 and 2 of port PTH The upload of log data is performed every 20 ms E DielNPort Tog File Edit wiew Simulation Format Tools Help PTT Pins 01 2 Digital input Figure 4 4 Sample model DigINPort mdl FW 08 07 41 rtmc9s12 Target A Simulink Real Time Target for 9512 microcontrollers 4 4 DigOUTPort mdl The model DigOUT Port mdl allows the control of digital output lines Here pins 2 and 6 of port PTT can be controlled using a slider gain Gain parameter download is performed continuously sample time 0 whereas the upload Display has been limited to 10 times per second Notice that the outputs switch high when the slider gain exceeds the On Threshold Von 3 5 the are switched to low when the slider gain is set to values below the Off Threshold Voff 2 Both thresholds can be set via the block parameter dialog box Bi DigOUTPort Jay File Edit wiew Simulation Format Tools Help DEBES TE inf External EE de Test program digital output PTT pins 2 and 6 are set high when the block input signal
57. m_server_RXTX_formatted_noExt EE File Edit wiew Simulation Format Tools Help Dc Bleo t 2c o m RF made TX Receive 5 element s RF ibus 12 ee S Server address Oxe7efefe Channel 0 Client address 0xc2c2c2c2 e User channel 0 Data type uint8 Sane Sample rate 0 1 s Dee nis FreePortComms_RX Sample rate 0 1 s r Comms_Server RF mode RX top centre T leti EET Client 1 double top right Server address xe7e7e7e7 Client address Oxc2c2c2c2 double bottom right Sere ements e Data type uint8 gc E E Sample rate 0 1 s o HEP o double top left da double centre Display 100 FixedStepDiscrete Figure 4 32 Sample model RFComm_server_RXTX_formatted_noExt mdl FW 08 07 63 rtmc9s12 Target A Simulink Real Time Target for 9512 microcontrollers Figure 4 33 shows the client side of this model The model receives the 5 bytes on logical channel 0 and loops them back using logical channel 1 The first element of the received data is used to control the 7 segment display of the receiving MiniDragon board displaying either 0 or 1 The server model receives the returned data and also displays either 0 or 1 depending on the first element of the 5 incoming bytes This sample model thus demonstrates that both the server as well as the client can be used to send and receive at the same time WW RFC omm client RXTX formatted noExt Jae File Edit View Simulation Format Tools Help Dude gt
58. microcontrollers To ensure that the host model runs forever open the simulation parameters menu Simulation Simulation Parameters and change the Stop time to inf W test PC MEX File Edit wiew Simulation Format Tools Help 0 AS ail Transmit 1 elements Comm part CON Baudrate 115200 bps Channel O Constant Slider Data type single Gain sample rate 0 1 s FreePortlomms TX nde45 Figure 3 5 Simple test program Host model We are now ready to compile the target model and run it on the target hardware Re open the target model test mdl and select the menus ToolsReal Time Workshop gt Build Model this initiates the build process of the block diagram Alternatively the shortcut CTRL B can be used Notice When running rtmc9s12 Target for the first time the toolbox might generate a library of all real time modules supplied by The MathWorks lt MATLAB_ROOT gt Irtwclibsrc This may take a few moments Once compiled the real time library is copied to lt rimc9S12 TARGET ROOT gt rtwlib Subsequent build processes do not require the library to be rebuilt In the current release of the toolbox the precompiled version of this library is already included This allows the evaluation version of Metrowerks CodeWarrior HC12 special license to be used with the toolbox Previous versions required the full version of CodeWarrior mostly because the 32 files limitation of the evaluation version made it impossible to compile the
59. much data can be sent through a RFComms block at anyone time Using the formatted data transmission of the RFComms blocks each telegram has a size of 4 number of elements x element size bytes In this equation the number of elements defines the width of the block input whereas the element size is given by the width of each data type The following data types are supported type width single uint8 int8 uint16 int16 int32 int32 boolean A A Coo A This means that it should be possible to send up to 7 single precision numbers per transmission or 28 individual data bytes FW 08 07 55 rtmc9s12 Target A Simulink Real Time Target for 9512 microcontrollers The above model Figure 4 22 runs on a MiniDragon board The first of the 5 elements received on FreePort channel 0 serial communication interface SCIO is used to select one of two displays on 7 segment display of the board connected to port H All 5 elements here uint8 are sent via the wireless link to client number 1 using logical channel 0 Note that this channel number has nothing to do with the one used by the corresponding FreePort block The second FreePort channel 1 also connected to serial port SCIO receives 7 bytes uint8 and sends them to the same client via the wireless link Logical channel 1 is used for this transmission Again this channel number has nothing to do with the corresponding FreePort channel The
60. nd freePortSend see the test m file script freeport_test m i FreePortComm_TX_simple JE File Edit View Simulation Format Tools Help im As lu mw inf Marmal Transmit 5 elements Comm part CON Baudrate 115200 bps E Channel O Data type uinte sample rate 0 1 s FreePortComms TX User data 100s T 7 26 440 FixedStepDiscrete Figure 4 12 Sample model FreePortComm TX simple mdl host 4 7 2 Simple upload of data from the target The target model FreePortComm TX simple2 mdl and the corresponding host model FreePortComm RX simple2 mdl demonstrate the use of the FreePort communication blocks for data upload from the target to the host The target model reads the dip switches connected to port H PTH and uploads this information O or 1 to the host The optional target sided display block is only serviced when running in External Mode Figure 4 13 Figure 4 14 shows the corresponding host model Note that instead of using a host sided Simulink model the command freePortReceive could have been used This is often more convenient especially when the received data is to be processed further by an m file Command freePortReceive has the following syntax myData numElementsReceived freePortReceive 1 115200 0 5 2 1 This attempts to receive data via COM1 at 115200 bps using channel 0 The number of elements to be received is 5 and they are of type 2 uint8 O single 1 int8 2 uint8 3 i
61. ng feature It supports evaluation of simple fuzzy inference systems FIS As this has been implemented as a hardware feature of the microcontroller core the resulting fuzzy controller is generally very fast The toolbox provides a fuzzy control block which can be configured as a 1 to 3 input 1 output Mamdani FIS In our undergraduate laboratories we use the free MATLAB fuzzy toolbox FlouLib www listic univ savoie fr modules php name Content amp pa show amp acronym FlouLib developed at the Universite de Savoie Chambery Annecy France Laboratoire d Informatique Systemes Traitement de l Information et de la Connaissance LISTIC This toolbox provides a number of Simulink S Function blocks for fuzzy logic systems using Mamdani FIS as well as Takagi Sugeno FIS The membership functions used during fuzzification and defuzzification can be defined using simple text files The same holds for the rule base Figure 4 34 shows an example of a simple Proportional Derivative PD fuzzy controller for an inverted pendulum experiment As this controller sits in the feedback branch of the control loop the inputs have been placed on the right hand side whereas the outputs are on the left i single GameController Fuzzy PD 2x SepOutGain Controller fuzzy controller File Edit View Simulation Format Tools Help D oc amp LI 5 Normal v Theta1_error position Theta1dot_error e Theta2 error ctrl signal bd balance go24 factor Theta2dot
62. nnnnnnnininininines 47 4 7 3 Simultaneous upload and download of data between host and target 49 4 7 4 Download of unformatted data to the target sss 51 4 7 5 Upload and download of data via both ports SCIO and SCI 52 4 8 Wireless COMMUNICATIONS tisse cni visi ls 54 4 8 1 RP COMM SetVel cesse id e aia 54 4 8 2 A cu tet mds 59 4 8 3 Other REC Omnis mode Serraren as 62 L9 PEV CONT O A A ee SEEN pU ICM e EC a e LEE 65 FW 08 07 1 rtmc9s12 Target A Simulink Real Time Target for 9512 microcontrollers TANCE LOCKS TT 69 4 10 4 Output Compare mode OC 69 410 2 Input Capture modelar 71 Vl DIA ASA aia d d E e eM E E 72 4 1 1 Toggling a pin of PORTB in External Mode seeeeeeeeeeeeeesee 72 4 11 1 Toggling a pin of PORTB in standalone mode eeeeeeuueuee 73 Ald SSUmple SONGL TAN DE INCI an 73 443 Miscellaneous Sample Models E 75 415 Tie flA Sida E 75 ANS 2 A rudimentary robot CONTO A AAA 75 4 13 3 Band limited white noise generator esee PI 4 13 4 Generation of a chirp signal frequency wobbling ccccceeesssssssseeeeeeeeens 78 PPD CNG I b etc Y 79 Appendix A POSSIDIe things TO dO cec cb pt tti o t Pa eee eee as ici e 81 FW 08 07 2 rtmc9s12 Target A Simulink Real Time Target for 9512 microcontrollers
63. nt16 4 uint16 5 int32 6 uint32 7 boolean A blocking call is made to freePortReceive last call up parameter 1 blocking O non blocking i e the command only returns once some data has been received if the received data is not FW 08 07 AT rtmc9s12 Target A Simulink Real Time Target for 9512 microcontrollers destined for the chosen channel here 0 both return parameters are 0 when the received data is destined for the chosen channel numElementsReceived should match the expected number of elements here 5 and myData are the received data values The latter are of the expected type here single For examples of how to use command freePortReceive see the test m file scripts freeport test2 m freeport test3 m and freeport test4 m FreePortComm_T1X_simple 4 Jog File Edit wiew Simulation Format Tools Help 1 ce As E uU inf External E double Transmit 5 elementis Comm port SCID PTH Baudrate 115200 bps Pins 0 1 2 3 4 Channel 0 Data type uint amp Sample rate 0 1 s Digital input FreePortComms TX Display FixedStepDiscrete Figure 4 13 Sample model FreePortComm RX simple2 mdl target ii FreePortComm RX simple2 JE File Edit View Simulation Format Tools Help 1 cm Lj l inf Mama E Receive 5 elements Comm part COT Haudrate 115200 hps Channel O Data type uinta sample rate 0 1 s FreePortComms Re Display 100 T 31 086 860 Fi
64. o A Converter Sero motor PYM P id B 16 bit Pw clk A 16 bit Pulse pin PTP 3 Period 0 02 Sign pin PTH 4 Pulse pin PTP 1 Period 2 s Saturation 1 Saturation 100 Servo Motor Ph Pulse Width Modulation Figure 2 1 The blocks of rtmc9s12 Target Application examples of all blocks of the toolbox can be found in the examples directory of the toolbox Wherever a system includes communication blocks e g Freeport Send Receive or RF Communication Client Server the system comprises of a target model lt example name gt mdl as well as a host model example name PC mdl See chapter 4 for details about the provided examples FW 08 07 9 rtmc9s12 Target A Simulink Real Time Target for 9512 microcontrollers 2 2 1 User Communication blocks obsolete Previous releases of this toolbox included a pair of User Communication blocks Receive user data and Send user data These blocks provided a mechanism for simple communication between a target model running on the microcontroller and a separate host model running on the PC The user communication blocks had been integrated into the External Mode communication protocol User communication blocks therefore only worked in conjunction with the External Mode interface An advantage of this approach was that the second Serial Communications Interface SCI of the microcontroller remained unused and could therefore be used otherwise A disadvantage was that the sending of user telegrams
65. om The executable code is generated from a regular MATLAB Simulink V7 4 R2007a model using Metowerks CodeWarrior V3 0 or later www metrowerks com Adaptations to other 9512 based development boards should be straight forward The author believes in the usefulness of free software rtmc9s12 Target is thus released under the terms of the GNU Public License Agreement GPL The spirit of free software incorporates the users freedom to run copy distribute study change and improve the software Commercial developments based on rtmc9s12 Target are permitted within the limits of the GPL For further details please visit the GNU website or refer to www gnu org philosophy free sw html FW 08 07 5 rtmc9s12 Target A Simulink Real Time Target for 9512 microcontrollers 1 2 Background The idea for the development of an easy to use real time target for a microcontroller was born during the writing and delivery of a number of laboratory sessions for a graduate level Control Engineering class held at Glasgow Caledonian University Scotland between 1999 and 2001 It became apparent that students often find it difficult to make the link between the theoretic concepts taught in class and practical real world applications To address this problem a number of microcontroller based design exercises were introduced Working in small groups of 2 to 4 students the participants were asked to develop a microcontroller based mobile robot which could
66. original Simulink demonstration file This example has been included to validate the correct operation of rtmc9s12 Target with models of a slightly elevated complexity The model runs at a base sample rate of 50 Hz sample time 20 ms with an upload of log data every 100 ms Wf14 JE File Edit view Simulation Format Tools Help DG bs a E Stick Input in alpha rad Bewator Command deg Bevator Deflection d deg Nz Pilot g vertical Velocity w ft sec Vertical Gust wGust ft sec Pitch Rate q rad sec Rotary Gust qGust rad sec alpha rad Simulation parameters Solver ODE1 Euler gt 3 4 ms cycle time Fixed Step size 20 ms Use the External Mode Control panel to start stop this model trigger initially unarmed 100 Figure 4 45 Sample model f14 mdl 4 13 2 A rudimentary robot control The target model robot mdl together with its corresponding host model robot pc mdl provide a very basic remote control for a mobile robot The target model receives direction commands using user data channel 0 The two values are multiplied by a common factor speed which is sent to the robot using user channel 1 Many more sophisticated robot control systems can be devised The pair of models has simply been included to provide a simple starting point for further experiments In our laboratory we supply the robot with information about its own position thus allowing it to react to what it sees Co ordinates and in
67. radio module acts as server of the RF communication network RF channel 12 is used and the server and client addresses have been set to Oxe e e e and Oxc2c2c2c2c2 respectively Note that the model runs in normal mode as opposed to External mode once compiled it is not controlled by MATLAB anymore The data which is sent to this model through serial communication interface SCIO is generated by a small m file script which sends data through the COM1 serial port of the host computer rfComms server TX freePortO 5x2 test formatted m A set of 5 bytes uint8 data type 2 is sent using user channel 0 followed by a set of 7 bytes on user channel 1 Oo v test program RECOMM server IX ILreePortU 5x2 lormatted nobxtsmol i 0 while 1 myDbataL e bL o2 9 4 5 mybDataz a L z 3 05 5 7 disp sending mnumzstr myDatal T J J freePortsSengd l 115200 Ur 5 4 2 MyDatad disp sending numzstr myData2 L Ts freePortsenc l 115200 1y Ty 2 myDataZ SS gt I if i 2 1 0 end pause end disp never reached Figure 4 23 shows the block parameters of the rfComms Server block in transmit TX mode Note the similarity of this block and the FreePort block The only parameters which distinguish this block from the FreePort block are the radio frequency channel RF channel 0 127 the server address hexadecimal 4 bytes the client address hexadecimal 4 bytes and the number of clients
68. ragon 12 target C128 based and C32 based targets The latter have been provided to allow the toolbox to be used with inexpensive targets such as Wytec s Dragon Fly At the writing of this document neither of these two targets has been fully tested Option Memory model defines the memory layout of the generated runtime code Two settings are currently available Flash_flat and Flash_banked Most small control applications can make use of the efficient Flash flat model Memory model Flash_banked should only be used for applications with very large code requirements and or large sets of in lined parameters The Flash_flat memory model assumes a 16 bit linear address space 0 64 kByte RAM is located from 0x1000 Ox3FFF 12 kByte ROM exists in two blocks one from 0x4000 Ox7FFF 16 kByte the second from 0xC000 OxD7FF 6 kByte Note that the upper ROM block has been limited to the first 6 kByte This is only necessary when working with ROM resident system programs in the protected area of Flash The boards in our laboratory have been pre loaded with a self test program For further details about the protected Flash of the 9512 see www mecheng adelaide edu au robotics WWW_Devs Dragon12 Dragon12 htm Model Flash_banked produces target executables which use the memory banking mechanism of the 9512 to expand the address space beyond the 16 bit limit of 64 kByte The memory window resides at addresses 0x8000 OxBFFF The MC9512 can
69. rate of 20 values per seconds sample time 0 05 seconds Figure 3 12 shows the modified target block diagram FW 08 07 34 rtmc9s12 Target A Simulink Real Time Target for 9512 microcontrollers Bitest mE File Edit View Simulation Format Tools Help 1 m amp En i External Et Receive 1 elementis Comm part SCIL Haudrate 115200 bps Channel 0 Data type single Display sample rate 0 2 s FreePornlomms Rx gt Pulse Gain Zero Order Scope Generator Hold Figure 3 12 Modified target block diagram Reduced upload rate In addition to the reduced upload rate we can also slim line the target code by eliminating the unnecessary continuous time solver algorithm Our block diagram does not include any dynamic blocks which would require numeric integration Therefore there is no need to include an ordinary differential equation ODE solver algorithm We can thus choose the solver setting discrete no continuous time states This is done on the Solver page of the Configuration Parameters dialog CTRL E see Figure 3 13 Save the block diagram and re build the target code CTRL B Once downloaded to the target the executable is automatically started Connect to the target and run the model code The scope block should still display a symmetric pulse train with a period of 2 seconds and a 50 duty cycle However the upload rate has been reduced by a factor 10 Upload rate considerations are very important when more th
70. reaches a level of 3 5 Volts The pins are reset when the signal level falls below 1 5 Volts Both threshold values can be set on the fly m the block parameters matching both values suppresses the hysteresis PIT Pins 2 6 Constant Slider Gain Digital output Display 100 odel Figure 4 5 Sample model DigOUTPort mdl 4 5 Pulse Width Modulation PWM Model PWM mdl produces a host driven pulse width modulated signal with a period of 100 ms In conjunction with a suitable amplifier e g a H bridge amplifier stepper motor driver the PWM module can be used to implement a large variety of drive systems DC motors servo motors stepper motors etc Forward reverse information is derived from the polarity of the block input signal and can be accessed on the configured sign pin The example uses PORTB pin 1 to display the sign information Port PTP is connected to the PWM unit of the microcontroller Each channel has been assigned a pin of port PTP Channel O corresponds to PTP O channel 1 is PTP 1 and so on A cascaded 16 bit PWM channel ties up two 8 bit units The generated pulse train can then be read from the upper of the two associated pins i e PTP 1 for cascaded unit O amp 1 PTP 3 for cascaded unit 2 amp 3 etc Block inputs above the Saturation level here 5 are clipped and result in a 100 duty cycle The optional block output has been enabled Signal monitoring However it should be noted that this
71. reas Figure 4 20 shows the host sided equivalent Notice that this requires the External Mode interface to be disabled no background monitoring Ml FreePortComm_RXTX_noExt Ja ES File Edit View Simulation Format Tools Help D AS Receive 5 elementis Comm port SCI1 Baudrate 115200 bps Channel 0 Data type uinte EET Sample rate 0 1 5 double FreePortComms RX Digital output Transmit 2 elementis Comm part SCIU Haudrate 115200 bps Channel 1 Data type inta sample rate 0 1 s FreePortlomms TX User data FixedStepDiscrete Figure 4 19 Sample model FreePortComm_RXTX_noExt mdl target FW 08 07 52 rtmc9s12 Target A Simulink Real Time Target for 9512 microcontrollers ii FreePortComm_TXRX_noExt JE File Edit View Simulation Format Tools Help a As lu mw inf Marmal Transmit 5 elementis Comm port Co Haudrate 115200 bps cM Channel D Data type uint User data sample rate 0 1 s FreePornlomms TX Receive 7 elementis Comm port COT Baudrate 115200 bps Channel 1 Data type int sample rate 0 1 s FreePorlomms RA Display 1 anra T 58468 120 FixedStepDiscreke Figure 4 20 Sample model FreePortComm_TXRX_noExt mdl host Remarks 1 When using simultaneous upload and download it is important to start the host model first then the target model This is because the S Function underlying the host sided FreePortComms RX block flushes the reception buffer when it is start
72. rnal Mode The label Normal shown in the toolbar of the model see Figure 3 2 should have changed to External On the second target specific options page deselect the Timing signals check box as well as the Run upon reset check box Configure the target to use RTI as the main timing engine Besides these code generation options we also have to choose an appropriate base sample rate for our model Click on the Solver entry on the left hand side of the Configuration Parameter dialog box and change the solver type from Variable step to Fixed step Select a step size of 5 ms 0 005 This defines the base sample rate at which we intend to run the target program Care should be taken when choosing this value Too small a base sample time might lead to problems as the model has not enough time to execute before the next sample time hit occurs ISR overrun error 1 Sample times of less than 1 ms are not recommended Change the parameter Mode from its default value Auto to Single Tasking This option instructs Real Time Workshop to build code for a single tasking environment Please note that our target model has to perform two jobs namely the generation of the pulse train continuous time and the checking for new user data every 200 ms discrete time Real Time Workshop can service these two jobs from within the base sample rate task single tasking or as two individual tasks multi tasking Please note however that the latter approach
73. robot Using a simple MATLAB based robot simulator the students developed code to process frames from a camera simulated stream of camera images to detect position and orientation of the robot This information was then sent to the robots using the wireless RF links On the robot the current distance to the target was worked out as well as the misalignment of the current orientation vector and a vector from the current location of the robot to the target These two inputs were then fed to a fuzzy controller in charge of steering the robot around the workspace The latter had been tuned using the simulator As the simulator uses the very same algorithms and controller settings as the real application the commonly big step from simulation to application was rather straight forward Figure 4 37 shows the simulator used in conjunction with this exercise FW 08 07 67 rtmc9s12 Target A Simulink Real Time Target for 9512 microcontrollers z Fuzzy 7ilo File Edit View Simulation Format Tools Help Dae S Xl T Test program Fuzzy Controller MSF s inputd x1 zita t MSF s input 2 xZ 2i1 ott MSF Ss output v zZiTao t t Rule base rb ZiTa t t Output fuzzy controller Input 2 100 FixedStepDiscrete Al Figure 4 36 Testing a fuzzy controller on the target Figure 1 Robot simulation 1200 1000 em es S 600 gt gt 400 200 200 400 600 800 1000 1200 1400 1600 x position EE nem A aa
74. rtmc9s12 Target A Simulink target for real time control using Freescale 9812 microcontrollers testBClRobot3g ext MEE Cla S X SB RSP om Normal et gt Ir ae Velocity right myGaled Pulse Train s leri gare Velocity left Motor Enable Pin testBCIRobot3g_ext Command RX File Edit View Simulation Format Tools Help Dh sae kE Ese a Noma a Bo BRE Lanu Cr er Had RF chanel 12 Cleiti Se ner address 0we7e7e7e7 Cliertaddress Oncacacac2 do not drive this using a terminal program code la e peer to Time offset 0 vend raw num bers not ascll fled Display FixedStepDiscrete Compiler suite Metrowerks CodeWarrior Manual V 2 1 Frank W rnle August 2007 rtmc9s12 Target A Simulink Real Time Target for 9512 microcontrollers 1 Contents Introduchion and Backeround 53 119 9220 09 2 9 CE Er Hd EUN TE ed Ead EE EA OPEP RE HELM TRO QU 4 DP TO AAA ID I me e dut 4 123 BACA E 6 The Simulink real time target rtmc9s12 Target ecce eee e eere eere eene ane 8 a NS SAA AAA tell dI MI LM d AAN e 2 1 1 Installing ne 981 227 APC CL tt 8 2 1 2 ovstem Ncap SPACe seems dob oo toD Im Ite i Maia eee 8 221 3 Micratine models trom R 13 1 to RI dor RI he ems 8 22 The TNC OST TV RS CELO COS Cd A dt e MU e 9 22 User Communication blocks obsolete oooooooononnnncnnnnnnnnnnnnnnnnnnnnnnnnanonos 10 2 22 FreePort communicat
75. rtmc9s12 Target contributes 14 new blocks Figure 2 1 A to D converter Digital input Digital output D to A converter On board D to A converter Dragon 12 Rev E Pulse Width Modulation PWM Servo motor PWM FreePortComms RX FreePortComms TX RF communications client RF communications Server Sonar range finder Timer and a Fuzzy controller block WW Library mc 951 tool ole File Edit View Format Help Freescale MC9512 real time control library RF mode Rx RF mode TX RF channel 12 RF channel 12 Client 1 Client 1 Receive 2 elementis Transmit 2 elementis Server address xe Terera7 Server address xe efere Comm part SCID Comm port Scio Client address Oxc2c2c2c2 p Client address Oxc2c2c2c2 Baudrate 115200 bps Baudrate 115200 bps User channel User channel 0 Channel 0 i Channel 0 Elements 1 Elements 5 Data type uint Data type uint Data type uinte Data type uinta Sample rate 0 1 s Sample rate 0 1 s sample rate 0 1 s Sample rate 0 1 FreePortComms Rx FreePortCoamms TX rcCamms Client r camms Server i FTT Output Channel 3 Fins 0 1 2 Input Period 0 3 Digital Output PTT Pin 1 Resolution 5 33338 006 Digital Input Sonar Range Finder Timer Unit ADC Input L DACO Channel 2 Vsat 5 MSFsinput 1 x1 3ila txt Ato D Converter D ta A Converter MSPs input 2 x2 3ilao bd MSFs input 3 x3 311 ott MSFs output v 3i1o t DACO Rule base rb 3i1a t t Vsat 5 Fuzzy Controller On board D t
76. s need to be unsigned numbers The block mask allows the following parameters to be set Figure 2 6 Sample time Resolution PWM period Pulse pin Minimum Pulse Width Maximum Pulse Width and Saturation input level The sample time defines the rate at which the block is updated The PWM period is the period of the generated PWM signal This parameter is limited by the maximum period of the PWM timer 179 seconds Minimum and maximum pulse widths define the limits of the servo motor Typical values range from 0 5 ms to 2 5 ms A duty cycle of 0 will produce pulses with the minimum pulse width a duty cycle of 10096 will generate pulses with the maximum pulse width FW 08 07 14 rtmc9s12 Target A Simulink Real Time Target for 9512 microcontrollers The pulse pin defines on which pin of port PTP the PWM signal should be displayed The Saturation input level defines the magnitude of the block input signal beyond which the PWM output signal has a duty cycle of 100 Ta Sink Block Parameters Servo Motor PWM Subsystern mask Parameters Sample time 0 02 Pi pernod 15 bit up to 179 s 0 02 Minimum pulse width 0 0006 hd aximum pulse width 0 0020 Resolution 16 bit Pulse pin PTP 1 B bit 16 bit Saturation input level simulated voltage 1 Figure 2 6 Parameters of the block Servo Motor Pulse Width Modulation 2 2 6 Digital input All available digital inputs of the MC9S12 can be accessed using
77. s the state of sign bit this feature has not been implemented on the 9512 The monitoring output can be enabled or disabled using a check box in the block parameter page Figure 4 10 lox amp Ello 9 dastr mig a Br 05 Time offsek 625 Figure 4 9 Pulse width modulation monitoring the generated PWM signals Ta Function Block Parameters Pulse width modulation Subsystem mask Parameters Sample time 0 01 Resolution 16 bit Pi period 8 bit up to 0 699 e 16 bit up to 179 3 0 5 Pulse pin PTF 1 8 bit 16 bit Sign port PTH Sign pin 1 Saturation input level simulated voltage 5 Signal monitoring Figure 4 10 Block parameter page Pulse width modulation FW 08 07 45 rtmc9s12 Target A Simulink Real Time Target for 9512 microcontrollers 4 7 FreePort communications 4 7 1 Simple download of data to the target The target model FreePortComm RX simple mdl and the corresponding host model FreePortComm_TX_simple mdl demonstrate the use of the FreePort communication blocks for data download from the host to the target The FreePort communication interface does not rely on the External Mode and can therefore be used with small standalone programs as well as in parallel with optional External Mode communications via the other port The sample target model receives 5 values on its SCIO port and feeds these values to an output block for PTH The latter block has been conf
78. server TX counter formatted_noExt mdl Figure 4 31 implements a simple counter 0 to 3 which controls the on board 7 segment display of the MiniDragon board Data values are transmitted to a single client using formatted data telegrams logical channel 0 1 element of type uint8 The model runs in normal mode no External mode FW 08 07 62 rtmc9s12 Target A Simulink Real Time Target for 9512 microcontrollers w RFComm server TX counter formatted noExt Jim E File Edit View Simulation Format Tools Help D cde Bleo t 2 AS RF mode TX RF channel 12 Client 1 Server address Oxe7e 7efe7 Soubise Client address 0xc2c2c2c2 User channel 0 Counter Elements 1 Data type uint8 Sample rate 0 1 s fComms_Server 0 3 L double a i double top centre double top right double 3 i double bottom right o double bottom centre 1 LI double 3 double 3 p a 3 double top left double centre Display 100 FixedStepDiscrete Figure 4 31 Sample model RFComm server TX counter formatted noExt mdl Whenever a sample model receives data from the host the name includes freeport An example is RFComm server RXTX formatted noExt mdl with client model RFComm client RXTX formatted noExt mdl Figure 4 32 shows the server end of affairs This model receives 5 elements of type uint8 from serial port SCIO and sends them via the RF link to the client formatted transmission RFCom
79. signals can be measured using a scope probe A typical trace of both timing signals as well as the activity on the serial reception line is shown in Figure 2 15 FW 08 07 22 rtmc9s12 Target A Simulink Real Time Target for 9512 microcontrollers 1 v e P yrwwRVrFFFFFENY Q o 2 9 O o 7 2 4353 O0 06 0 P wr ee s e o 4 in Ko 5 DAC Jiolo LITO NL 0000 14 1 r 9o Dooo Y a O mi 34 i ADJ qA ZS V S60R LED TE ooooS9 YO pra BUF wer a 0 Q O 0 Q O o O SEO RES e PH 1 0 BUF oef a OS Ca E EM JE 1 Ma pd T j ial pio a 2 af r LO 3 NCAA SE l m e he RNE gt nO pits T POS TO AAA ee 9 i ta rs 2 US xL 32 ENT DRAGONI 2 EU D mx 1 IRRX C32 Figure 2 14 Accessing the timing signals on the Dragon 12 Figure 2 15 Cycle time top and serial reception RxD bottom In addition to the timing signals the second option page also allows definition of the target behaviour following a reset run directly or wait for external mode connection Furthermore the main timing engine can be configured to run of the Real Time Interrupt RTI or of timer channel TC7 The latter commonly achieves a slightly more accurate match between the specified and the actually achieved sample rate However in some cases it might be advantageous to keep the timer unit free In this case the RTI offers an independent time base In the majority of cases the choice o
80. splay for error messages mc8s12 code gener mc3 12 code gener en megel 2 code gener Figure 2 16 Category mc9S12 code generation options cont FW 08 07 24 rtmc9s12 Target A Simulink Real Time Target for 9512 microcontrollers 3 Building a simple model A mini tutorial The following example gives an outline of the build process of a simple target model with FreePort communication Let us begin by creating a new Simulink model From the main menu of MATLAB create a new Simulink model File gt New gt Model and save this empty model as test mal Open the library browser Upon successful installation you should find a new toolbox entry called Real Time mc9S12 Toolbox Click on the next to this entry to expand its contents Figure 3 1 Drag the block FreePortComms RX to the still empty model window test From the sources category of the main library Simulink Sources select the block Pulse Generator and place it in your model Similarly from the sinks category Simulink gt Sinks choose a Scope block as well as a Display block Link the output of the Pulse Generator to the input of the Scope block and the output of the FreePortComms_RX block to the input of the Display block Your model should look as shown in Figure 3 2 Double click on the Pulse Generator block to display its parameters The default settings are a period of 2 seconds a duty cycle of 50 amplitude of 1 unit and the start
81. strate the download of raw data from the host to the target using the FreePort communication blocks Figure 4 17 is the target sided model whereas Figure 4 18 shows the host sided equivalent A similar pair of block diagrams can be designed for the upload of raw data from the target microcontroller to the host E FreePortComm EX simple3 Bax File Edit wiew Simulation Format Tools Help 1 As E G inf External E Receive 5 elementis Comm port SCIL Haudrate 115200 bps Channel Data type uinte sample rate 0 1 s FreePortComms Rx Display 100 FixedStepDiscrete Figure 4 17 Sample model FreePortComm_RX_simple3 mdl target E FreePortComm_TX_simple3 ole File Edit View Simulation Format Tools Help im Ll lu m inf Normal Transmit 5 elements Comm part CON Baudrate 115200 bps Data type uinte sample rate 0 1 s FreePortCormms TX Liser data 100 T 79444 440 FixedStepDiscrete Figure 4 18 Sample model FreePortComm TX simple3 mdl host FW 08 07 51 rtmc9s12 Target A Simulink Real Time Target for 9512 microcontrollers 4 7 5 Upload and download of data via both ports SCIO and SCI1 The target model FreePortComm RXTX noExt mdl and the corresponding host model FreePortComm TXRX noExt mdl demonstrate the download of data from the host to the target using the link from COM2 to SCI1 while simultaneously using the link from SCIO to COM1 for data upload Figure 4 19 is the target sided model whe
82. t block It is thus possible to use one and the same RF channel 0 127 for up to 10 separate logical channels FW 08 07 54 rtmc9s12 Target A Simulink Real Time Target for 9512 microcontrollers RFComm server TX freePortO 5x2 formatted noExt File Edit View Simulation Format Tools Help D oca Receive 5 element s Comm port SCIO Baudrate 115200 bps Channel 0 Data type uint8 Sample rate 0 1 s FreePortComms_RxX 5 Receive 7 element s Comm port SCIO Baudrate 115200 bps Channel 1 Data type uint8 Sample rate 0 1 s FreePortComms RX1 m wma cz mi e y wt 0 1 N double L double T zB o Selector double double double double double double double double OE b m RF mode TX RF channel 12 Client 1 Server address xe7e7eT7e 7 Client address 0xc2c2c2c2 User channel O Elements 5 Data type uint8 Sample rate 0 1 s r Comms Server top centre top right bottorn right bottom centre bottom left top left centre dot Display RF mode TX RF channel 12 Client 1 Server address Oxe7efe 7e Client address Oxc2c2c2c2 User channel 1 Elements 7 Data type uint8 Sample rate 0 1 s fComms_Servert FixedStepDiscrete Figure 4 22 Sample model RFComm_server_TX_freePortO_5x2_formatted_noExt Note that the underlying code currently limits the maximum number of bytes to be sent in any RF transmission to 32 This has implications on how
83. t platform e g the Dragon 12 this simple test program will generate a periodic square wave signal with a 2 seconds period and a duty cycle of 50 FreePort telegrams can be downloaded at a maximum rate of 5 Hz 200 ms and will be displayed on the Display block of the block diagram However before the target can receive any FreePort telegrams we first have to design a corresponding host model A host model is only required when the target model includes any of the FreePort communication blocks Note that the host based communication partner can also be an m file Create a new model and save it as test PC mdl From the mc9512 library we need the user communication block FreePortComms TX From the Sources category of the Simulink library Simulink Sources select the block Constant and place it in your host model Open the Math category of the Simulink library Simulink Math and find the block S ider gain Drag this block to the host block diagram and connect all three blocks as shown in Figure 3 5 Open the block FreePortComms TX and choose to all parameters to match those of the reception side i e channel 0 1 element of type single The sample time can be set to O seconds continuous this ensures that the host transmits new user data as soon as it decides to update this block However when used on the host the parameter Sample time is often rather meaningless FW 08 07 29 rtmc9s12 Target A Simulink Real Time Target for 9512
84. that we are currently bombarding the host with a lot of unnecessary data to represent the 2 second square wave an upload rate of say 10 to 20 times a second would have been sufficient At the moment the target uploads a new time stamp and data value every 5 ms i e 200 times a second Noting that with the overhead introduced by the External Mode protocol 32 bytes per point this results in a data flow rate of 6 400 byte per second Seen that the serial transmission of a single byte requires the sending of a 10 bit word start bit 8 data bits stop bit no parity this means that we are working with a data rate of at least 64 kBit per second this is more than half the available bandwidth 115200 bps Every additional data packet such as response packets to the download of a new parameter set e g a new slider gain value will have to be transmitted in between It is therefore advisable to reduce the log data upload rate to the minimum required for a particular application In our case the displaying of a 2 seconds square wave signal does not require an upload of more than 20 values per period To reduce the volume of log data use the Zero Order Hold ZOH block These blocks achieve a down sampling from a high rate to a lower rate From the Simulink library category Discrete drag a ZOH into the target model block diagram Insert this block into the signal path between Pulse Generator and Scope block Open the ZOH and choose an upload
85. the model recommended minimum 1 ms This approach is thus only useful when the overall rate of the output signal is rather low Hz region The timer unit provides a good solution to the above dilemma Each of its 8 channels can be configured for signal production with rates up to 10 MHz 100 ns faster rates are possible but not recommended The nominal resolution of each channel is 16 bit However as the timer unit has a single central clock generator the actual resolution of each individual timer channel is limited by the dynamic range of all channels i e by the ratio of fastest sample rate to slowest sample rate To understand this recall that the slowest rate determines the prescale value of the timer unit the maximum period is achieved when counting at the chosen rate fime from O to 2 1 65535 This defines the smallest achievable time step timer tick to 1 ftimer Faster channels have shorter periods we now count up to values less than 65535 yet their period is still determined by the overall timer tick 1 ftimer This can lead to a rather poor accuracy of the programmed period e g when trying to program a 100 ns period with a smallest step of around 5 us 5000 ns Furthermore the block input of the timer in OC mode defines the percentage of the full period as specified in the block parameters A block input of 1 causes the timer to produce a square wave signal with twice the requested period on the assoc
86. the time a host driven flow control has been implemented Typically problems can occur when a user decides to launch a new application to move or resize a window to open a menu etc Any of these events can interrupt the regular upload of log data for an unspecified duration rtmc9s12 Target takes care of this uncertainty by timeout counters and the acknowledgement of each data packet The target thus stops sending log data when the host is busy regular operation resumes as soon as Simulink continues to operate normally 2 The Cancel Arm trigger button as well as the disconnecting from a running target have been found to be a bit flaky Their use is therefore discouraged FW 08 07 38 rtmc9s12 Target A Simulink Real Time Target for 9512 microcontrollers 4 The example models A set of sample models has been included to facilitate familiarisation with this toolbox They can all be found in the examples directory 4 1 AD 9 12 mdl The model AD 9512 mdl implements a 3 channel A D Conversion with real time data logging A D channels 2 3 and 4 are read and converted every 2 ms Data upload is performed every 20 ms As can be seen from the status bar Figure 4 1 the model has been configured to use an ODE solver ODE1 Euler method Note that this is not really necessary here as the model does not feature any continuous states iW AD 9512 Mix File Edit wiew Simulation Format Tools Help 0 cag Real time data acquisition with t
87. time 0 Close the parameter control window without making any changes Open the FreePortComms RX parameter page by double clicking the corresponding block icon The default parameters are a sample time of 0 1 seconds 100 ms SCIO 115 2 kBit s channel number 0 2 bytes UINT8 to be received and block output is double Change the sample time to 0 2 seconds the FreePort communication interface to SCI the number of elements to 1 and set the signal data type to SINGLE then close the dialog box FW 08 07 25 rtmc9s12 Target A Simulink Real Time Target for 9512 microcontrollers Ta Simulink Library Browser File Edit View Help O gt d to D Converter mc3s1z2taol A to D Converter liii Simulink ape npt 2 Commonly Used Blocks LLL Continuous E t Discontinuities vat D to A Converter 3 Discrete ua Logic and Bit Operations 27 Lookup Tables Math Operations 2 Model Verification 2 Model Wide Utilities H Ports amp Subsystems Signal Attributes Signal Routing 2 Sinks Sources 3 User Defined Functions 2 Additional Math amp Discrete ais On board D ta 4 Converter lp Aerospace Blockset lo Control System Toolbox lii Data Acquisition Toolbox MM Gauges Blockset li Real Time Workshop lio Real Time Workshop Embedded Code liy Real Time mc9512 Toolbox lis Robust Control Toolbox ur Signal Processing Blockset dr Simscape By Simulink Control Design lig Simulink Extras lg Stateflow hl Seectem THenri
88. tion mas output 5 Sample time 0 01 Figure 2 4 Parameters of the block ADC Input 2 2 4 Pulse Width Modulation unit PWM Pulse width modulated PWM signals can be generated using the Pulse Width Modulation block The current version of rtmc9s12 Target offers 4 to 8 PWM channels depending on the resolution of each individual channel The unit can be configured for up to 4 16 bit PWM channels or up to 8 8 bit channels Block inputs can be signed numbers The sign information is removed and presented on a programmable sign pin The block mask allows the following parameters to be set Figure 2 5 Sample time Resolution PWM period Pulse pin Sign port Sign pin Saturation input level and an optional monitoring output The sample time defines the rate at which the block is updated The PWM period is the period of the created PWM signal This parameter is limited by the maximum period of the PWM timer 179 seconds Pulse pin Sign port and Sign pin allow the output pins to be chosen on which display the PWM signal should be displayed The pulse port is fixed PTP The sign bit is high 5 V for negative signals and low 0 V for positive inputs The Saturation input level defines the magnitude of the block input signal beyond which the PWM output signal has a duty cycle of 100 Note that channels 0 1 4 and 5 run of PWM clock source A whereas channels 2 3 6 and 7 run of PWM clock source B This means that the ach
89. to be serviced 1 5 FW 08 07 56 rtmc9s12 Target A Simulink Real Time Target for 9512 microcontrollers Ww Sink Block Parameters rfComms Server Subsystem mask Parameters Sample time 0 1 Communication mode Ts RS Transmission T HF channel number U 127 12 Client to transmit to 1 Server address 4 bytes hexadecimal notation e g xeere e Une ve refe Client address 4 bytes hexadecimal notation e g Uacececece Uececececs User channel number 0 3 0 Humber of elements to be sentrecelved 5 Data Type UINTS Block sends receives raw data Figure 4 23 Block parameters of block rfComms Server The Server and client addresses can be chosen feely they simply have to match on all communication partners server clients Using more than one set of RF modules in the same area requires each communication network to be run on a different RF channel This is for instance important when multiple mobile robot experiments are to be run simultaneously within the same laboratory Assigning a different RF channel to each group allows for up to 128 parallel communication networks more than enough for most applications of this toolbox Figure 4 24 shows an example of a multi robot configuration we used during experiments in our laboratory The two robots on the right hand side of the image are transmitters on channel 12 and 13 respectively The robot in the middle is client 1 of the channe
90. ulates a linear PD controller Once a FlouLib simulation works satisfactorily the fuzzy controller files definition of the input and output MSFs rule base can directly be used with the fuzzy block of rtmc9s12 Target Simply enter the filenames in the corresponding edit boxes of the block parameter window Figure 4 35 FW 08 07 66 rtmc9s12 Target A Simulink Real Time Target for 9512 microcontrollers WW Function Block Parameters fuzzy controller Subsystem mask Parameters Number of inputs 3 MSFs input 1 filename 4 alo bet MSF es input 2 filename 2 Lo bt MSFe input 3 filename amp 3 1 0 bt MSF output filename Wo bet Rule base filename rb Silo bet Sample time 0 1 Figure 4 35 Using FlouLib definition files with the rtmc9s12 Target fuzzy block The toolbox uses the settings found in the input output and rule base files to generate a customized assembler code fuzzy engine This source code file is then added to the list of files to be compiled into the target To the user all of this is fully transparent Simply specify the required definition files and compile the model Figure 4 36 shows a sample model which can be used to validate the correct operation of a fuzzy controller The fuzzy block allows for interesting lab exercises In our laboratory we ran a small mobile robot exercise in which the students were asked to design a fuzzy controlled automatic parking system for a small mobile
91. xedStepDiscrete Figure 4 14 Sample model FreePortComm TX simple2 mdl target FW 08 07 48 rtmc9s12 Target A Simulink Real Time Target for 9512 microcontrollers 4 7 3 Simultaneous upload and download of data between host and target The target model FreePortComm RXTX mdl and the corresponding host model FreePortComm_TXRX mdl demonstrate the simultaneous upload and download between host and target using the FreePort communication blocks Figure 4 15 is the target sided model whereas Figure 4 16 shows the host sided equivalent i FreePortComm_RXTX Ja File Edit View Simulation Format Tools Help D c hs E inf Externi Receive 5 elementis Comm part SCI Baudrate 115200 bps Channel D Data type uinta sample rate 0 1 s FreePorlomims Ra Display 1 1 Receive 7 elementis Comm port SCIU Baudrate 115200 bps Channel 1 Data type single Sample rate 0 1 s FreePornlomms R1 Display Transmit 2 elementis Comm port 510 Baudrate 115200 bps Channel 3 Data type ints sample rate 0 1 s FreePortlomms TX Liser data 100 FixedStepDiscrete Figure 4 15 Sample model FreePortComm_RXTX mdl target FW 08 07 49 rtmc9s12 Target A Simulink Real Time Target for 9512 microcontrollers Wi FreePortC omm TARX e JJ E3 File Edit View Simulation Format Tools Help 1 im m em ll m inf Normal Transmit 5 element s Comm part COT Haudrate 115200 bps Data type uinta User data Sample rate 0 1 s
92. ytes uint8 is transmitted No additional overhead such as the channel number the data type byte etc are sent This is useful when interfacing the microcontroller to FW 08 07 11 rtmc9s12 Target A Simulink Real Time Target for 9512 microcontrollers intelligent sensors which provide measurements and other information in form of a stream of serial data bytes Selecting the raw data tick box causes the block mask to change to the reduced format shown in Figure 2 3 Ta Sink Block Parameters FreePortComms TX Subsystem mask Parameters Sample time 0 1 Communication port SCID Baudrate 175200 Humber of elements 2 Block sends raw data Figure 2 3 Raw data mode reduced parameter set 2 2 3 A D Converter unit ADC The A D converter unit of the MC9S12 can be accessed using the target block ADC Input This block has five parameters The ADC unit of the microcontroller ATDO ATD1 the range of channels to be converted 0 7 the resolution of the ADC 8 bit 10 bit the output format raw data normalized to 0 1 normalized to 0 5 and the sample time at which the block is to be updated Figure 2 4 shows the parameter requester of the ADC Input block FW 08 07 12 rtmc9s12 Target A Simulink Real Time Target for 9512 microcontrollers Ta Source Block Parameters to D Converter Subsystem mask Parameters ADC bank O Channels 0 7 2 ADC resolution 10 bits Mormaliza
Download Pdf Manuals
Related Search
Related Contents
ADSLモデム-MS5取扱説明書 Leica_LP-C_software-Manual_1v0_es N5072Speed Dome Network Camera 2.5 - Pittsburgh Supercomputing Center Staff Directory Home Decorators Collection 0561000930 Installation Guide XQG90-HR1214S User Manual B D S 2 8 0 / B D S 5 8 0 Carregar folheto (pt) 教育厚生委員会会議録 Copyright © All rights reserved.
Failed to retrieve file