NXPモデルベース・デザイン・ツールナレッジベース

キャンセル
次の結果を表示 
表示  限定  | 次の代わりに検索 
もしかして: 

NXP Model-Based Design Tools Knowledge Base

ディスカッション

ソート順:
In this video we discuss about how to use Processor-in-the-Loop (PIL) approach to generate the C-code and to validate the algorithm on the real hardware.  PIL simulation main goals are: - to generate and execute the C-code on the real target/microprocessor; - to help with specific algorithm and control designs by offering the means to optimize your software; - to establish a testing framework for the production code; PIL simulation can also use some of peripherals from the real target for inputs or outputs, making the simulation environment more realistic and closed to the final SW design specifications.   We discuss about: - What is PIL, When to use it and What is recommended for;  - How to convert any Simulink generic algorithm to run with PIL support using the Model Based Design Toolbox; - PIL Reference models;  NOTE: Chinese viewers can watch the video on YOUKU using this link 注意:中国观众可以使用此链接观看YOUKU上的视频
記事全体を表示
This video shows how to program the ADC with Model Based Design Toolbox to obtain the speed reference for the BLDC speed closed loop control system. We discuss about: - How the ADC works - How to simulate the ADC operations - How to implement a simple program to read data from the ADC - How to use BAM to load the application into microprocessor memory - How to test in real time with FreeMaster - How to scale the Potentiometer voltage into a speed reference data that represents the rpm. - How to implement from scratch a Simulink model to cover the ADC functionality NOTE: Chinese viewers can watch the video on YOUKU using this link. 注意:中国观众可以使用此链接观看YOUKU上的视频
記事全体を表示
      Product Release Announcement Automotive Microcontrollers and Processors NXP Model-Based Design Toolbox for MPC57xx – version 3.1.0     Austin, Texas, USA December 16 th , 2019 The Automotive Microcontrollers and Processors Model-Based Design Tools Team at NXP Semiconductors, is pleased to announce the release of the Model-Based Design Toolbox for MPC57xx version 3.1.0. This release supports automatic code generation for peripherals and applications prototyping from MATLAB/Simulink for NXP’s MPC574xB/C/G/P and MPC5777C series.   FlexNet Location https://www.nxp.com/webapp/swlicensing/sso/downloadSoftware.sp?catid=MCTB-EX   Activation link https://www.nxp.com/webapp/swlicensing/sso/downloadSoftware.sp?catid=MCTB-EX   Release Content Automatic C code generation based on PA SDK 3.0.2RTM drivers from MATLAB®/Simulink® for NXP MPC574xB/C/G/P and MPC5777C derivatives: MPC5744B, MPC5745B, MPC5746B                                                   (*upd) MPC5744C, MPC5745C, MPC5746C, MPC5747C, MPC5748C         (*upd) MPC5746G, MPC5747G, MPC5748G                                                  (*upd) MPC5741P, MPC5742P, MPC5743P, MPC5744P                                (*upd) MPC5777C                                                                                            (*new) Added support for SIL, PIL and AUTOSAR Blockset code generation and simulation for the MPC5777C Ultra-Reliable MCU for Automotive and Industrial Engine Management. Currently only the basic enablement is available for this microcontroller as shown in the picture below: Enhance MATLAB/Simulink support to all versions starting with 2016a to 2019b Enable MATLAB AUTOSAR Blockset on all MPC574xB/C/G/P and MPC5777C to allow users to configure, simulate, generate and profile AUTOSAR Applications with NXP Hardware; For more details, features and how to use the new functionalities, please refer to the Release Notes and Quick Start Guide documents.   MATLAB® Integration The NXP Model-Based Design Toolbox extends the MATLAB® and Simulink® experience by allowing customers to evaluate and use NXP’s MPC57xx MCUs and evaluation boards solutions out-of-the-box with: NXP Support Package for MPC57xx Online Installer Guide Add-on allows users to install NXP solution directly from the Mathwork’s website or directly from MATLAB IDE. The Support Package provide a step-by-step guide for installation and verification. NXP’s Model-Based Design Toolbox for MPC57xx version 3.1.0 is fully integrated with MATLAB® environment in terms of installation, documentation, help and examples;     Target Audience This release (v.3.1.0) is intended for technology demonstration, evaluation purposes and prototyping for MPC574xB/C/G/P and MPC5777C MCUs and their corresponding Evaluation Boards: DEVKIT-MPC5744P PCB RevX1 SCH RevB DEVKIT-MPC5748G PCB RevA SCH RevB DEVKIT-MPC5777C-DEVB                                                                     (*new) Daughter Card MPC574XG-256DS RevB Daughter Card X-MPC574XG-324DS RevA Daughter Card MPC5744P-257DS RevB1 Daughter Card SPC5746CSK1MKU6 Daughter Card MPC5777C-516DS                                                        (*new) Daughter Card MPC5777C-416DS                                                        (*new) Motherboard X-MPC574XG-MB RevD Motherboard MPC57XX RevC      
記事全体を表示
This video shows the overall motor control application developed with Model Based Design Toolbox. We are going to assemble all the blocks developed throughout this course and we will have the motor running under Speed Controller supervision. We also discuss about the FreeMASTER and you can easily create nice control panels for the applications and how you can validate the Speed Controller and overall Motor Control application. We discuss about: - Speed Controller implementation in Simulink for real time systems; - Motor and Inverter protection for over-current, over- and under-voltage; - FreeMASTER control panel using HTML and Java Script; - Various tests on the MPC5744P DevKit and MotorGD DevKit;   NOTE: Chinese viewers can watch the video on YOUKU using this link 注意:中国观众可以使用此链接观看YOUKU上的视频
記事全体を表示
In this video we discuss about control system theory and the mathematics behind the speed controller designing process. We are going to analyse the control system stability based on poles and zeros location and then we will compute the PI speed controller gains using the Root Locus allocation method. For the cases where the system transfer function is unknown we are discussing Ziegler Nichols method for finding the controller gains and we are going to verify the control system designing process by simulating a BLDC motor behavior and building a PI speed controller to handle the system response. We discuss about: - How to choose the controller type based on system transfer function; - How to analyze system stability starting from the characteristic polynomial; - What are the gain, zeros and poles of closed loop transfer function; - Root Locus allocation method based on second order ideal model with dumping factor and natural frequency; - Ziegler Nichols tuning methods; - Simulink models for BLDC motor and PI Speed Controller NOTE: Chinese viewers can watch the video on YOUKU using this link 注意:中国观众可以使用此链接观看YOUKU上的视频
記事全体を表示
This video presents the hardware and software setup used for Motor Control Class. It shows: - MPC5744P DevKit main hardware features - MotorGD DevKit main hardware features - How to install the Model Based Design Toolbox for MPC5744P revision 2.0.0 - How to generate a license - How to setup a compiler toolchain using S32 Design Studio for Power Architecture - How to add the Model Based Design Toolbox for MPC5744P into the Simulink Standard Libraries - How to validate the software installation by generation C code for the first time NOTE: Chinese viewers can watch the video on YOUKU using this link. 注意:中国观众可以使用此链接观看YOUKU上的视频
記事全体を表示
General Installer and Setup  How to install the license of MBDT for S32K3?  How to setup the S32K344 toolbox and EVB?  How to export the generated code to S32DS3.4? Export generated projects in MBDT for s32k3XX  Programming methods MBDT for S32k3 using P&E Multilink Custom code usage SENT Protocol Support in S32K3 MBDT Custom project usage How to use custom project configuration Sequential reset S32K344-Q172 sequential reset SIL / PIL / External Mode External mode External mode example wouldn't compile after update  S32K3X4EVB-Q257 with MBDT PIL Example: Not able to run Simple PIL S32CT example Peripherals ADC How to add a new ADC channel using the external configuration tool  SPI How to send 32 bit frames  DIO S32K3x4-Q172P_with_MBDT_Blink_Project DIO and PWM configuration issues ICU PWM Duty cycle measurement PWM PWM raising edge and falling edge detection Interrupt based PWM generation CAN FreeMASTER over CAN connection issue  Apps Motor Control SPI configuration MODEL based design tool box- 32 bit instruction (SIMULINK) 
記事全体を表示
This video demonstrates how to: Wake up on time interrupt Read temperature via FlexIO interface Relay information to host PC via UART interface Go to sleep to preserve the power
記事全体を表示
Introduction The application is based on an example of basic GPIO for S32K144 (gpio_s32k14_mbd_rtw). The application is extended to fit the needs of motor control application running a sensorless PMSM Field Oriented Control algorithm. Therefore, certain modes (states) and transitions (events) are implemented. NOTE: Theory of Finite state machines defines states and events (transitions). Following design uses approach which may seem to mix states and transitions at some point. Some states are run just once, thus they may be considered as transitions only. However, the design is considered as an example and may be extended in terms of additional checks for external events, making these "one-shot" states the actual states. The design has been well known from NXP Automotive Motor Control Development Kits and it has been well accepted by majority of customers. Therefore, the same concept is presented for MATLAB Simulink. Finite State Machine Design The application structure should introduce a systematic tool to handle all the tasks of motor control as well as hardware protection in case of failure. Therefore, a finite state machine is designed to control the application states using MATLAB Simulink Stateflow Chart (Stateflow library/Chart). The motor control application requires at least two states - "stop" represented by "ready" state and "run" represented by "run" state. However, some additional states need to be implemented to cover e.g. power-on situation, where the program waits for various auxiliary systems (system basis chip, DC-bus to be fully charged, memory checks, etc.). In addition, the motor control application and specifically the sensorless field oriented control requires additional states to calibrate the sensors and to start the motor with known position. Therefore, transition from READY state to RUN state is done through an initialization sequence of CALIB (sensors calibration) and ALIGN (initial rotor position alignment or detection) states. To stop the motor, the application goes back to the READY state via INIT (state variables initialization). While the INIT state is designed to clear all the internal accumulators and other variables (but the parameters can be changed in the run time and not reset to the default settings), the RESET state is introduced to enable power-on or "default configuration" or "soft reset" initialization in the case of the motor control parameters are changed using FreeMASTER or other user interface. All the states are linked with an output event which is traced out of the state machine chart block. These events can be used as trigger points for calling the handlers (state functions). The transitions are driven by the input value of the state machine, treated as an event using a simple comparison (e.g. [u==e_start]). To change the state, the event/input value should be changed. If the event has changed, the state machine changes the state only in case of there is an existing action linked with the current state and the event. The state machine is designed to be used in the application using Event input (to signal the event), State output (to indicate the current state) and Event triggers outputs (to call the state functions / handlers). Following application has been built to show an example of the state machine usage. Following tables show the nomenclature of the states and events: State Purpose Value Reset Power-on / Default settings / Soft-reset state. May include some HW checking sequence or fault detection. 1 Init Initialization of control state variables (integrators, ramps, accumulators, variables, etc.). May include fault detection 2 Ready Stand-by state, ready to be switched-on. Includes fault detection, e.g. DC-bus overvoltage or high temperature 3 Calib Calibration state to calibrate ADC channels (remove offsets). Includes fault detection 4 Align Alignment state to find the rotor position and to prepare to start. Includes fault detection 5 Run Motor is running either in open-loop or sensorless mode. Includes fault detection 6 Fault Fault state to switch off the power converter and all the peripherals to a safe state. 7 Input events are the triggers which initiate a change of current state. Input Event Purpose Value e_init_done Asserted when the Init state has finished the task with success 1 e_start Asserted when a user sends the switch-on command 2 e_calib_done Asserted when all the required ADC channels are calibrated 3 e_align_done Asserted when the initial rotor alignment / position detection is done 4 e_stop Asserted when a user sends the switch-off command 5 e_fault Asserted when a fault situation occurs 6 e_fault_clear Asserted when a user sends the "clear faults" command or when the situation allows this 7 e_reset Asserted when a user sends the "reset" command to start over with default settings 8 Output events are used to trigger the Motor Control State Handlers and correspond to actual state. These events are triggered with every state machine call. Therefore, the state machine shall be aligned with the control algorithm. For example, it shall be placed within the ADC "conversion completed" interrupt routine or PWM reload interrupt routine. Finite State Machine Usage The state machine shall be used in good alignment with the control algorithm. The usual way of controlling a motor is to have a periodic interrupt linked with the ADC conversion completed or with the PWM reload event (interrupt). The state machine shall be called within this event handler, right after all the external information is collected (voltages, currents, binary inputs, etc.) to let the state machine decide, which state should be called next. Internal event/state handling inside of the state machine is clearly described by the state machine block definition. Output event triggers are configured to provide clear function-based code interface to the state machine. That means, the output events shall be connected to a function designed to handle the state task. For example, in Run state, the run() output event is triggered with every state machine call, while within the Run state function the whole motor control algorithm is called. If an input information is supposed to switch the state, a simple condition shall be programmed to change the Event variable (defined as a global variable). For example, if a user sends the "stop" command, the Event is set to "e_stop" and the state machine will switch to the Init state. For more complex triggering of output functions, additional output events can be programmed within the state machine definition. Template state handler function is based on the function caller block. In general, the function blocks can work with global variables, thus there is no need for inputs or outputs. Thanks to global Event variable, event-driven state machine can react on events thrown inside a state handler function or outside of the state machine (e.g. based on other asynchronous interrupt). An example of a simple template is shown below. In this example, the function represents the Reset state, which is supposed to be run after the power-on reset or to set all the variables to its default settings. Therefore, the first part is dedicated to hardware-related settings, the second part is covering the application-related settings. The third part checks whether all the tasks are done. If yes, the e_reset_done event is thrown (stored into the Event variable). In this case, the ResetStatus variable is obviously always going from zero to two with no additional influence. Therefore, the final condition may be removed (even by the MATLAB optimization process during compilation). If there is an external condition, such as a waiting for an external pin to be set, then it makes sense to use such "status" variable as a green light for completing the state task and throwing the "done" event. Embedded C code Implementation In default settings, MATLAB Embedded Coder generates the state machine code in a fashion of switch-case structure. This might be not very useful for further code debugging or for manual editing. Therefore, the function call subsystem block parameters should be changed as shown below. The function packaging option is set to "Nonreusable function", other settings might be left at default values. This will keep the state machine code structure in switch-case, however the state handlers function calls will be generated as static functions (instead of putting the code inside the switch-case). Following code sample is a part of the state machine code generated in the stateMachineTest.c example code. The state machine decides based on the State variable, which is internally stored in the stateMachineTest_DW.is_c1_stateMachineTest. Based on the stateMachineTest_DW.Event, a transition is initiated. Finally, the state handler function is called, in this case stateMachineTest_Resetstate(). void stateMachineTest_step(void) { /* ...  */       switch (stateMachineTest_DW.is_c1_stateMachineTest) { /* ... */       case stateMachineTest_IN_Reset:             rtb_y = 1U;             /* During 'Reset': '<S5>:35' */             if (stateMachineTest_DW.Event == stateMachineTest_e_reset_done) {               /* Transition: '<S5>:37' */               stateMachineTest_DW.is_c1_stateMachineTest = stateMachineTest_IN_Init;               /* Entry 'Init': '<S5>:1' */               rtb_y = 2U;             } else if (stateMachineTest_DW.Event == stateMachineTest_e_fault) {               /* Transition: '<S5>:46' */               stateMachineTest_DW.is_c1_stateMachineTest = stateMachineTest_IN_Fault;               /* Entry 'Fault': '<S5>:18' */               rtb_y = 7U;             } else {               /* Outputs for Function Call SubSystem: '<Root>/Reset state' */               /* Event: '<S5>:49' */               stateMachineTest_Resetstate();               /* End of Outputs for SubSystem: '<Root>/Reset state' */             }             break; /* ... */       }‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍ /* ... */ }‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍ The reset state function is compiled based on priorities set in each block of the Simulink model. If no priorities are set, the default ones are based on the order of adding them to the model. Therefore, it is very important to verify and eventually change the priorities as requested by its logical sequence. This setting can be changed in the block properties as shown below. The priority settings is shown after the model is updated (Ctrl+D) as a number in the upper right corner of each block. State Machine Test Application Testing application is designed to test all the features of the state machine, targeting the S32K144EVB. To indicate active states, RGB LED diode is used in combination with flashing frequency. On-board buttons SW2 and SW3 are used to control the application. The application is running in 10 ms interrupt routine (given by the sample time). There is an independent LPIT interrupt controlling the LED flashing. After the power-on reset, the device is configured and the RESET state is entered, where additional HW and application settings are performed. Then, the application runs into the INIT state with a simulated delay of approx. 2 seconds, indicated by the blue LED diode flashing fast. After the delay, the READY state is entered automatically. Both buttons are handled by another state machine, which detects short and long button press. While the short press is not directly indicated, the long press is indicated by the red LED diode switched on. By a short pressing of the SW2, the application is started, entering the CALIB state first, followed by the ALIGN state and finally entering the RUN state. The CALIB and ALIGN states are indicated by higher frequency flashing of the blue LED, while the RUN state is indicated by the green LED being switched on. The application introduces a simulation of the speed command, which can be changed by long pressing of the SW2 (up) or SW3 (down) within the range of 0 to 10,000. Moreover, to simulate a fault situation, the e_fault event is thrown once the speed command reaches value of 5,000. The FAULT state is entered, indicated by the red LED flashing. To clear the fault, both SW2 and SW3 should be pressed simultaneously. The INIT state is entered, indicated by the blue LED diode flashing fast. Following tables show the functions and LED indication. Button Press lenght Function SW2 short press Start the application SW2 long press Increase the speed command (indicated by the red LED diode ON) SW3 short press Stop the application SW3 long press Decrease the speed command (indicated by the red LED diode ON) SW2+SW3 short press Clear faults State LED Flashing Reset - Init Blue period 50 Ready Blue period 500 Calib Blue period 250 Align Blue period 100 Run Green always on Fault Red period 100 any Red always on when a long press of SW2 or SW3 is detected Running the example The example can be built and run along with the Model Based Design Toolbox for S32K14x, v3.0.0. This version has been created using MATLAB R2017a. Please follow the instructions and courses on the NXP Community page prior to running this example. Usage of the S32K144EVB with no connected extension boards is recommended, however this example doesn't use any HW interfaces except of (please refer to the S32K144EVB documentation): S32K144 pin S32K144EVB connector Usage PTD15 J2.2 GPIO output / strength: High / Red LED PTD0 J2.6 GPIO output / strength: High / Blue LED PTD16 J2.4 GPIO output / strength: High / Green LED PTC12 J2.10 GPIO input / Button SW2 PTC13 J2.12 GPIO input / Button SW3 PTC6 J4.4 UART1 / RxD / FreeMASTER PTC7 J4.2 UART1 / TxD / FreeMASTER The application works also with the FreeMASTER application. Users can connect to the target and watch or control the application. The FreeMASTER project is attached as well, however, the ELF file location needs to be updated in the FreeMASTER project settings after the application is built and run.
記事全体を表示
This article details the TPL communication setup between S32K1xx boards and MC3377xBTPL Battery Cell Controllers.  It covers both hardware and software setup for the Battery Management System models designed using Model-Based Design Toolbox for battery packs of more than 14 cells in series.  At the end of this article, the user will be able to setup the Battery Cell Controller hardware and to design a Simulink model that reads the cell and pack voltages, current, temperatures and faults status. The measured values will be displayed on the host PC using FreeMaster. 
記事全体を表示
  1. Introduction 1.1 A New Control Option For NXP Cup Race Car    NXP Cup car development kit is usually based on NXP's Freedom KL25Z board for motors control and image evaluation. However the control of the race car can be done with multiple NXP solutions.    In this article, a solution based on S32K144EVB board will be presented along with a programming approach based on MATLAB/Simulink Model-Based Design Toolbox for S32K. Additionally another tool provided by NXP - FreeMASTER - will be used to debug in real time the application.     As S32K144 pinout is not compatible with the default Landzo board pinout, an additional board to route the pins to the desired destination has been built. Complete details on the mapping of the pins are provided in the tutorial.   This article is structured as a tutorial detailing all the steps and providing all the source code to enable one to use this solution. However the control application is done very simple - on purpose - and uses just 10% of the speed to prove the concept.  Table 1. Freedom KL25Z vs. S32K144 features Freedom KL25Z Board Features S32K144 Board Features 32-bit ARM Cortex-M0+ core, up to 48 MHz operation 32-bit ARM Cortex-M4F core,  up to 112 MHz operation Voltage range: 1.71 to 3.6 V Voltage range: 2.7 V to 5.5 V • Up to 128 KB program flash memory • Up to 16 KB SRAM • Up to 512KB program flash memory • Up to 64 KB SRAM • Clock generation module with FLL and PLL for system and CPU clock generation • 4 MHz and 32 kHz internal reference clock • System oscillator supporting external crystal or resonator • Low-power 1kHz RC oscillator for RTC and COP watchdog •  4 - 40 MHz fast external oscillator (SOSC) with up to 50 MHz DC external square input clock in external clock mode •  48 MHz Fast Internal RC oscillator (FIRC) •  8 MHz Slow Internal RC oscillator (SIRC) •  128 kHz Low Power Oscillator (LPO) • 16-bit SAR ADC • 12-bit DAC • Analog comparator (CMP) containing a 6-bit DAC and programmable reference input  • Up to two 12-bit Analog-to-Digital Converter (ADC) with up to 32 channel analog inputs per module • One Analog Comparator (CMP) with internal 8-bit Digital to Analog Converter (DAC) •  Low-power hardware touch sensor interface (TSI) •  Up to 66 general-purpose input/output (GPIO) •   Non-Maskable Interrupt (NMI) •   Up to 156 GPIO pins with interrupt functionality • Two 8-bit Serial Peripheral Interfaces (SPI) • USB dual-role controller with built-in FS/LS transceiver • USB voltage regulator • Two I2C modules • One low-power UART and two standard UART modules   • Up to three Low Power Universal Asynchronous Receiver/Transmitter (LPUART/LIN) modules with DMA support and low power availability • Up to three Low Power Serial Peripheral Interface (LPSPI) modules • Up to two Low Power Inter-Integrated Circuit (LPI2C) modules • Up to three FlexCAN modules • FlexIO module for emulation of communication protocols and peripherals (UART, I2C, SPI, I2S, LIN, PWM, etc) • Six channel Timer/PWM (TPM) • Two 2-channel Timer/PWM modules • 2 – channel Periodic interrupt timers • 16-bit low-power timer (LPTMR) • Real time clock • Up to eight independent 16-bit FlexTimers (FTM) modules • One 16-bit Low Power Timer (LPTMR) with flexible wake up control • Two Programmable Delay Blocks (PDB) with flexible trigger system • One 32-bit Low Power Interrupt Timer (LPIT) with 4 channels • 32-bit Real Time Counter (RTC) • 4-channel DMA controller, supporting up to 63 request sources • 16 channel DMA with up to 63 request sources 1.2 Resources Model-Based Design Toolbox – Tool used to create complex applications and program the S32K144 MCU directly from the MATLAB/Simulink environment. This tool allows automatic code generation for S32K144 peripherals based on configuration of the Simulink model done by the user. S32K144-Q100 Evaluation Board – Evaluation board from the S32K14x family used for quick application prototyping and demonstration. NXP Cup Development Kit – Information about the hardware components of the development kit and instructions regarding the car assembling. Software which is helpful for the project design is also presented. FreeMaster Debugging Tool – Real-time data monitor tool which shows in both graphical mode (as a scope for example) and text mode the evolution of variables in time. It is suitable to monitor application behavior in real time during execution of the code.  TSL1401 Datasheet – Information regarding the camera configuration. Excel Spreadsheet (attached at the end of the document) with routing information to map pins from Landzo to S32K144 board. 2. Hardware Setup    After assembling all the hardware modules as indicated in the development kit the car will look like in the next image. It should be mentioned that for the S32K144 EVB to system board connection an S32K adapter board was created. Fig 1. Hardware setup 2.1  Hardware Modules    The hardware modules of this application and the way the peripherals of the S32K144 MCU are communicating with those is summarized in the Fig. 2. To understand more about the control of the motors, please check chapters 3.4.4 and 3.4.5. For learning how to debug the application using the Freemaster software, take a look at the chapter 4 where a detailed description is presented. A similar indication is given also for the camera information collecting. Chapter 3.4.1 and 3.4.2 provide a close-up image of the operations that need to be done in order to make the car “see”. Fig 2. System block diagram 2.2  Hardware Validation Steps    After connecting all the hardware modules, connect a USB cable to the PC. Connect other end of USB cable to mini-B port on FRDM-KEA at J7. When powered through USB, LEDs D2 and D3 should light green like in the picture below. Also, once the S32K144 board is recognized, it should appear as a mass storage device in your PC with the name EVB-S32K144.        Fig 3. LEDs to validate the correct setup 3. Model-Based Design Application 3.1  Application Description    The Model-Based Design approach consists of a visual way of programming, which is based on blocks. A block implements a certain functionality, such as adding two numbers. In case of the NXP's Model-Based Design Toolbox which is specifically developed for the S32K14x family, a block implements a functionality of a MCU peripheral, such as turning on the green led on the board. Each block has a different functionality and for a complex application, multiple components should be used together so they can provide the best solution for the problem proposed. For example, if you want to toggle the green led at every 10 seconds, you are going to add a new block to your design, one that can count those 10 seconds and then trigger an action when the count is over, which is toggling the led. Connection between the blocks should be made accordingly to your application system model. When building the model, the code that stands behind the blocks and implements the connection logic between them is automatically generated and downloaded on the embedded target. Doing so, code errors are certainly eliminated, and a faster design process is accomplished.    For using the Model-Based Design Toolbox for S32K, the MATLAB programming platform should be installed on the PC you are working on. Make sure that you respect all the System Requirements that you can find on the following link (Model Based Design Toolbox). Follow the installation steps from the Install and Configuration Steps and now you are ready to develop your own model-based design application.           3.2  Application Scheme    The generated code from the Simulink model is downloaded on the S32K144 MCU. A mapping between hardware and software for this application is illustrated in the figure below: Fig 4. Hardware to software mapping    The hardware components are controlled by the application through the peripheral functions of the S32K144 MCU. This board is connected to the other hardware modules by using an adapter board. In the link NXP Cup Development Kit there are information regarding how to connect the camera, servo and motors modules on the System and Driver Boards. Thus, the software generated signals are transmitted to the modules that need to be configured and controlled (camera, servo, motors). Fig 5. Application Scheme    When you open the Simulink model, this structure shown in Fig. 6 will be displayed. The functionalities are grouped in areas, which area containing a small description of what it is computed inside it. There are blocks and connections between them like mentioned before. Based on the image given by the camera, the steering and the speed of the car should be controlled. More details about how each of the subsystems works are provided in the following chapters. Fig 6. Simulink top level system 3.3 Application Logic    The application logic is described by the following block diagram. The signal from the camera is converted and the data is stored in an array. Based on the elements of the array (description of the image in front of the car), an algorithm will compute how much does the car have to steer its front wheels. This is expressed in a duty cycle value of a signal, signal which will be directly transmitted to the servo module. A constant speed, 10% of the maximum reachable of the car, it is also given as a duty cycle of the signal which will control the two rear motors. Fig 7. Application logic diagram   3.4 Simulink Model Components 3.4.1 Camera Configuration                 The camera module has a major importance in the project, because it is used to scan and process the track in front of the car. Firstly, for the main purpose of the application: control the car and maintain its position on the desired direction, the camera module should be configured so it can receive the analog signal properly. After the camera receives the analog signal, the application converts it into 128 digital values on the basis of which control decisions will be taken. There are 128 digital values for a conversion because the line scan camera module consists of a linear sensor array of 128 pixels and an adjustable lens. As specified in the datasheet, for the camera module configuration, two signals must be generated, a clock and a serial input (CLK and SI). Fig 8. Waveforms for camera configuration    To validate the functionality of this module, you should open the FreeMaster and check that the camera is working properly. Open the .pmp file and watch the conv variable evolving on the recorder. Put a white paper in front of your camera and then move an object in front of it. Every time the camera spots a dark color, its graphical evolution presents easy observable dips like in the picture below (blue graphic).                                                                                      Fig 9. Dips caused by dark objects CLK Signal    For the CLK signal generation, a FTM (FlexTimer) block is used. This block generates a PWM signal with a duty cycle given as an input (DTC – Dutcy Cycle Camera). The duty cycle has to be 0.5 (50%) as specified in the datasheet. The PWM signal is then passed to the corresponding pin of the camera module through the S32K144 board.    Check the Landzo_car pins to S32K144EVB file for the mapping and connections.     The frequency of the clock signal was chosen considering the imposed value range in the datasheet. (fclock between 5 and 2000 kHz).       Fig 10. Generating the CLK signal      When configuring the FTM block, the following block parameters will be available:                    Fig 11. FTM block parameters    The FTM functionality has 4 different modules, each of them with 8 channels grouped in pairs (for each channel an output pin can be selected). After checking the Landzo_car pins to S32K144EVB file for the corresponding pin of the camera CLK, the choice of the FTM module and the pair should be done (FTM0_CH1 means that the pin is connected to the FTM0 module, pair 0-1). It should also be mentioned that the camera module is connected on the CCD1 interface of the System Board in the hardware setup of this application. Another linear interface CCD2 is available for user usage, as specified in the description of the development kit. The frequency of the signal can also be set from the editbox in the Frequency Settings groupbox. An initial duty cycle value equal to 0.5 was set according to the datasheet.    There are two operation modes for each pair of channels and they can be chosen from the popup box next to the pair selection. These modes are called independent and complementary. Let’s give them a short description.    By setting channel n in the Complementary mode, the output for the channel n+1 will be the inverse of the channel n output and the block will have only one input. In the Independent mode, the channels have independent outputs, each one depending on the duty cycle given as an input on that channel (2 inputs for the block in this case). The CLK signal of the camera is transmitted to a single pin of the hardware module, so there is no need for two channels to be configured. Only one is enough to output the desired waveform (in complementary mode, only the first channel of a pair will be set; ex: channel 0, channel 2, channel 4, channel 6). That is why the Complementary option is chosen in this case. The input will be the 50% duty cycle on the basis of which the CLK signal will be generated. The channel 7 will now be the inverse of the channel 6 but in the next picture it can be observed that the channel 7 does not have a pin to output the signal to, because the inverted CLK signal is not needed in the current application.                   Fig 12. FTM output signals SI Signal      The SI signal’s period must provide enough time for 129 CLK cycles, as the timing requires (datasheet). 129 CLK cycles are needed with the purpose of acquiring 128 samples of the analog signal received by the camera. In order to meet all the specified conditions for a normal operation mode, the algorithm to create the CLK and SI waveforms as required uses two Periodic Interrupt Timers (PIT) blocks. Fig 13. PIT blocks    An interrupt represents a signal transmitted to the processor by hardware or software indicating an important event that needs immediate attention. The processor responds to this signal by suspending its current activities, saving its state and executing a function called an interrupt handler to deal with the event. The interruption is temporary, and, after the interrupt handler finishes, the processor resumes its normal activities.    A PIT block is used to trigger an interrupt handler to execute at every timeout of a counter. The Function-Call Subsystems linked to the PIT blocks represent the actions inside the interrupt handler. The interrupt handler will be triggered every Period(us). For the first PIT, it will be triggered every 20000us and for the second one every 100us. This means that every time the counter reaches the value specified in the block configuration parameters, the Function-Call Subsystem is triggered, the actions inside of it executed and the counter reinitialized. Fig 14. PIT block parameters    The PIT functionality has 4 channels, and they are implemented based on independent counters. The channel 0 is not available for user usage because it is configured to trigger the execution of the entire model at every period of time specified in the model configuration parameters.    The last checkbox from the block parameters is used to start the counter immediately after the application initialization, without waiting for other events.    Considering all the information mentioned above, the timing of creating the waveforms as required involves the following actions:      at every 100µs (CLK signal’s period) the next things happen: Fig 15. Actions in the 100us interrupt           C variable, which counts the clock cycles, is incremented; If C >=2, the SI signal is turned from high to low. (value 2 was chosen to keep the SI signal high for the convenient amount of time as specified by the tw, tsu, th and ts parameters. Their values can be found in the datasheet)                    Fig 16. Timing for camera configuration    A GPIO (General Purpose Input/Output) block is used for this and its role is to send the value given as an input to the selected pin which can be selected from the dropdown menu available in the block configuration parameters). Fig 17. Setting SI signal LOW Fig 18. GPIO block parameters A conversion is started and if C < 128, the converted values (analog-digital conversion of the received signal from the camera) are stored in an array of 128 elements (Store the converted values into an array subsystem is triggered) and into the conv array. Conv variable is used for the debugging process which will be later detailed.          at every 20ms (SI signal’s period) the next things happen:        SI signal is turned from low to high using the same GPIO functionality;       The clock cycles counter C is reinitialized;             Based on the values of the array (high values for white, low values for dark) and on their indexes, the duty cycle (DTS – Duty Cycle Servo) which controls the              Servo is computed (it controls the car to turn left or right with a certain angle); Fig 19. Actions in the 20ms interrupt 3.4.2 Camera Reading    After the camera module is configured (SI and CLK signals generated as specified), the data acquisition can be started. The signal given by the camera is converted into digital values which are stored in an array. The conversion implies the usage of the ADC (Analog to Digital Converter) functionality. Taking this into consideration, a configuration block for the ADC should be added to the Simulink model.         Fig 20. ADC configuration block    The ADC of the S32K144 has two modules (ADC0, ADC1) each of them with up to 16 external analog input channels and up to 12-bit conversion resolution. The camera module is connected to the CCD 1 linear interface of the System Board. The Landzo_car pins to S32K144EVB file specifies that the pin of the camera module which receives the analog signal is ADC1_CH10, so the ADC 1 module should be configured. A 12-bit conversion resolution was chosen for improving the accuracy of the sampled data.     An analog to digital conversion should happen every 100us as specified in the Timing section, because 128 samples of the input signal need to be acquired (every time the C variable is incremented, a value should be stored in the conversion array). Fig 21. Start of conversion    Considering the facts mentioned in the previous paragraph, every time the subsystem of the PIT block is triggered, the conversion is started (an ADC Start block is used) and if C < 128 the sampled data is stored into the array that will consist the information on which basis the servo control decision will be taken. Variable C is the index of the array elements and each result of the conversion represents the value of an element. Following this algorithm, the Y array is created and it is going to be used in the next chapter where the algorithm which computes how much the car should steer, based on the image of the track in front of it, is described. For putting the values into the array an assignment block is used. Fig 22. Storing conversion values to Y array     3.4.3 Camera To Steering Algorithm    The algorithm presents a basic approach and uses an if-else logic. Before giving it a short description, a couple of things should be mentioned.   Considering the reference voltage of the ADC module of the microcontroller which is 5V and the 12 bit resolution of the conversion, the resolution on a quantum is 5 / 4095. But the camera is powered by a voltage approximately equal to 3.4V, thus resulting a value which varies around 3.4 / ( 5/4095) = 2785. This value is the maximum that the ADC can provide when the camera spots white in front of it. The light conditions in the room represent a major factor that contributes to variations of this value.   The Servo of this kit needs a 20ms period PWM signal with the pulses duration equal to 600µs for a neutral position of the wheels, 400µs for the wheels turned maximum left, and 800µs maximum right. This results in the following values for the duty cycle (0.03 - the car goes forward, 0.02 – the car turns maximum right, 0.04 – the car turns maximum left). The 0.02 value should be replaced by 0.023 in order to obtain a proper operation mode due to the servo’s construction particularities.      The array with the converted values (Y) is iterated. If a dark value is found (the difference between ‘maximum white’ and the value of the current element is bigger than a threshold), the duty cycle is computed to determine how much right or how much left the front wheels should turn. If a dark value is spotted in the first half of the array, the car should turn right, or left if found in the other. But the camera gives the image from right to left so the turning ways are opposite (left if a dark value is spotted in the first half of the array, right for the second one).    After determining the way of the steering, left or right, the DTS is computed proportionally with the index of the array where a dark value is found. If a value representing a dark color is spotted at the beginning or at the ending of the array, it means that the what needs to be avoided is not exactly in front of the car, but more to one side of it, so a steering with a small angle should be effective in order to keep the car on the runway. On the other hand, if a small value is found more to the middle of the array, a wider angle of steering should be computed in order to ensure the avoidance of the dark color and the car moving off the track.     Fig 23. Matlab function for computing the DTS 3.4.4 Set The Servo    The DTS is then passed to another FTM_PWM_Config block to generate the signal needed to control the Servo.       Fig 24. FTM block for controlling the servo      In order to do so, the block should be configured with the following parameters, which have the same signification as mentioned in chapter 3.4.1:                 Fig 25. FTM block parameters    According to the hardware connections from the S32K adapter board and the current setup, only one Servomotor is used, and this is the STEERINGPWM1 mentioned in the file with the mapping between the Landzo car pins and the S32K144 board. The allocated peripheral for this module is the FTM0_CH1, which means that the module 0 should be chosen from the configuration parameters together with the 0-1 pair of channels. To control the servo, only one signal is needed, so there is no need to use 2 channels. The complementary mode could have been used here, like in the camera CLK signal configuration, but doing so, only the configuration of channel 0 would have been possible and channel 1 is requested for the application. By choosing the independent mode, a duty cycle input will be available for the both channels of the pair, and because only channel 1 is needed for the control of this module, an input equal to 0 will be given to the other one. The frequency is set to 50Hz considering the motor construction particularities and a duty cycle equal to 0.03 (wheels not steered) is set as an initial value.     Fig 26. FTM output signals 3.4.5 Set The Motors    For the two rear motors, the same principle applies. The duty cycle (DT) is configured by default at the 0.1 value which will cause the car to move along the track with 10% of its maximum speed.     The frequency of the PWM signal that controls the motors is 5000Hz. This value is in the range specified in the datasheet of the motor drivers mentioned in the schematics.                 Fig 27. FTM block for controlling the traction motors     For the control of a single motor, two signals are needed. The schematics of the Motor Driver board indicate that for the control of each motor two integrated circuits are used (BTN7960). They form an H bridge which looks as in the picture below.                 Fig 28. H bridge    To make the motor spin, the potential difference of the points the motor is connected between must be different from 0. It can be observed that each integrated circuit needs an input signal. The pins that give the input signals to the circuits are corresponding to the output channels of the FTM block. Let’s take for example the 1st rear motor. It is controlled by a FTM Config block which outputs on the following channels.                     Fig 29. FTM output signals    By setting and keeping channel 3 of the FTM Config block channels to 0, an input equal to 0 will be transmitted to one of the BTN modules as an input on the IN pin (for example, to the right one). This will trigger the right lower transistor to act like a closed switch. The transistor above it will remain opened, so the voltage of the OUT point will be 0V. The channel 2 corresponds to the other integrated circuit, and a positive input will be received by this one on the IN pin (left side of the picture). Now, the left upper transistor will act like a closed switch, and the one below will remain open, making the OUT point’s potential to represent a positive value (depending on the duty cycle given as an input to the FTM block). Thus, a potential difference is created and the motor will start spinning. 3.4.6 Configuration Block    In addition to all these, the model needs also a configuration block which is used to configure the target MCU, the compiler, the system clock frequency, etc. A configuration block is needed in all the models because it ensures the communication with the target. Fig 30. Model configuration block    The operation frequency can be chosen from the MCU tab of the block parameters window. For this model, it was set at 80Hz. The board model, the SRAM and the clock frequency can also be set from the MCU tab. Fig 31. Configuration block MCU tab    If you want to change the compiler and also the optimization levels, click the Build Toolchain tab and take a look at the available options presented in the picture below. From this tab you can also choose the target memory for the model which can be FLASH or SRAM.                   Fig 32. Configuration block Build Toolchain tab    The application is downloaded on the target through OpenSDA. OpenSDA is an open standard serial and debug adapter. It bridges serial and debug communications between a USB host and an embedded target processor. Make sure that the Download Code after Build option is checked in order to see your application running on the target.                   Fig 33. Configuration block Target Connection tab    For additional information about the blocks used in this model, right-click on them and choose the ‘Help’ option available in the menu. 4. How To Debug The Application Using FreeMaster    In order to use FreeMaster for debugging and managing the information from your application, a FreeMaster configuration block must be used in the Simulink model. Fig 34. FreeMaster configuration block    The block parameters should be configured as in the following picture: Fig 35. FreeMaster configuration block parameters    The interface field specifies the communication interface between the application and the FreeMaster. LPUART1 is chosen in this example because it is directly connected to the OpenSDA. OpenSDA is an open standard serial and debug adapter. It bridges serial and debug communications between a USB host and an embedded target processor.    The BaudRate represents the speed of data transmission between the application and the FreeMaster and it is expressed in kbps. The receive data pin and the transmit data pin should be always configured to PTC6, respectively PTC7 (for the LPUART1 interface) because these pins are connected to the OpenSDA Receive and Transmit pins, as specified in the HMI Mapping.       Fig 36. OpenSDA to LPUART1 connection    By clicking the Show Advanced Options checkbox, multiple settings are available and their functionalities are all specified in the Help file which will open after clicking the Help button in the Block Parameters tab.    The variables that need to be observed changing over time must be declared Volatile. The variables already added to the FreeMaster project are declared using the Data Store Memory block.                 Fig 37. Global Variables    The Volatile option can be chosen from the Block Parameters Tab. After double clicking the Data Store Memory block, click the Signal Attributes tab and in the Code Generation groupbox, set the Storage Class option to Volatile (Custom), as in the picture below.  Fig 38. Data store memory block parameters    For calling the FreeMaster data acquisition each time a subsystem is triggered, a FreeMaster Recorder Call block should be added in the subsystem where the variables that you want to record are computed. Thus, a recorder block is placed in the subsystem which is triggered at 100us for recording the evolution of C and conv variables. Fig 39. FreeMaster recorder call    To check the functionality of the FreeMASTER, open the .pmp file with the same name as the Simulink model and click on the red STOP button in order to initialize the communication with the S32K144 evaluation board. Fig 40. Start/Stop FreeMaster communication    If errors appear, click on the Project menu and open the Options window. Make sure that the port value is the same as the one on which your S32K144 is connected (you can check the COM number of the evaluation board in the Device Manager window). Make sure also that the Speed is the same as the baud rate of the FreeMaster Config block.       Fig 41. FreeMaster communication setup    Click on the MAP Files tab and ensure that the default symbol file is the .elf file from the folder that is created when you build your Simulink model. It should be called (your_model_name.elf).           Fig 42. FreeMaster .elf file    Once the connection is set and the app working, you will observe how the values of the variables in the Variable Watch are changing.    Click on the Recorder option from the left side of the window in order to see the graphical evolution of the variables.    You can add or remove variables from the watch by right-clicking inside the Variable Watch area and choosing the Watch Properties options.    Right clicking on the Recorder will provide a Properties option as well. Use that for selecting the variables that you want to display and for many other options.           Fig 43. FreeMaster recorder properties 5. Autonomous Intelligent Car Demonstration And Hints For Improvement 5.1 Demo    If you want to make sure that everything works as it is supposed to before actually putting the car on the track, you can use the FreeMaster tool to visualize the evolution of the variables of your project. Considering every setup was made as specified, here is what you should expect to see. Fig 44. Variable Watch    The two rear motors duty cycle and also the one for the camera CLK signal should have constant values all the time (0.1 respectively 0.5). The DTS should vary its values between 0.023 and 0.04 as mentioned in the Camera to Steer algorithm chapter. C variable must be incremented every 100us and reset every 20ms, this meaning that when it reaches 200, it should be set back at 0. This evolution can also be graphically observed by using the recorder option. Conv variable and Y array represent the conversion result and all the bottoms of the conv graphical evolution represent the existence of a dark color in the visual field of the car.    A demonstration video with the car following the track for a lap is attached to the current content.   5.2 Improvement Areas    The application proposed uses a basic if-else algorithm in order to compute the steering of the front wheels based on the track in front of the car. A proof of the concept that the vehicle can be controlled and kept on the path using a S32K144 board and a Model Based Design approach is realized in the presented solution. Major improvements regarding the lap time could be achieved by developing a way to control also the car speed which now is at a constant value. Many other hardware and software solutions can be designed and implemented with the purpose of obtaining the fastest autonomous self driving car for the NXP Cup. NXP CUP - LINE FOLLOWER WITH MODEL-BASED DESIGN TOOLBOX FOR S32K MICROPROCESSOR
記事全体を表示
1. Introduction  The purpose of this article is to illustrate how to configure and use the ADC and PWM peripherals of the MR-CANHUBK3 Evaluation board.  We will demonstrate how to develop an application which uses the on-board potentiometer to control the PWM duty cycle for the RED LED on the target. For more details on MR-CANHUBK344 and how to do the initial setup (Simulink ®  environment, J-Link debugger, etc.) please refer to Interacting with Digital Inputs/Outputs on MR-CANHUBK344 article. 2. ADC Configuration  2.1 Hardware Connections  The MR-CANHUBK344 evaluation board has multiple ADC channels that can be routed on various pins in complex applications. Our focus will be on the ADC channel corresponding to the potentiometer.  The potentiometer present on the board (R84) is a 10K trimmer potentiometer connected between 3V3 and GND and is connected to the net named ADC_POT0. This is further routed via pin 11 – PTE13/ADC1_S19.    Potentiometer  and LED1 placement on the EVB:     Potentiometer schematic:   ADC_POT0 pin and its different routing options, with the correct one highlighted can be seen below:  The configuration of Adc component will be done in S32 Configuration Tools, but the same behavior can be achieved using EB Tresos.  2.2 Pins Configuration Firstly, we need to specify the configuration options for the pin itself. This is done in the Pins menu of the S32 Configuration Tools, as follows:   1.We search for the PTE13 pin and check if it is already configured.  In this case it is not routed to any functionality, but, if it was routed to anything but ADC, we need to perform the same steps:   1.Click on the checkbox near the pin name:   2. Select ADC1:adc1_s19 from the pop-up window:   3.Provide a label and identifier for the newly mapped pin  In this example, the Label and Identifier are set to ADC_POT0  After the pin is configured, we move to the Routing Details menu:   We search in the Routing Details menu for our pin, using the label set at the previous step. Once we find our pin, we check for the following options to be configured as follows:   Direction to be configured as Input  Input Buffer Enable to be configured as Enabled and update them accordingly if they aren’t.  2.3 Component Configuration  With the pins properly configured, we can move on to configure the Adc peripheral. We open the Adc component and begin by navigating to the AdcConfigSet tab where several steps need to be performed. In the AdcHwUnit menu, we first need to define a HW Unit for the ADC.  If no HW unit is defined, a new one can be created by clicking the "+" button. We can modify the default configuration delivered with the toolbox and automatically assigned by MBDT in the new Simulink model or we can configure a new one. With the ADC peripheral instance defined, the first steps are to:  Name our HW unit. In this example it is named AdcHwUnit_0.   Select the ADC hardware of our unit. As we already know from the schematics, the potentiometer uses channel S19 of the ADC1, so we choose ADC1 for this configuration option.  The logical Unit ID is used to enumerate multiple HW units if present. Since for this example we only have one, we put the value 0 here.  For the transfer type we can choose between either Interrupt or DMA. For this example, we choose to use interrupts.  From the options presented below, most of them are not relevant for this example and can be kept with their defaults value.  An important setting is the conversion resolution. For this example, we chose the maximum resolution of 14, which corresponds to a maximum value of 2^14 (16384). We can now move to the Channel definition inside the HW unit. If no channels are present, we can add a new one the same as before, by clicking the "+" button.  With a channel defined, the following configuration options need to be performed:  We need to specify the name of the ADC channel. For this example, we use ADC_POT_0. Note: This will be relevant when defining ADC groups. An ADC group is composed of multiple ADC channels.   Logical channel ID is 0 for this example since this is the only channel configured.  For the Physical Channel Name, we choose S19_ChanNum43 because we know we are on the S19 channel of the ADC. By looking in the S32Kxx Reference Manual we see that channel number 43 is mapped to ADC1_S19.  Physical Channel Id is just a mirror of the channel number from point 3.  With both HW Unit and Channel in place, we need to define an Adc Group. Adc Groups are used to oversee conversion for the channels assigned to them. For this example, our group will only have one channel assigned, the ADC_POT_0.  In the Group configurations array menu, we click the "+" button to add our group.   We name our group. For this example, our group will be named Adc1Group_0.   Group access mode should be SINGLE.  Conversion Mode should be ONESHOT. When Conversion Mode is set to Oneshot, the ADC unit performs a single conversion and then waits to be triggered again.  Conversion Type should be NORMAL. Here we can choose between NORMAL and INJECTED conversion types; an injected conversion can be performed on top of a regular conversion, based on some external trigger(sensor, timer etc.). For this application we don’t need this feature.  Group ID is 0 since it is the only group configured.  Group Trigger source is SW  Group Notification function is Adc_Adc1Group0Notification . This is the callback function of the ADC group. The function pointer is called each time the group conversion is finished.   Note: underlined values at steps 1 and 7 are highlighted because they will be visible in Simulink blocks when we create our model.  We can configure several options for conversion as well. In this example we have HW average enabled, using 4 samples. This is done in order to mitigate noise that may occur on the readings without delaying too much the final results.  In the AdcGroupDefinition menu, we have to add our channel, as configured in the previous steps.   2.4 Clocks Configuration (MCU)  For the ADC to work properly, it needs to have its peripheral clock enabled. This is done inside the Mcu Peripheral, under McuModuleConfiguration tab -> McuModeSettingConf:   Important note here:  Since ADC_POT0(PTE13) is configured by default as VRC_CTRL,  which is a PMC voltage regulator output that uses a BJT (Bipolar Junction Transistor) to generate a 1.5V supply, we need to disable this feature from Mcu configuration, otherwise we will not get accurate readings on the ADC pin.  This is done in the Mcu component, McuModuleConfiguration tab, McuPowerControlUnit menu, by disabling Last Mile Regulator Base Control Enable option:  2.5 Interrupts Configuration (Platform)  Since we opted to use the ADC in Interrupt Mode, we need to perform the correct configuration options inside Platform MCAL component.  The corresponding Interrupt Vector needs to be enabled, a priority must be given to it, and the correct handler function has to be specified from the RTD implementation.  All these options are configured inside Platform peripheral -> Interrupt Controller tab:     As it can be observed, the Interrupt Vector for ADC1 is enabled, has a priority of 5 and its handler function is Adc_Sar_1_Isr.  Finally, we save our configuration, we use the Update Code button and move to the model creation part of our example.     3. ADC Model Overview   With the configuration in place, the usage of S32 Configuration Tools (S32CT) is finished and we can implement our application in Simulink. In the following sections, we will go through the steps of creating a model that reads the potentiometer voltage and displays its value, converted into digital values, in FreeMASTER. More details FreeMASTER setup can be found in article 2.  Model overview:      Going from top to bottom we have:  3 data store variables: the ADC VersionInfo, Adc1Group0_ResultBuffer, and Channel0.  The initialize block  The FreeMASTER config block  The Start Group Conversion block  The HW Interrupt Callback block, which triggers:  The ADC Read Group block  All the ADC blocks can be found inside the MBDT:  The functionality is further detailed below:  In the initialization block we prepare the SW for the ADC conversion by assigning the result buffer variable for our ADC group and by enabling the Group Notification.  Note: To be observed that the ADC Group used in both ADC blocks is exactly the same as the one underlined in 2.3 configuration chapter.  With the initialization done, the ADC group conversion can be started. This is performed periodically in the model’s step() function.  When the group conversion is finished, the group notification callback signals back to us that we can read the ADC value, and this is done into the subsystem triggered by the Hardware Interrupt block:  The freshly converted value is stored inside Channel0 variable and it is ready to be used further.   As it was observed in Sending data via UART and monitoring signals with FreeMASTER, FreeMASTER can be used to observe the evolution of a certain variable over time. We can use this feature to display the ADC readings stored on Channel0 on an oscilloscope.   We check if the values shown match our expectations when the Potentiometer is rotated. As it can be observed in the picture below, the values go from 0, up to 16384, and then back down to 0, as the potentiometer is rotated clockwise and then counterclockwise. This fully matches our expectations and validates that both the configuration and the Simulink application are implemented correctly.    4. PWM Configuration  4.1 Hardware Connections  The MR-CANHUBK344 is suited for various Pulse Width Modulation applications. The main PWM output port of the board is P8A, which in conjunction with P8B can be used to control and read feedback from common servomotors.  In this example , we are controlling the intensity of the RGB LED via PWM, based on the ADC readings from the potentiometer.  Note: The PWM control of the RGB LED is possible because each one of the 3 colored LEDs can also be routed via an eMIOS channel:  It is important to mention that we chose to generate our PWM signals using the Enhanced Modular IO Subsystem (eMIOS). eMIOS provides us independent channels, UCs (unified channels) that we can configure to generate or measure time events for different functions in different chip applications.   eMIOS distributes these channels across a number of global and local counter buses. Each local bus is dedicated to a group of eight contiguous channels. Each channel can generate its own timebase, and each counter bus has its timebase provided by a dedicated channel.  For the S32K344 MCU, we have 3 eMIOS instances available, each with the following configuration:  There are 4 different eMIOS channel types: X, Y, G and H. Each channel type supports a different subset of operation modes. More information can be found in “eMIOS channel types section of the S32K3xx MCU Family - Reference Manual :  It is important to be acquainted with the types of channels and their supported operation modes in order to be able to configure UCs properly, as some permutations may not be possible and configuration errors may occur.  The eMIOS is clocked by CORE_CLK, which has a frequency of 160 MHz. This is worth mentioning now, as it will become relevant when calculating the frequency of our PWM.  Important note: For this example, we choose to control the intensity of the Red LED ONLY, as the configuration steps for the other 2 LEDs would be similar.   Since we know that the Red LED is routed via CH19 of eMIOS_0, which is a type Y channel, we can choose to operate it via OPWMB Mode (Output Pulse Width Modulation Buffered). This mode comes with a fixed period for the PWM signal, variable(controllable) duty cycle and uses an external counter bus.   4.2 Pins Configuration Firstly, we need to route the pin:  We look for the port and pin number of the red LED, and we observe it is part of Port E and has pin number 14:  As we did for the ADC pin, we look for PTE14 inside Pins tool , and we route it to eMIOS_0: emios_0_ch_19_y  When prompted, we select Output as direction for our pin. We provide a label and an identifier(RGBLED0_RED) for the pin.  In the Routing Details menu, we should have the following options configured:  Direction: Output; Output Inversion Select: Invert and OutputBuffer Enable: Enabled.   Note: If the configuration is done in EB Tresos and we add a new routing for the pin as PWM in the Port component, an error message will most likely appear. This can occur if the pin is already configured as a GPIO pin (DIO) inside Port component. To avoid this, the routing of the pin as a GPIO should be deleted.    4.3 Clocks Configuration (MCU)  As a prerequisite, we need to make sure that CORE_CLK is configured . This can be observed inside Mcu component -> McuModuleConfiguration tab -> McuClockSettingConfig menu -> McuClockReferencePoint submenu  Moreover, we need to make sure that the clock is enabled for the eMIOS instance we will be using:  This can be done in Mcu -> McuModuleConfiguraion ->McuModeSettingConf - >McuPeripheral  4.4 MCL  As stated before, eMIOS can work using global or local buses. Different channels need to be assigned as timebase channels for the buses depending on the desired configuration:  Global bus A: serves all UCs, uses CH23 as timebase  Local bus B: serves UC0..UC7, uses CH0 as timebase  Local bus C: serves UC8..UC15, uses CH8 as timebase  Local bus 😧 serves UC16..UC23, uses CH16 as timebase  Global bus F: serves all UCs, uses CH22 as timebase  For example, we will use the global bus A and CH23 as master timer channel. This is configured inside Mcl component, as follows:  In the Mcl Specific Configuration tab, in EmiosCommon menu, we can add a new common eMIOS configuration, or we can modify an existing one to suit our needs.  We name our configuration   We select the eMIOS instance (eMIOS_0 in our case, since Red LED is routed via CH19 of eMIOS_0)  Clock Divider Value is used in frequency calculation and will be addressed separately. It has a range from 1 up to 256.  We need to define the time base channel for our master bus in its dedicated tab, as follows:  We name our time base channel  We select CH23, since we use Global Bus A  Default period and Master Bus Prescaler are used in frequency calculation. Default period can be any value from 0 up to 65534 and Master Bus Prescaler can be 1, 2, 3... up to 16.   PWM frequency calculation:  The PWM frequency needs to be decided upon based on the type of peripheral we want to actuate. For example, most servomotors operate at 50Hz, most BLDC motors support frequencies ranging from 5kHz up to 50kHz etc. This information needs to be known beforehand and configured according to the following formula:  A different way to think about this is by visualizing this formula having in mind the period of our PWM signal instead of its frequency:    Default Period is given in ticks, and the value of a tick is determined by the CORE_CLK frequency, divided by the 2 prescalers(Clock Divider Value and Master Bus Prescaler) and then inverted.  An undivided(both prescalers are 1) CORE_CLK tick has a value of 6.25 ns (1/160000000Hz).   Knowing the desired frequency for our application, we can determine its period. In order to have the same period, hence frequency, for the generated PWM signal, we need to adjust(or not, depending on the application) the values of the 2 prescalers in order to increase the CORE_CLK tick duration. The maximum value we can set for the Default Period is 65534; this value is then multiplied with the CORE_CLK tick duration after it is prescaled and the final result is the period of the PWM signal our application will generate.   Note: Without any prescaling, the maximum PWM period duration is roughly equal to 410 microseconds (6.25 ns * 65534), which corresponds to a frequency of ~2.4kHz. For applications that need slower frequencies, the CORE_CLK has to be prescaled. Ideally, the values for the prescalers and for the number of ticks should output an integer number for the period duration.  If we know our operating frequency f, we can adjust the 2 prescaler values and the default number of ticks to achieve it:  Example 1: If we know we need to actuate a servomotor with operating frequency of 50 Hz, we substitute in the formula the values we know (PWM_Frequency, CORE_CLK) and look for values of the prescalers and default number of ticks that do not exceed the configurable range. Note that multiple solutions are likely to be found and a suitable one needs to be chosen.  A possible solution for this specific frequency is Clock Divider Value = 256, Master Bus Prescaler = 1, Default Period = 12500.  Another one is {128,4,6250}.  Example 2: If we know we need to actuate a BLDC with an operating frequency of 20kHz, a possible solution is {1,1,8000}. Another one is {2,2,2000}.    4.5 Component Configuration  Inside the Pwm component, we need to perform 2 sets of configurations, one for the eMIOS channel and one for the PWM channel. Both can be performed in PwmChannelConfigSet tab.  4.5.1 eMIOS    First of all, we need to add our eMIOS instance. This is done by clicking the "+" button at the top of the window. We need to make sure the proper hardware instance is selected, in our case, eMIOS_0.  With that in place, we can move to the configuration of the channels. If no channels are configured, a new one can be added using the "+" button. In our example, several channels are already configured, but our focus is on the 8th channel. With it selected, we set its name, we select the Channel ID to address  19th eMIOSchannel, select the desired operating mode(OPWMB), choose Bus A as a counter bus. For the PwmEmiosBusRef, we use the one previously configured at step 4.4.  We keep the prescalers at DIV_1 and we choose not to phase shift our signal, since it is not needed for our application.  4.5.2 Pwm Channel  With the eMIOS channel configured, we can move to the PWM channel configuration.  We add our channel, we give it a relevant name and assign it a channel ID. The Channel ID identifies the position of the channel in the configured list of channels.  For the PwmHwChannel option, we select the eMIOS channel configured at the previous step.  Default Period should have the same value as the one we defined for the Master Bus inside Mcl component, otherwise we will receive an error message.  Default Duty cycle represents the duty cycle forwarded to the LED at initialization. We keep it at 0 for our example.  At the PwmMcuClockReferencePoint option, we select CORE_CLK, as defined in the Mcu component.  Note: For this example, the use of interrupts was not needed. However, if interrupts have to be used, proper configuration settings must be done inside Platform component:  As it can be observed, we have 6 Interrupt vectors, numbered from 0 to 5, for each EMIOS instance. Each vector handles 4 channels. The channels are assigned in descending order, starting with vector 0: For each instance, the _0 vector will serve the channels # 23, 22, 21 and 20, the _1 vector will serve the channels # 19, 18, 17 and 16 and so forth until the _5 vector which will serve the channels # 3, 2, 1 and 0.  This concludes the configuration part of the PWM channel needed for our example and we can move on with the Simulink model.   5. PWM Model Overview    In order to implement this application, we will extend the ADC model created at step 3. Since we want to control the intensity of the LED based on the readings from the potentiometer, we will use the ADC converted potentiometer value as an input for the PWM channel.   Our application is structured into 4 parts:  Initialization part  Input Handling  Algorithm  Output Setting  The Initialization and Input handling sections of our application are similar to the ones present in the model created at step 3 of this article, the only exception being that the ADC reading is not only stored inside Channel0 variable, but it is also fed into the algorithm.  Our application’s algorithm’s goal is to convert the raw values provided by the ADC into values that are accepted by the PWM block. Since our input values need to be scaled up with a factor of 2, we need to apply the Gain block from Simulink.    We need to consider that the Pwm Block expects an argument of uint16 data type, so we need to make sure that the gain applied is of that type:  The output of our application is represented by the LED intensity (i.e. the duty cycle). One important mention here is that the duty cycle is not expressed as a percentage, but as a value from 0 to 32768 (0 -> 0% duty; 16384 -> 50% duty; 32768 -> 100% duty).   For the output control, we need to use a Pwm block from the MBDT:    We drag and drop the Pwm block into our canvas, we select the desired function (Pwm_SetDutyCycle) in our case, and also the Pwm channel we want to control(we choose the PWM channel configured at 4.5.2 step, in our case PwmChannel_8; all the channels selectable from the drop-down list are the ones previously configured in S32CT) :  We apply the algorithm to the input value and feed the result into the PWM block:   Below, a video showcasing the functionality can be found In the first part of the video, the potentiometer is rotated clockwise and the duty cycle of the LED gradually reaches 100%, then, in the second half of the video, the potentiometer is rotated in the opposite direction and the LED can be observed dimming down until it turns back off completely. Note: The status LEDs were covered with black tape so that the Red LED's intensity can be seen more clearly   6. Conclusion  ADC and PWM are 2 peripherals with a large applicability domain and they are frequently used in embedded applications. The goal of the article was to extend the general knowledge about those 2 peripherals and apply it on a hands-on example using MR-CANHUBK344 Evaluation board. The LED intensity dimming example illustrated in this article covers the configuration part of both peripherals, the development of an algorithm that handles input values and feeds them to the output and, together with the previous articles, helps us understand better the integration process of embedded applications using Model-Based Design Toolbox.      Instructions on how to run the attached model: Download and extract the archive’s contents; Copy both the .mdl and .mex file to the location where you wish to set up the project; Note: for the model to work properly, please place the .mex file next to the model. Open the .mdl file and make sure that MATLAB’s Current Folder points to the folder that contains the model; Click on the Hardware tab and then press the “Build, Deploy & Start” button.   Simulink is a registered trademark of The MathWorks, Inc. See mathworks.com/trademarks for a list of additional trademarks.  
記事全体を表示
1. Introduction This is the second article in the beginner’s guide series and it showcases an example application developed in MATLAB ® Simulink ® for the MR-CANHUBK344 evaluation board. The application illustrates the ease of utilizing UART capability through NXP ® 's Model-Based Design Toolbox. For more details on MR-CANHUBK344 and how to do the initial setup (Simulink environment, J-Link debugger, etc.) please refer to article 1. 2. UART Configuration The focus in this chapter will be to provide a detailed guide on how to configure the UART (Universal Asynchronous Receiver-Transmitter) peripheral, by covering all the necessary steps such as configuring an UART instance and its corresponding pins for data transmission and enabling the peripheral clock and interrupts. Configuration of the MCU peripherals, the clock and pins direction, can be performed using S32 Configuration Tool (S32CT) which is proprietary to NXP. Please be advised that exactly the same microcontroller configuration can be achieved using Elektrobit Tresos Studio (EB Tresos). 2.1. Hardware Connections Looking at the Schematic of the evaluation board (MR-CANHUBK344-SCHematic), we can see that the LPUART2 peripheral can be routed through the debug interface: This is very convenient since the kit includes a DCD-LZ Programming Adapter, a small board that combines the SWD (Serial Wire Debug) and the Console UART into a single connector. 2.2. Pins Configuration For configuring the LPUART2 peripheral pins, we must open the configuration project (please check article 1 for more information on this process) and access the Pins Tool (top right chip icon).   While in this screen, from the Peripherals Signals tab, we can route the lpuat2_rx to the PTA8 pin and lpuart2_tx to the PTA9 pin: 2.3. Component Configuration In this subchapter, we dive into configuring the UART peripheral, component that allows the serial communication. We will also explore the various settings and parameters that enable efficient data transmission and reception. First, the LPUART_2 instance must be assigned to UartChannel_0 of MCAL AUTOSAR module by doing the following settings in the UARTGlobalConfig tab, which can be opened also from the Components tab: UART asynchronous method is set to work using interrupts as opposed to DMA. This method dictates how the mechanism for the functions AsyncSend and AsyncReceive works. More will be discussed in chapter 3. Other settings here include: Desire Baudrate (115200 bps), Uart Parity Type, Uart Stop Bit Number, etc. . These are important as they will have to be mirrored later in the PC terminal application. Afterwards, go to GeneralConfiguration and please note that the interrupt callback has the name MBDT_Uart_Callback, this is already configured in the default S32K344-Q172 project: MBDT_Uart_Callback is the name of the user defined callback which will have its implementation designed in the Simulink application. It will be called whenever there is an UART event: RX_FULL, TX_EMPTY, END_TRANSFER or ERROR. We can give any name to this callback, but since it will also be later used in the Simulink model implementation, it would be easier to keep the same nomenclature, at least for the purpose of this example. 2.4. Clocks Configuration (Mcu) In this subchapter we enable the clock of the LPUART2 instance, in the Mcu component: In the newly opened Mcu tab, go to McuModuleConfiguration then McuModeSettingConf and then to McuPeripheral: Then enable the clock for the LPUART_2 peripheral: UART is an asynchronous data transmission method, meaning that the sender and receiver don't share a common clock signal. Instead, they rely on predefined data rates (baud rates) to time the transmission and reception of bits. The clock, in this context, is used to establish the bit rate and ensure that both the sender and receiver are operating at the same speed. This synchronization enables successful data transmission and reception, preventing data loss or corruption. In UART, the transmitting device sends data bits at regular intervals based on the clock rate, and the receiving device uses its own clock to sample and interpret these bits accurately. This asynchronous nature makes UART suitable for various applications, allowing data to be transmitted reliably even when devices have slightly different clock frequencies. 2.5. Interrupts Configuration (Platform) In this subchapter, we will illustrate how to enable the UART interrupts. To find the corresponding settings we need to access the Platform component, afterwards we go to Interrupt Controller and then enable the UART interrupts: The interrupt controller from the Platform component configures the microcontroller interrupts vector and the handler there is the one declared inside RTD (Real-Time Drivers), implemented also inside RTD. It means that the LPUART_UART_IP_2_IRQHandler is already defined and it is not recommended to change its name. We are just pointing the interrupts vector to use it. 3. UART Model Overview In this chapter we will do the implementation for a simple Simulink model that uses the above configuration of the microcontroller to send a message via UART when the processor initially starts, and then echo back the characters that we type in a serial terminal. For implementing our application we are going to create a Simulink model, where we can drag and drop the UART block from the Simulink library to implement the logic of our application. The UART block can be found in the Simulink Library under the NXP Model-Based Design Toolbox for S32K3xx MCUs. The UART block can be found under S32K3xx Core, System, Peripherals and Utilities in CDD Blocks: After adding it to the Simulink canvas we can double click on it to access the block settings: Here the desired function can be selected: GetVersionInfo, SyncSend, AsyncSend, GetStatus etc.   Some useful information can be found below, regarding the functions that will be later used in this example, as an addition to what the Help button already provides. Uart_SyncSend is used for synchronous communications between the target and the UART terminal as it is checking the status of the previous transfers before proceeding with a new one (not to be confused with a synchronous serial communication, there is no separate clock line involved). This method of transferring data bytes ensures that the transmission buffers are free while it is blocking the main thread of execution until the corresponding transmit register empty flag is cleared. Uart_AsyncSend function, as a method of transferring data, is called asynchronous because data can be transmitted at any time without blocking the main thread of execution. It is recommended to be used in conjunction with transfer interrupts handlers to avoid errors. Uart_AsyncReceive is the function used to get the input data. Its output, Data Rx, is used to specify the location where the received characters will be stored. By placing this block in the initialize subsystem and in the interrupt callback, as we are about to see in the following chapter, we make sure that each character received will be stored and also that the receive interrupt is ready for the next event. Also, for UART, the Hardware Interrupt Callback block can be added from ISR Blocks: Here, the previously configured Interrupt handler (MBDT_Uart_Callback, see chapter 2) must be selected: The Hardware Interrupt Handler Block is used to display all the user defined callbacks that can be configured in S32CT, allowing their implementation in the Simulink model. In case of UART, the MBDT_Uart_Callback will be present in this block, to allow the implementation of specific actions when an interrupt occurs on the configured LPUART instance. If we would have modified the name of the receive callback in S32CT, after updating the generated code, we would be able to see the change in the Simulink block by pressing the Refresh button. Here’s how the overall picture of the implementation looks like on the Simulink canvas: In the Variables section we can see a list of DataStoreMemory blocks which act as memory containers similar with the global variables in C code. The Initialize block is a special Simulink function in which the implementation that we only want to be executed once, at startup, can be added. Inside this function block the variable transfer_flag is initialized with value 1, marking that the next event will be to receive a byte. Uart_AsyncReceive block sets a new buffer to be used in the interrupt routine where the character sent from the keyboard is stored. This function doesn’t actually read the character but only points to the memory location where the characters will be stored after reading it. Uart_SyncSend function will output the string of characters: “Hello, MR-CANHUBK3 here! Please write a message and I will echo back the characters as you type them”, framed by NL and CR characters. In UART Actions we have the Hardware Interrupt Handler Block that calls UartCallback at each transfer event, but we use the Event line to filter out all events except for END_TRANSFER. Now let’s see what’s inside the If Action Subsystem block: When a character is sent from the PC terminal and received in our application, an End Transfer event occurs (with receive direction) and the Send block is the executed path (because transfer_flag is equal to 1). This, in turn, will call the function Uart_AsyncSend to load the transmit buffer with that same byte that was received. Also the variable transfer_flag is changed from 1 to 2. When the transmit buffer was successfully emptied, meaning that a character was sent to the PC terminal, an End Transfer event occurs (with transmit direction) and the Receive block is the executed path (because transfer_flag is now equal to 2). This, in turn, will call the function Uart_AsyncReceive to reset the receive buffer making it ready for the next receive event. Also the variable transfer_flag is changed from 2 to 1. The Uart_GetStatus function block can be used to store the number of remaining bytes and the transfer status if further development of this example is desired. The complete  application together with the executable files can be found in the first attachment of this article (Article 2 - mrcanhubk344_uart_s32ct). 4. Test using the PC Terminal Emulator In this chapter we discuss the details of building, deploying, and testing the UART-based application. Our focus will be on the testing phase, creating an effective testing setup and ensuring that each element of the application performs correctly. First of all please make sure that the hardware setup with all the wires connected looks like this: Beside the hardware connections that are already mentioned in setup chapter from article 1, a USB to Serial converter device needs to be connected between the USB port of the PC and the DCD-LZ adapter that comes with the evaluation board. The DCD-LZ adapter is then connected to the evaluation board via the P6 debug port. The J-Link debugger can be connected directly to the evaluation board or to the DCD-LZ adapter via the P26 JTAG port. Once the hardware setup is complete, we can continue with the project build step. Pressing the Build button in the Embedded Coder ® app in Simulink, will generate the corresponding C code from the model. The code is then compiled and the executable file is created and deployed on the target (MR-CANHUBK3 evaluation board) using J-Link JTAG. As previously mentioned, a Terminal emulator program needs to be installed and configured on your computer and an USB to Serial converter needs to be connected between the computer and the target, as illustrated in the above picture. Probably the simplest choice for the Terminal would be PuTTY, which needs to be installed and then configured as follows: We can see now that the UART settings from chapter 2.3 are mirrored here. What port the USB-Serial converter uses can be found by looking it up in Device Manager, under the Ports tab. Here’s what will appear in the terminal once the application is deployed and running on the board: As a first part of the application’s functionality, after deployment, when the processor initially starts, a welcome message is sent: Hello, MR-CANHUBK3 here! Please write a message and I will echo back the characters as you type them. In the second part of the functionality, after the initialization phase, the UART terminal automatically transmits ASCII bytes corresponding to whatever is typed in the terminal window. If everything works correctly you will be able to see, being sent back like an echo, the characters that were just typed. In this case: 13780 -> Each typed in character is echoed back! 5. FreeMASTER Model Overview In this chapter we will discuss about the NXP proprietary FreeMASTER tool and how it can be integrated with Model Based Design Toolbox applications. We will build a second Simulink model to demonstrate its capabilities. FreeMASTER is a user-friendly real-time debug monitor and data visualization tool that enables runtime configuration and tuning of embedded software applications. It supports non-intrusive monitoring of variables on a running system and can display multiple variables on oscilloscope-like form or as data in text form. You can download and find out more about it on the NXP website. The FreeMaster blocks can be found under S32K3xx Core, System, Peripherals and Utilities in Utility Blocks: FreeMASTER Config block allows the user to configure the FreeMASTER embedded-side software driver, which implements the serial interface between the application and the host PC. It actually inserts the service in the application, and it is the only one mandatory to be added to the Simulink canvas in order to have the FreeMASTER functionality available. FreeMASTER Recorder block is optional and allows the user to call the Recorder function periodically, in places where the data recording should occur, in our case in the main step function. For this example the only configuration that is needed, is to select the appropriate UART instance, in our case LPUART2, and set the Baudrate to 115200 bps: It is important to mention that the UART instance that is used by the FreeMASTER toolbox cannot be properly used for other communication purposes. The reason for this is that, during initialization, the configuration for the transfer interrupt callbacks as well as the Tx and Rx buffers are changed definitively to be controlled by FreeMASTER. If the above-mentioned blocks would be added in the previously described Simulink model, then only the welcome message would appear in the terminal at initialization phase (after powerup or MCU reset). On the other hand, echoing back the characters that are typed in the terminal window would no longer work. This is not an issue since the terminal can no longer be used anyway. That is because the COM port of the PC is used by the FreeMASTER application, which would prevent any other app from accessing it. For these reasons a new project needs to be created in Simulink for the FreeMASTER example application, but the UART configuration created in chapter 2 can definitely be reused. Similar to the first part of the functionality that was described in chapter 4, FreeMASTER communication protocol is synchronous, using an implementation that resembles the one for the SyncSend function. The execution is blocking the Step Function (I.e., the main execution thread) for as long as it takes to free the transfer buffer, which normally happens instantly unless there is an error (like a broken physical wire). The flags that signal whether the transmission or reception registers are empty or full, respectively, are checked in a do-while loop in interrupts, in case of Long Interrupt Mode (See Mode setting in the FreeMaster configuration tab). To better understand how FreeMASTER works and how it can help development, a dummy variable called counter was created which does nothing more than just store the incrementing value coming from the Counter Limited Simulink block. For the purpose of this example the limit of the block was set to 200, meaning that the counter will reset when the value is reached. It is important to make sure that the compiler will not optimize the code in such a way that this variable could be renamed. If the variable is renamed it is difficult to be found in the associated FreeMaster project which will be described in the following section. Compiler optimizations on certain variables can be avoided by setting their Storage Class to Volatile or Exported Global as shown below: As previously mentioned, what we need to add to the Simulink model are the two FreeMaster blocks Config and Recorder. Here’s a picture with the overall view of the working canvas: Once the FreeMASTER blocks are added in the Simulink model, we can proceed with similar actions to the ones from chapter 4: press the Build button in the Embedded Coder app to generate the corresponding C code from the model, this code is then compiled, the s32k3xx_uart_fm_s32ct.elf file is created  and deployed on the target (MR-CANHUBK3 evaluation board) using J-Link JTAG. The complete application together with the executable files can be found in the second attachment of this article (Article 2 - mrcanhubk344_fm_s32ct). 6. FreeMASTER PC application Up until now, all that we discussed about FreeMASTER was related to the board side of the whole project: UART configuration, implementation of the Simulink model, hardware connections. In what follows we will do the setup for the FreeMASTER application on a Windows PC. For this, we need to install and launch FreeMASTER 3.2 or a later version (as mentioned in chapter 5 , you can download it from the NXP website) We now need to configure the hardware connection that is used for communicating with the board. Under Project – Options… go to Comm tab and choose the corresponding port (as mentioned in chapter 4, you can find out what port your USB-Serial converter uses by looking it up inside Device Manager, under the Ports tab or leave the Port value as COM_ALL for automatic port finding): In order to identify the variables that we want to watch, we need to point to the location where the .elf file is stored. Go to MAP Files tab and choose …\mrcanhubk344_fm_s32ct\mrcanhubk344_fm_s32ct.elf as Default symbol file: We need to create a Variable watch for the counter. For this, simply expand the drop-down list and begin typing the initial letters of the variable’s name: If the update rate of the value is not fast enough, the Sampling period can be decreased: OK, now we have the variable but we need to track its value evolution over time. We could use an oscilloscope for this. Create New Oscilloscope by right clicking on counter in the Watch window: At this point you can press Start communication (the green GO! button). Let it run for a few seconds in order to have it looking like this: FreeMASTER Recorder can be added to the window similarly to the method previously described. Press Start communication (the green GO! Button). The Run/Stop buttons can be pressed at the desired moment for starting or respectively stopping the recording of the specified variable. Time triggers can also be used to replace the button presses. The Simulink implementation can be updated at any point in time as needed. If the two FreeMASTER blocks are active then you should be able to add: multiple variables with the keyword volatile in front (in C code, if you wish to continue working with the generated code) or multiple DataStoreMemory blocks with Volatile Storage Class in Simulink. Then Build the model as usual to be able to monitor the newly added variables in the PC app. After build and deploy are completed, when the FreeMASTER window regains focus on the screen, please make sure to click Yes. This means that the newly created .elf file was automatically detected and the list of symbols needs to be resynchronized: This streamlined approach guarantees efficient variable tracking and management, elevating the debugging experience  and the quality of model-based design. 7. Conclusion The integration of Simulink UART and FreeMASTER blocks in model-based design offers an effective solution for developing and testing embedded systems. The Simulink UART block facilitates communication with external devices using UART protocols, enabling seamless data exchange. Meanwhile, the FreeMASTER tool enhances monitoring and control by providing real-time visualization of variables and parameters. Together, these tools streamline the development process, allowing for efficient testing, debugging, and optimization of embedded systems, ultimately leading to more reliable and robust products.   Instructions on how to run the attached model: Download and extract the archive’s contents; Copy both the .mdl and .mex file to the location where you wish to set up the project; Note: for the model to work properly, please place the .mex file next to the model. Open the .mdl file and make sure that MATLAB’s Current Folder points to the folder that contains the model; Click on the Hardware tab and then press the “Build, Deploy & Start” button.   NXP is a trademark of NXP B.V. All other product or service names are the property of their respective owners. © 2023 NXP B.V. MATLAB, Simulink, and Embedded Coder are registered trademarks of The MathWorks, Inc. See mathworks.com/trademarks for a list of additional trademarks.
記事全体を表示
This video shows: - how to download the Model Based Design Toolbox; - how to generate a license from your account; - how to setup the environment; - quick tour of the toolbox, supported functionalities and available examples;
記事全体を表示
The content of this article is identical to the AN13902: 3-Phase Sensorless PMSM Motor Control Kit with S32K344 using MBDT Blocks
記事全体を表示
This video shows how to build a simple S32K application with NXP's Model-Based Design Toolbox that consists in: Read the SW2 push button state at each 0.1 seconds Switch on/off the Blue LED Record the value of the push button and display its state via serial communication in FreeMASTER
記事全体を表示
In this video we talk about  how hall sensors works, how the commutation sectors are defined based on hall transitions and how can we identify the hall patterns when no datasheet is available.   We discuss about: - Hall sensors - Commutation sectors  - Hall sensors alignment procedure - Hall sensors electronic circuit used on MotorGD and MPC5744P devkits NOTE: Chinese viewers can watch the video on YOUKU using this link 注意:中国观众可以使用此链接观看YOUKU上的视频
記事全体を表示
Four-Part How-To Series Model-Based Design Toolbox (MBDT) is an integrated development environment and toolchain for configuring and generating all the necessary software automatically to execute complex applications. The MBDT includes integrated Simulink® embedded target for NXP processors, peripheral device blocks and drivers, the Math and Motor Control library set, and bit-accurate simulation results. Watch on-demand each of our Model-Based Design Toolbox four-part How-To series and learn the basics of MBDT, also its SPI and CAN communication and its PWM control blocks.   Session 1/4 = Get to Know the User-Friendly NXP MBDT for Application Development in MATLAB/Simulink dumitru-daniel.popa‌ will show you how to configure and use the MBDT, engineered to help you speed up application development in MATLAB/Simulink Environment for NXP hardware. Get to know its main features and capabilities through the creation, simulation, built, deployment, and validation of a basic "hello world" type of application on theS32K144EVB.  Session 2/4 = Introducing the SPI Communication Blocks from NXP MBDT nxf46081‌ will highlight the key aspects of communication in the automotive industry while showing you how to configure and use designated blocks that implement the SPI communication inside the MATLAB/Simulink Environment for creating a quick and easy data transfer application using MBDT and the S32K144EVB. Session 3/4 = Introducing the CAN Communication Blocks from NXP MBDT constantinrazvan.chivu‌ will highlight the key aspects of communication in the automotive industry while showing you how to use MBDT and the S32K144EVB to simplify CAN applications with only a few blocks: configuration, transmit, and receive. Session 4/4 = Introducing the PWM Control Blocks from NXP MBDT mariuslucianandrei‌ will showcase how to start using PWM, its features and functionalities while showing you how to build a first application able to generate different types of PWM signals using MBDT and the S32K144EVB; also, learn to sample the external signals to determine the key values: duty-cycle, period, among others.   Your software development processes can speed up by using the free-of-charge NXP Model-Based Design Toolboxes for MATLAB and Simulink development environments, providing full integration, an out-of-the-box configuration, and action blocks for basic/advanced features for designing complex automotive solutions.
記事全体を表示
In this video we discuss about power stage (DevKit MotorGD) configuration that involves the configuration and initialization of the MC34GD3000 FET pre-driver via SPI commands and the setup of the FlexPWM peripheral to generate PWM commands to the inverter MOSFETs via pre-driver MC34GD3000.   We discuss about: - Pre-driver MC34GD3000 initialization sequence; - Pre-driver MC34GD3000 programming via SPI; - How to configure and test the FlexPWM peripheral; - How to test and validate the SPI communication between MPC5744P and MC34GD3000; NOTE: Chinese viewers can watch the video on YOUKU using this link 注意:中国观众可以使用此链接观看YOUKU上的视频
記事全体を表示
General Tip of the day Tip of the day  Licensing MBDT license missing error  Toolbox functionality Registers, Linkers not displaying options  Profiler/Execution S32k144 Simulation Time and Profiler  Peripherals How to put MCU into sleep? Apps Motor Control
記事全体を表示