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

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

NXP Model-Based Design Tools Knowledge Base

ディスカッション

ソート順:
 1. INTRODUCTION    This article presents how to use NXP’s Model-Based Design Toolbox (MBDT) to implement an Air Quality Monitor that integrates multiple sensors, which will be configured to run on the 3S32K144 EVB.    The Model-Based Design Toolbox offers a solution for deploying complex applications on NXP hardware directly from Simulink. It incorporates hardware-optimized software, including drivers, libraries, and tools, allowing users to concentrate solely on algorithm development. The toolbox manages the hardware integration, ensuring the applications are hardware-aware. By integrating with the MathWorks ecosystem, the Model-Based Design Toolbox leverages the model-based design paradigm. This enables a programming process based on models, where users create logical diagrams using Simulink blocks for dedicated functions, eliminating the need to write C code for their designs.     This article aims to show how this tool can be used for designing and deploying on an S32K144 Evaluation board an air quality monitor application. Therefore, the steps meant to accomplish this are parted in the following sections:       II. General purpose – what is the aim of the application;       III. Application overview – how the application works and how the sensors are integrated;      IV. Hardware design – the description of the components used;       V. Software design – the execution flow of the application and the model implementation explained in detail;      VI. Conclusion – results of the application.    2. GENERAL PURPOSE    This application shows how easily an Air Quality Monitor can be implemented when using the MBD toolbox for S32K1xx, which helps the users simplify their job by providing the means to use a graphic and visual way to put their idea into use and generate the C code from it, which will be uploaded on the EVB.    3. APPLICATION OVERVIEW     The application displays in FreeMASTER the values of temperature, humidity, dust density, pressure, and the values of eCO2 and TVOC. Those values are read from the sensors connected to the EVB and computed using the algorithms from the libraries corresponding to each sensor, such as Adafruit’s libraries for BMP280 and CCS811, Sparkfun library for HTU21D and the GP2Y1010AU0F library, which are then adapted in Simulink logic. The application will be split into four subsystems, each covering a sensor and its algorithm.    BLOCK DIAGRAM                                                        Figure 1: Block Diagram     4. HARDWARE DESIGN          4.1. Hardware components   The required components for this application are:  S32K144 Evaluation Board  HTU21D, temperature and humidity sensor CCS811, eCO2 and TVOC sensor  BMP280, pressure sensor  GP2Y1010AU0F, dust density sensor          1) S32K144 Evaluation Board  The S32K144EVB is a low-cost evaluation and development board for general-purpose industrial and automotive applications. The board represents the main part of the application as it collects the data from the sensors and applies the algorithm to compute the values shown in FreeMASTER.  For more information about the board, access the following NXP page.      2) Temperature and humidity sensor HTU21D  The HTU21D is an easy-to-use, digital sensor for measuring humidity and temperature levels. It utilizes the I2C communication protocol, making it suitable for various applications, such as an Air Quality Monitor.     3) eCO2 and TVOC sensor CCS811  The CCS811 sensor precisely monitors indoor air quality, measuring TVOCs and carbon dioxide levels in real time. Using the I2C communication protocol, it is easily integrated into air quality monitor applications.     4) Pressure sensor BMP280  The BMP280 sensor accurately measures atmospheric pressure using the I2C communication protocol.     5) Dust density sensor GP2Y1010AU0F  The GP2Y1010AU0F sensor is utilized for the measurement of dust density with high precision. Utilizing an analog output mechanism, it delivers reliable data for comprehensive air quality assessments.       4.2. Electrical schematic    Apart from the components described above (HTU21D sensor, CCS811 sensor, BMP280 sensor and GP2Y1010AU0F sensor), a resistor and a capacitor will be needed.   The following electrical schematic is an example of how the sensors can be connected:                                                             Figure 2: Electrical schematic    5. SOFTWARE DESIGN        5.1. Prerequisite software  To be able to follow the next steps presented in this article, the following software will be necessary:  Matlab® and Simulink® (2021a or newer), including Stateflow ®, MATLAB® CoderTM, Simulink® CoderTM, Embedded Coder®  NXP Support Package S32K1xx         5.2. Model overview   The application uses the Simulink environment to implement the algorithms for computing the data read from the sensors connected to the S32K144 EVB. The model is organized into two big sections: initialization and sensors’ algorithms. For the sensors part, each sensor has its subsystem where the algorithm is implemented.                                                     Figure 3: Application’s model        5.3. INITIALIZATION  The initialization holds the blocks required for our model to work. On the first line, from left to right, the following can be found:        1) The Configuration block for S32K1xx processor family. The required settings of the processor configuration block are the default ones, except for the processor family and the download interface.                           Figure 4: Configuration block for S32K1xx family of processors        2) The LP2IC Configuration block. Here the functioning mode (master or slave) can be changed, and the pins used for communication can be chosen. This application has three sensors that use this communication protocol:  BMP280, whose address is 0x76  CCS811, whose address is 0x5A HTU21D, whose address is 0x40                                            Figure 5: Configuration block for LPI2C        3) The FreeMASTER configuration block. Here the communication interface, the baud rate, and long interrupt serial communication can be set. This component facilitates communication between the S32K144 EVB LPUART1 instance and the FreeMaster tool, via the microUSB serial port.                                Figure 6: Configuration block for FreeMASTER        4) The configuration block for ADC. The ADC converter number and the resolution mode can be selected from here.     Figure 7: Configuration block for ADC    On the second line, the data stores for the variables used in this project can be found. The data type and size for the data stores can be found in the following table:     VARIABLE NAMES  DATA TYPE  SIZE / DIMENSION  SENSOR  aux_temp  uint8  3  BMP280  aux_press  uint8  3  BMP280  BMP280_Temp  uint8  6  BMP280  BMP280_Press  uint8  18  BMP280  BMP280_T  uint16  1  BMP280  BMP280_T2  int16  2  BMP280  BMP280_P  uint16  1  BMP280  BMP280_P2  int16  8  BMP280  raw_press  int32  1  BMP280  raw_temp  int32  1  BMP280  Pressure  double  1  BMP280  buf  uint8  8  CCS811  TVOC  uint16  1  CCS811  eCO2  uint16  1  CCS811  temperature  double  1  HTU21D  humidity  double  1  HTU21D  hum_raw  uint16  1  HTU21D  temp_raw  uint16  1  HTU21D  humcomp  default  default  HTU21D  dustDensity  default  default  GP2Y1010AU0F    Figure 8: Variables    Note! It is important, for the variables to be visible in FreeMASTER, to go to Apps -> Embedded Coder -> Code Interface -> Default Code Mappings -> Data Stores and set all the variables to Volatile.    Figure 9: Embedded Coder selection    Figure 10: Default Code Mappings        5.4. ALGORITHM   The second part of the model consists of every sensor’s subsystem. In each subsystem, the necessary algorithm for computing the data is implemented.   Let’s look at every subsystem and algorithm.        5.4.1. BMP 280 Pressure sensor   For this sensor’s initialization, BMP280_Temp and BMP280_Press will  be used. Top down, five subsystems can be found: Global Initialization Sensor, Temp Calib, read16LE – temp, Press Calib, read16LE – press.     Figure 11: BMP280 subsystems    The purpose of the Global Initialization Sensor is to prepare the sensor for subsequent data reading. This involves transmitting specific data to the sensor using the LPI2C Master Transmit block. These data include values such as 0xF5 and 108, as well as 0xF4 and 111, which serve to configure and calibrate the sensor for upcoming tasks. Having multiple sensors connected using I2C communication protocol, the way the sensor can differentiate between them is by their address. Therefore, the data will be sent to the 0x76 address, which corresponds to the address of the pressure sensor.  Figure 12: Pressure sensor initialization    In Temp Calib subsystem, data is read from the temperature's memory location and placed into the BMP280_Temp data store mentioned earlier. The addresses from which data needs to be read are sequential, so reading begins from the 0x88 address and 6 bits of data are requested, resulting in reading from address 0x88 to address 0x8C inclusively.  Figure 13: I2C Master Multi Transfer    In read16LE – temp subsystem, the add operation is utilized to perform an OR bit operation for calibrating the data and placing it into the BMP280_T data store and the BMP280_T2. LE stands for Little Endian.    Figure 14: Temperature data calibration    For the Press Calib and read16LE – press subsystems, the same operations described previously are performed, but for a greater number of bits. After the initialization is completed, the Else subsystem is entered, where the computing takes place. An auxiliary temperature is computed, which is required for the pressure's formula. For this purpose, the data store named aux_temp will be used. Within this subsystem, there are 2 further subsystems: READ TEMP REGISTER and RAW TEMP.  In READ TEMP REGISTER, data is read from the 0xFA address using an LPI2C Master Multi Transfer, and 3 bits of data are transferred into the aforementioned aux_temp data store.  In RAW TEMP, the raw_temp necessary for the pressure calculation formula is computed.  Similar to the temperature calculation, the pressure calculation data is read from the 0xF7 address into the data store named aux_press, and then the raw_press required for the formula is computed.  For the actual computation of the pressure, an S-Function block with C code inside is utilized, where the algorithm found in the Adafruit Library for BMP280 is included. [1] [functions float Adafruit_BMP280::readTemperature() and float Adafruit_BMP280::readPressure()].  Figure 15: convertPressure S-Function         5.4.2. CCS811 TVOC & eCO2 sensor  For this sensor, during initialization, the same procedure as before is followed: specific data is sent to the sensor using the LPI2C Master Transmit to notify it of the upcoming data reading. Specifically, the predefined data 0xF4 and 0x01, 16 is now transmitted.   Figure 16: Initialization for eCO2 and TVOC sensor    In the Else subsystem, 8 bits of data are read and placed into the buf variable using the LPI2C Master Multi Transfer block. Subsequently, after the necessary data is retrieved from the sensor, the required values are computed, with their formulas sourced from the Adafruit Library for the CCS811 sensor [2]:  _eCO2 = ((uint16_t)buf[0] << 😎 | ((uint16_t)buf[1]);  _TVOC = ((uint16_t)buf[2] << 😎 | ((uint16_t)buf[3]);    Figure 17: Compute data for eCO2 and TVOC values        5.4.3. Humidity & Temperature subsystem  For this sensor, another library [3] will be utilized to obtain the necessary formulas and the algorithm. Initially, for both temperature and humidity readings, the LPI2C Master Multi Transfer block will be employed to retrieve the required values. Specifically, the command to trigger temperature readings is 227, and for humidity, it is 229. Each reading will consist of 3 bits, from which only the most significant bit and the least significant bit will be utilized for temperature and humidity, respectively.  For both of them, the raw values need to be computed. The formulas needed are:  For temperature:  uint16_t rawValue = ((uint16_t) msb << 😎 | (uint16_t) lsb;  temp_raw = rawValue & 0xFFFC;       2. For humidity:  uint16_t rawValue = ((uint16_t) msb << 😎 | (uint16_t) lsb;  hum_raw = rawValue & 0xFFFC;    The temperature is computed using the following formula:  Temperature = temp_raw * (175.72 / 65536.0) – 46.85;    Figure 18: Temperature computing    The humidity is computed using the following formula:  Humidity = (-6) + 125 * (hum_raw / 65536.0) + (25 – Temperature) * (-0.15);    Figure 19: Humidity computing    Figure 20: Temperature and humidity subsystem        5.4.4. Dust Pm2.5 subsystem  For this final sensor, an additional library [4] will be employed to implement our model-based design algorithm for measuring and computing the PM2.5 levels in our surroundings.   In this scenario, the GPIO Write block will be utilized to activate and deactivate the infrared LED on the sensor. Following activation, a 0.28ms delay will be introduced before employing the ADC to read the data, which will then be computed using the provided formula:  dustDensity = (170 * 5 / 1024 – 0.1) * Voltage      Figure 21: Formula applied for dust density    After applying the above-mentioned formula, another delay of 0.04ms will be used and then the LED will be turned off.    Figure 22: Dust Pm2.5 subsystem         5.5. FREEMASTER  To visualize the results from the application, a FreeMASTER project can be created. Once created, the .elf file of the built application can be added by navigating to Project -> Resource files -> "pack" directory setup -> MAP Files -> Default symbol file.  Variables can be added to the Variable Watch section. For this project, the most important ones are Pressure, eCO2, TVOC, humidity, temperature, and dustDensity.    Figure 23: Variable watch section        5.6. HARDWARE SETUP  A possible example for hardware setup is represented in the below picture:  Figure 24: Hardware setup    6. CONCLUSION    The application covers the steps of developing an air quality monitor that monitors how the pressure, TVOC, eCO2, humidity, temperature, and dust density evolve in a room, using the Model-Based Design Toolbox for S32K1 MCUs. It can be a good academic study for how to use the S32K1XX EVB and sensors using the MBDT and for how to adapt C code and use it in a graphic programming environment such as Simulink to simplify your work.      Bibliography:   [1] https://github.com/adafruit/Adafruit_BMP280_Library  [2] https://github.com/adafruit/Adafruit_CCS811  [3] https://github.com/sparkfun/SparkFun_HTU21D_Breakout_Arduino_Library  [4] https://github.com/mickey9801/GP2Y1010AU0F       NXP is a trademark of NXP B.V. All other product or service names are the property of their respective owners. © 2024 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.   
記事全体を表示
1. Introduction   This article demonstrates how to control a 4-wire server fan based on temperature or user input, using the Model-Based Design Toolbox for S32K1 MCUs. The Model-Based Design Toolbox represents a solution which allows the complex applications deployment on NXP hardware directly from Simulink. By incorporating hardware optimized software, such as drivers, libraries, and tools, the Model-Based Design Toolbox allows the users to focus only on the algorithm development, while making such applications hardware-aware is handled by the toolbox. By the integration with the MathWorks ecosystem, the MBDT leverages the model-based design paradigm, thus enabling a programming process based on models - users to not need to write C code for implementing their designs, but create logical diagrams using Simulink blocks performing dedicated functions. In this article, we will demonstrate how this tool can be used for designing and deploying on an S32K146 Evaluation board a fan speed control application. Thus, the steps proposed for achieving this are described thorughout the article, in the following sections: II. Application overview – how the application works and the links between the components; III. Hardware design – the description of the components used and the electrical diagram; IV. Software design – the application execution flow and the model implementation explained in more detail; V. Conclusion – the results of the application.   2. Application overview   The application has 2 operating modes: automatic and manual. To switch between operating modes, we need to press the SW2 button on the S32K146 board. When starting, the application is in automatic operating mode (the RGB LED of the board lights up green): this means the fan adjusts its speed according to temperature. In manual mode (the RGB LED of the board lights up blue), the fan changes its speed depending on the value supplied by the potentiometer. The graphs and values of fan speed, acceleration, ambient temperature will be displayed in FreeMASTER. Block diagram   Figure 1: Block diagram   3. Hardware design   A. Hardware components The required hardware components are:  S32K146 Evaluation board  Thermistor NTC100K  4-wire PC fan   12V power supply AC-DC.   1) S32K146 Evaluation board The S32K146EVB serves as an affordable evaluation and development board designed for a wide range of industrial and automotive uses. The board is the “brain” of the application, as it collects data from various sensors (e.g.: temperature sensor) and uses the algorithm to regulate the actuators (e.g.: the BLDC motors found in fans).  For more information about the board, please read from here.   2) Thermistor NTC100K A thermistor is a resistor whose resistance is dependent on temperature. The temperature value is calculated using the Steinhart-Hart equation. The Steinhart-Hart coefficients A, B, C vary depending on the type and model of thermistor and the temperature range of interest. To find these coefficients, we use three values of resistance data for three known temperatures. For example, from NTC100K Thermistor Datasheet we get for the temperatures of 15℃, 25℃ and 45℃, corresponding resistance values of 156407 Ω, 100000 Ω and 43659 Ω. It results, according to the equation (2), that the coefficients have the following values:  So, the steps to determine the temperature are to get the thermistor resistance using a voltage divider converter along with an analog-to-digital converter (ADC) and calculate the temperature from the resistance.    3) 4-wire PC fan The fan has 4 pins, being used especially for processors with high power consumption. The simplest fan has 2 pins, one for power and one for ground. The 3-wire fan has an extra pin called “tachometer”, which indicates the speed of the fan (one/two impulses are received for each rotation). With 2-wire and 3-wire fans, the speed is controlled by increasing/decreasing the voltage on the power pin. Instead, the 4-wire fan has a control pin and uses PWM (Pulse Width Modulation) to control the speed.  Before using the fan, we must find out information such as the maximum speed, the number of impulses per rotation given by tachometer and the minimum operating speed if necessary. These things can be looked up in the fan’s datasheet or can be determined experimentally if we have an unknown fan, and we cannot find its datasheet.  The values of the fan used as an example in this article were determined experimentally and we got an approximate maximum speed of 300 rotations per second (18000 rpm), two impulses per rotation and a minimum operating speed of 80 rotations per second (4800 rpm).    4) 12V power supply AC-DC The power supply converts alternating current (AC) electrical energy into direct current (DC) electrical energy with an output voltage of 12 volts. In our application, it will supply the power for the fan.   B. Electrical schematic There are multiple hardware configurations for the fan speed control application. We will use, in addition to the hardware components mentioned above (fan, 12V power supply, thermistor), the potentiometer, the SW2 button and the RGB LED of the S32K146EVB.  We propose the following electrical schematic:  Figure 2: Electrical schematic Note! It is important that all components are connected to the same ground.   C. Hardware setup A possible hardware setup may look like in the following picture:  Figure 3: Hardware setup example   4. Software design   A. Prerequisite software To be able to follow the next steps in this article, the following software is necessary: MATLAB ®  and Simulink ®  (2021a or newer), including Stateflow ® , MATLAB ®  Coder TM , Simulink ®  Coder TM , Embedded Coder ® Model-Based Design Toolbox for S32K1xx 4.3.0   B. Flow chart The application execution flow is based on a state machine, according to the following diagram. Figure 4: State machine The architecture of the application is a closed-loop system, which uses a feedback signal to adjust the fan speed. The current fan speed and the fan acceleration update their values with each tachometer pulse. The difference between the reference speed (set using temperature or potentiometer) and the current speed, alias error signal, is the input to the closed-loop control system, such as a proportional-integral-derivative (PID) controller. The PID controller applies a correction based on proportional, integral, and derivative coefficients to a control function, in our case, it determines the PWM duty cycle to control the fan speed.  Figure 5: Application's model   C. Model Overview From top to bottom (Figure 5), we have 4 big sections:  Initialization Switching between operating modes The operating modes which set the reference speed The control algorithm. Let’s take each section to dive further into the details.    1) Initialization  Figure 6: Initialization section We have on the first line, from left to right, the Configuration block for S32K1xx processor family, the FreeMASTER Configuration Block and two ADC Configuration Blocks. On the second line, we have the pull-up resistance on the tachometer pin and two mapping functions from the temperature value and the ADC potentiometer value to the reference speed. Also, there are variables for current operating mode, temperature value, reference speed, current speed, duty cycle and some other auxiliary variables.  The required configurations of the processor configuration block are the default ones, except for the processor model and the download interface (Figure 7).  For the FreeMASTER configuration block, we set the communication interface (e.g.: LPUART1), the baud rate (e.g.: 19200) and long interrupt serial communication. This component provides an interface where relevant data such as current speed, ambient temperature and many others are displayed. In the ADC configurations blocks, used for reading temperature and potentiometer value, we select the ADC converter number and the resolution mode (e.g.: 10-bit conversion).   Figure 7: Configuration block for S32K1xx family of processors   2) Switching between operating modes We configure the pin PTC12 (SW2) to generate a falling edge interrupt on each button press, using the GPI ISR block. Figure 8: Switching mode section When an interrupt is generated, the value of the operation mode variable is toggled and the color of the LED corresponding to the operating mode lights up (automatic mode – green, manual mode – blue). It also enables/disables the PIT (Periodic Interrupt Timer) interrupt which triggers the ADC reading of the temperature sensor at each one second (Figure 10).  Figure 9: The function called when the interrupt is generated.  Figure 10: Enable/disable PIT interrupt for ADC temperature reading; RGB LED in Automatic & Manual mode   3) Operation modes  Figure 11: Operation modes section Depending on the operating mode, the reference speed is set by the temperature value or the ADC value of the potentiometer. a) Automatic mode In this mode, the PIT block is enabled, and the ADC value of the thermistor is read once per second. The resolution of the ADC is 10 bits. So, it can take values between 0 and 1023, which corresponds to voltage values between 0V and 5V. Let’s assume Vout is the output voltage on the pin PTB13. Also, according to the electrical schematic from Figure 2, we have a voltage divider: We can find out the value of thermistor resistance: And then, we can get the temperature value using the Steinhart-Hart equation (1).  Based on the temperature, we can map a value for reference speed. We can define for this mapping a linear function or whatever we need.  Figure 12: Automatic mode   b) Manual mode In manual mode, the ADC value of the potentiometer is read and mapped to reference speed.  Figure 13: Manual mode   4) The control algorithm  Figure 14: The control algorithm section In this section, the closed loop of the system is implemented using the PID (Proportional-Integral-Derivative) controller. We must tune the coefficients of the PID controller (Kp, Ki, Kd) to produce the optimal control function. There are several methods for tuning: manual, Ziegler-Nichols or using software specialized tools. For this application, the Ziegler-Nichols method was used, and, for fine adjustment, manual tunning was applied. After applying this method, we get the following values: KP = 0.003, KI = 0.003, KD = 0.001.  Figure 15: PID controller configuration With the PWM signal from the PID controller, we control the fan speed via the PWM pin, using the FTM PWM Config block. We configure the block as follows:  Figure 16: Parameters of FTM PWM Config block According to the electrical schematic (Figure 2), the pin used to control the fan speed is PTC1, which corresponds to FTM0_CH1. This means we need to configure the channel 1 from the module 0 of FTM (FlexTimer Module). To get the fan current speed, we need to know the period between two pulses from the tachometer. This can be determined using the FTM Input Capture block, which returns the timestamp in microseconds. Remember that there are two pulses per rotation. We measure the speed once every 10 milliseconds. So, the acceleration has the following value:  Figure 17: Calculation of fan speed and acceleration   D. FreeMASTER To visualize the results of the application, you can create a FreeMASTER project. Add the .elf file of the built application to Project – Resource files – “pack” directory setup – MAP Files – Default symbol file. You can add variables to the Variable Watch section, such as operation mode, current speed, reference speed, temperature (Figure 19). Also, you can create a graph, as in Figure 18, using the FreeMASTER oscilloscope with the current speed and reference speed. In the following figure, we can observe that the system is initially in automatic mode: temperature is about 28 Celsius degrees, which corresponds to an approximate reference speed of 110 rotations per seconds. Then, when SW2 button is pressed (at second 685 on the graph), the system goes into manual mode and the reference speed is set about 236 rotations per second, which is mapped according to the value read from the potentiometer. The current speed (red line) is tracking the reference speed imposed (green line).  Figure 18: Graphic with reference speed and current speed Also, we can track values such as operation mode - boolean value (0 for automatic mode and 1 for manual mode), temperature in Celsius degrees, reference speed and current speed measured in rotations per second, acceleration or the PWM duty cycle used for controlling the fan speed.  Figure 19: Variable watch section   5. Conclusion   In conclusion, the application consists in controlling the fan speed depending on the temperature or the potentiometer value, using the Model-Based Design Toolbox for S32K1 MCUs. It combines notions from systems theory, electronics, and embedded systems, representing an academic study on the use of fans for temperature control in different applications like servers, routers, switches, etc.   Useful links:   1. S32K146EVB:   https://www.nxp.com/document/guide/getting-started-with-the-s32k146-evaluation-board-for-general-purpose:NGS-S32K146EVB  2. NTC100K Thermistor: https://www.tme.eu/Document/f9d2f5e38227fc1c7d979e546ff51768/NTCM-100K-B3950.pdf  https://en.wikipedia.org/wiki/Steinhart%E2%80%93Hart_equation#Steinhart%E2%80%93Hart_coefficients  3. 4-wire fan:  https://www.electroschematics.com/4-wire-pc-fan/  https://www.nidec.com/en/product/search/category/B101/M111/S100/NCJ-V40S-E5-57/  4. PID coefficients:  https://control.com/textbook/closed-loop-control/p-i-and-d-responses-graphed/  https://en.wikipedia.org/wiki/Proportional%E2%80%93integral%E2%80%93derivative_controller    NXP is a trademark of NXP B.V. All other product or service names are the property of their respective owners. © 2024 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.  
記事全体を表示
  Product Release Announcement Automotive Processing NXP Model-Based Design Toolbox for S32M2xx – version 1.0.0 RTM   The Automotive Processing, Model-Based Design Tools Team at NXP Semiconductors, is pleased to announce the release of the Model-Based Design Toolbox for S32M2xx version 1.0.0. This release supports automatic code generation for S32M2xx peripherals and applications prototyping from MATLAB/Simulink for NXP S32M2xx Automotive Microprocessors. This new product adds support for S32M41, S32M242, S32M43,  S32M244, S32M274, S32M276 MCUs and part of their peripherals, based on RTD MCAL components (ADC, AE, DIO, CAN, DPGA, GDU, GPT, MCL, PWM, MCU, PORT, QDEC, UART). In this release, we have also added support for FreeMASTER, AMMCLib, and MATLAB support for the latest versions. The product comes with over 60 examples, covering all supported peripherals, and Simulink simulation modes Software-in-the-Loop, Processor-in-the-Loop, and External Mode.   Target audience: This product is part of the Automotive SW – S32M2 Standard Software Package.   FlexNet Location: https://nxp.flexnetoperations.com/control/frse/download?element=3785898   Technical Support: NXP Model-Based Design Toolbox for S32M2xx issues will be tracked through the NXP Model-Based Design Tools Community space. https://community.nxp.com/community/mbdt     Release Content Automatic C code generation from MATLAB® for NXP S32M2xx derivatives: S32M241 S32M242 S32M243 S32M244 S32M274 S32M276   Support for the following peripherals (MCAL components): ADC AE DIO CAN DPGA GDU GPT MCL PWM MCU PORT QDEC UART   Provides 2 modes of operation: Basic – using pre-configured configurations for peripherals; useful for quick hardware evaluation and testing Advanced – using S32 Configuration Tool or EB Tresos to configure peripherals/pins/clocks   Integrates the Automotive Math and Motor Control Library version 1.1.34: All functions in the Automotive Math and Motor Control Functions Library v1.1.34 are supported as blocks for simulation and embedded target code generation.   Integration with FreeMASTER We provide several Simulink example models and associated FreeMASTER projects to demonstrate how our toolbox interacts with the real-time data visualization tool and how it can be used for tuning embedded software applications.   Support for MATLAB® versions R2021a R2021b R2022a R2022b R2023a R2023b   Support for custom board initialization Toolbox generates the components’ peripherals initialization function calls as configured in the Board Initialization window, which can be customized to each Simulink model. This feature allows users to set a custom order for the components initialization, the insertion of the Custom code sequences, or share the custom initialization with multiple Simulink models via the Export and Import functionality.       Support for custom default project configuration The toolbox provides support for users to create their custom default project configurations. This could be very useful when having a custom board design – only needing to create the hardware configuration once. After it is saved as a custom default project, it can be used for every model that is being developed.     Integration with S32 Config Tools version v1.7:       Integration with S32 Design Studio The toolbox automatically generates the <model_name>_Config folder, next to the Simulink model location, providing the user the opportunity to easily import the generated code from Simulink into S32 Design Studio. Each time the code is generated, the <model_name>_Config folder is updated with the new changes. The toolbox also provides a mechanism to launch an S32 Design Studio instance, with the imported generated code project in the Project Explorer tab from S32DS.   Simulation modes: We provide support for the following simulation modes (each of them being useful for validation and verification): Software-in-Loop (SIL) Processor-in-Loop (PIL) External mode   Support for profiling in PIL mode:   Examples for every peripheral/function supported: We have added over 60 examples, including: CDD Blocks (Ae, Dpga, Gdu, Mcl, Qdec) Communication (Can, Uart) AMMCLib IO Blocks (Adc, Dio, Pwm) ISR Blocks (Hardware Interrupt Handler) MCAL Blocks (Gpt) Utility Blocks (FreeMASTER) Software-in-the-Loop / Processor-in-the-Loop / External mode   For more details, features, and how to use the new functionalities, please refer to the Release Notes document attached.   MATLAB® Integration The NXP Model-Based Design Toolbox extends the MATLAB® and Simulink® experience by allowing customers to evaluate and use NXP’s S32M2xx MCUs and evaluation board solutions out-of-the-box with: Model-Based Design Toolbox for S32M2xx version 1.0.0 is fully integrated with MATLAB® environment in terms of installation:     Target Audience This release (1.0.0) is intended for technology demonstration, evaluation purposes, and prototyping of S32M2xx MCUs and Evaluation Boards.   Useful Resources Examples, Training, and Support: https://community.nxp.com/community/mbdt      
記事全体を表示
1. Introduction This is the fourth article in the Beginner’s Guide series and it aims to showcase how to configure the CAN peripheral to be able to send and receive CAN messages over the CAN Bus using the MR-CANHUBK344 Evaluation Board. For more details about the MR-CANHUBK344 board or step-by-step instructions on how to run a Simulink ® model on it using MBDT, please check out the first article in the series: Interacting with Digital Inputs/Outputs on MR-CANHUBK344. This article’s application consists of reading digital and analog inputs, processing them before they are sent across the CAN Bus from one CAN instance to another, and then controlling digital and analog outputs based on the received message. 1.1. Extra Prerequisite Software On top of the requirements from the first article, the application that we are developing in this article requires the Vehicle Network Toolbox TM from MathWorks. 1.2. Optional Hardware In this article we are going to show the messages that are sent across the CAN Bus using a device that can interact with the CAN Bus. The specific model we are using is the PCAN-USB Pro FD. 2. CAN Configuration This chapter will focus on the changes that have to be made in the configuration project in order for the board’s components to communicate properly with each other. It will focus mainly on the CAN-related settings, as the settings for the DIO, ADC and PWM have been explained in the previous articles. 2.1. Hardware Connections The MR-CANHUBK344 board has 6 CAN instances, with 3 different transceivers among them. CAN0 and CAN1 use TJA1443ATK, CAN2 and CAN3 use TJA1463ATK and CAN4 and CAN5 use TJA1153. Each of the CAN instances has 2 identical connectors, wired to each other, labelled A and B, to allow for daisy chain wiring. In this article we will focus on communicating between the CAN0 and CAN1 instances. Note: A CAN bus usually requires 60 Ohm termination at both ends of a CAN bus. This may be accomplished using one of the included CAN Term boards. For a CAN instance to work properly, the unused connector (if there is one) has to be connected to a CAN Term board, which is included in the MR-CANHUBK344 package. Below you can find a schematic that shows how the CAN0 instance is connected to its transceiver and how the signals are routed between them: 2.2. Pins Configuration The pins for the CAN instances can be found by searching for the component name inside the schematic. For this article’s purpose, I have extracted the necessary pins below. The _RX and _TX pins are linked directly to the CAN instance, while the _ERRN, _STB and _EN pins correspond to the transceiver associated to the CAN instance, like illustrated in the schematic above. To start configuring the pins, we have to open the Pins Tool, inside the S32 Configuration Tools. To quickly open the configuration project for a model, you can click on the Configure button from the window that appears when double-clicking a MBDT Block. Once the software has opened, clicking the Pins button will open the  Pins Tool. Inside the Pins Tool, we will focus on the top-left window, called the Pins tab. First, we check if the pin we are trying to add already exists in the configuration by typing the name in the search bar. Here we can see that no other pin is configured for this purpose (by the lack of green checkmarks in the box to the left). This has to be done for every of the 12 pins that we are configuring. This process has been showcased in detail in the first article, Interacting with Digital Inputs/Outputs on MR-CANHUBK344. Here is a case where the pin already exists. The steps that have to be taken in order to remove the old configuration consist of clicking the green checkmark, and then unchecking the currently selected option in the window that pops up. After checking every pin, we can start adding the ones we want to configure. Note: CAN_RX, CAN_ERRN are inputs, while CAN_TX, CAN_STB and CAN_EN are outputs. The CAN_STB and CAN_EN are outputs because we will set appropriate values to them to initialize the transceiver by switching it into the normal operating mode, while the CAN_ERRN is an input because it is used to inform the MCU about possible problems that can take place when initializing the transceiver. To do that, we type the pin’s value in the search bar. As an example, let’s look at some of the pins that we are configuring: The LED_CAN0 pin is connected to a red LED placed near the CAN connector which is used separately from the CAN, similarly to any other LED on the board. It also shares the same inverted logic as the other LEDs. It has the corresponding value PTC18, which we type in the filter. Afterwards, we populate the Identifier and Label fields with the pin’s name. Then we click the checkmark to the left and select the appropriate option in the window that shows up. Here, the for the LED we select the SIUL2:gpio,82 option. Since we are configuring an LED, which is an output, we also select the Output option in the window that asks for the pin’s direction. The process is similar for the other pins, but keep in mind that when configuring the CAN_RX and CAN_TX pins, you have to choose another signal from the list of available signals. Given the difference between the pins we are configuring, the CAN_ERRN, CAN_EN and CAN_STB are connected to the SIUL2 peripheral as inputs/outputs, while the CAN_RX and CAN_TX are connected to their respective CAN peripheral. Here is how that looks for the CAN0_RX pin: This is how the signals for the CAN0 and CAN1 instances look after being configured: To be able to see the signals in a similar manner, you can type “CAN” in the search bar of the bottom window, called Routing Details. Next, we have to return to the Peripherals Tool by clicking the highlighted button.   2.3. Component Configuration 2.3.1. CanController To start configuring the CAN instances, the first step is to open the Can_43_FlexCAN component and navigate to the CanController tab, inside the CanConfigSet panel. Here we are going to configure the two CAN controllers that correspond to the CAN0 and CAN1 instances. The CanController section provides all the necessary settings to configure a CAN controller instance, as required by the application.  You can expect to interact with some of them more frequently than the rest, so we are focusing on explaining what these do. The Name field controls the name that is associated to the controller and it is used to reference the controller in other menus. Can Hardware Channel controls which physical CAN instance is connected to the current controller. The Can Controller Activation checkbox enables the Can Controller. Without it, the controller does not function. CAN Rx/Tx Processing Type enables/disables read and write operations through Can_MainFunction_Read(), respectively Can_MainFunction_Write(), for handling PDU (Protocol Data Unit) events while set to polling. If the parameter is set to POLLING or MIXED, then the functions mentioned will be polling for RX Indication or TX Confirmation. If the parameter is set to MIXED, then only the hardware objects which have the attribute CanHardwareObjectUsesPolling set to true will be affected. Alternatively, if the parameter is set to INTERRUPT, Can FD ISO controls whether the Flexible Data-Rate feature is enabled on the Controller. In this example, we use the Can FD protocol for communicating between CAN instances so it will be checked. The Can Controller Default Baudrate field is responsible for choosing which Baudrate configuration to assign to the controller. The Baudrate configuration will be presented in the following screen. CanCpuClockRef allows you to select the reference clock. For the CAN peripheral, there are 2 clocks available, FLEXCAN_PE_CLK0_2 and FLEXCAN_PE_CLK3_5, covering the CAN0, CAN1, CAN2 and CAN3, CAN4, CAN5 respectively. These clocks can be configured inside the Mcu component, which will be shown in the following chapters. The Name field is used to select it in the Can Controller Default Baudrate field from the previous screen. Can Automatic Time Segments Calculation can be used to automatically set the Can Propagation Segment, Can Phase Segment 1 and Can Phase Segment 2 according to the Bitrate and the Can Controller Prescaler. Can Controller Prescaler sets the prescaler for the controller, based on the Clock selected. Can Controller BaudRate (Kbps) controls the speed that the data is transferred at. In the following section, containing Can Propagation Segment, Can Phase Segment 1 and Can Phase Segment 2 you can configure the timings of the CAN transfer. And finally, in the bottom section you can configure the timings for the Flexible Data-Rate protocol, by changing the Can FD Controller Baudrate, Can FD Propagation Segment, Can FD Phase Segment 1, Can FD phase Segment 2, Can FD Resynch Jump Width and Can FD Prescaler. These can be seen as FD equivalents for the previous settings. The first section allows you to configure the CanRamBlock associated with the current Can Controller. A CAN controller’s CAN RAM contains CAN hardware objects defined as a PDU buffer. The CAN RAM block can store message buffers in different configurations of sizes. According to the S32K3XX reference manual, the RAM block can store 32 messages of 8 bytes, 21 messages of 16 bytes, 12 messages of 32 bytes or 7 messages of 64 bytes. In the second section, CanRxFifo, the RX Fifo can be added or removed. According to the S32K3XX Reference manual, only the CAN0 allows the use of Enhanced RX FIFO. So if you are using another CAN instance and the FD protocol, the CanRxFifo should be disabled duo to the incompatibility between CanLegacyFifo and the FD protocol. Since this article’s application involves 2 CAN instances communicating with each other, it means that another Can Controller has to be set up besides the one that is already here. To have a solid starting point for the second Can Controller’s configuration, you can copy the current controller’s configuration and paste it into a new one. After completing the steps above, you will end up with 2 identical Can Controllers, which will cause conflicts due to duplicate items. To solve this, fill in the details for the second Can Controller. In this case, that only involves changing the Name, the Can Hardware Channel, the Can Controller ID (which should simply increment) and Can Controller Default Baudrate (the correct one becomes available in the dropdown list after changing the Name field). The last setting that needs to be changed on this newly created Can Controller is deleting the CanRxFifo, since the CAN1 does not have the Enhanced Fifo feature and we are using the FD protocol at the same time. 2.3.2. CanHardwareObject The next step is configuring the Can Hardware Objects inside the CanHardwareObect tab, still under the CanConfigSet menu. Working in a similar manner to the previous subchapter, we will focus on the explaining the options that you can expect to use. First of all, as a general rule, the RX objects should be placed before the TX objects in the list of objects. So there shouldn’t be any RX object with an ID that is higher or equal to the lowest TX object’s ID. The Name field controls the name associated to the hardware object that is displayed inside MBDT blocks. The Can ID Message Type controls whether the can message’s ID type is Extended, Mixed or Standard. Can Object ID acts as an identifier for the hardware objects. It starts with 0 and should continue without any gaps. Can Object Type controls whether the hardware object will be used to receive or transmit CAN messages. Can Controller Reference selects which Can Controller this object is configured for. Can Hw Object Count defines the number of elements in the hardware FIFO. The CanHwFilter is used for filtering messages. The Can Hw Filter Mask determines which part of the filter is active. The decimal number 536870911 converted to binary is 11111111111111111111111111111 (29 digits). This means that the mask enables the entire filter, since the extended ID format has 29 bits. The Can Hw Filter Code is the ID that the message would be compared to, based on the filter mask. Let’s look at the example in the image: Filter Code:  00000000000000000001111110000 (1008 in decimal) Filter Mask:  11111111111111111111111111111 Allowed IDs: 00000000000000000001111110000 (1008 in decimal) This means that the filter only allows messages coming from the extended ID 1008. If you want the filter to allow more than one value, you have to modify the filter mask in such a way that the filter does not check if every bit is equal to the filter code. Another example: Filter Code:  00000000000000000001111110000 (1008 in decimal) Filter Mask:  11111111111111111111111111110 Allowed IDs: 00000000000000000001111110000,                      00000000000000000001111110001 (1008 and 1009 in decimal) In this case, the filter mask allows the last bit to be different from the filter code. Since the Can Hardware Objects that already exist are properly configured for the CanController_0, we do not have to perform any changes. But, for the CAN1 to be able to communicate with the CAN0 instance, we have to add a TX (Transmit) hardware object for it. To do that, click on the highlighted + Button and then configure the object accordingly. As an alternative, you could copy the configuration from CanHardwareObject_Can0_Tx_Interrupt and simply change the fields that are relevant to the CAN1. This means changing the Name to reflect the correct controller, updating the Can Object ID, making sure that the Can Object Type is set to TRANSMIT, and changing the Can Controller Reference to point towards the CanController1. After finishing these configuration steps, the CAN0 would be set up to both receive and send messages, while the CAN1 is configured to only send messages. 2.4. CanIf Configuration The CAN Interface is found between the low-level CAN drivers and the upper communication service layers from the AUTOSAR stack. It provides a way to interact with different CAN Hardware device types like CAN Transceivers and CAN Controllers. Next, the newly created Can Controller (for the CAN1) has to be added to the CanInterface, in the CanIfCtrlCfg section, inside the CanIfCtrlDrvCfg menu. To add a new CanIfCtrlCfg element, press the + button, and then you have to update the CanIfCtrlId field and choose the right Can Controller for the CanIfCtrlCanCtrlRef.   2.5. Clocks Configuration (MCU) In order for the CAN instances to work properly, their clock has to be enabled in the McuModeSettingsConf tab, under McuModuleConfiguration, in the Mcu component. Once on this page, you have to scroll down and verify that the Clocks corresponding to your FlexCAN instances are enabled. By default, they are enabled in this current configuration, but it is important to remember that the CAN peripherals require to have their clocks. To change the reference clock, CanCpuClockRef, for a set of Can Controllers, you can find them in the McuClockSettingsConfig > McuClockReferencePoint.   2.6. Interrupts Configuration (Platform) The last step in the Configuration Tool is to set up the Interrupts for the CAN instances that we are using in this model so that we can use Interrupt-based blocks. To do that, head to the Platform component, by clicking the Platform button on the left of the Peripherals Tool. Afterwards, we have to navigate to the Interrupt Controller tab, where we can see all the interrupts that are currently configured. To configure the CAN instances, scroll down until you see the FlexCAN instances that you are configuring. In this article we use the CAN0 and CAN1 instances, so we are configuring these two instances. When it comes to FlexCAN interrupts, the FlexCAN0_0 contains 9 general interrupt requests, while the FlexCAN0_1 – FlexCAN0_3 instances contain 96 message buffer interrupts. More details about the interrupt mappings can be found inside the reference manual, S32K3XXRM, by consulting the attached file called S32K3xx_interrupt_map.xlsx. As you can see, one of them is already configured, so we only have to configure the FlexCAN1 instance as follows:   2.7. Dio Configuration The Input/Output pins configured previously also have to be configured in the Dio component, similarly to chapter 2.3. from the first article, Interacting with Digital Inputs/Outputs on MR-CANHUBK344. Now, inside the Dio component, we are configuring the input/output pins that will be used later in the model to enable the transceivers. Briefly going over the process, we have to remove the default pins that do not match the configuration we are working on. In this situation, it means removing the CanController_0_EN, CanController_0_STB and CanController_0_ERRN channels from the DioPort PTC_H. Afterwards, we add the Input/Output pins configured previously.   2.8. Uart, FreeMASTER, Adc and Pwm Configuration This article’s application involves using the Adc and Pwm components, as well as the FreeMASTER functionality, the way they were configured in the previous articles. For details on how to configure Uart and FreeMASTER, please refer to the second article, Sending data via UART and monitoring signals with FreeMASTER. As for the Adc and Pwm configurations, you can find step-by-step instructions in the third article of this series, Controlling LED intensity with ADC and PWM. For these components, there is no difference from the setups described in the referenced articles.   3. CAN Model Overview This article’s application aims to incorporate the previous components into a single example. This application consists of gathering data from two inputs, the ADC potentiometer and the USER_SW2 button, processing it, packaging it and sending it across the CAN Bus, so that it can be received by the other CAN instance and then control two outputs. The two outputs are a Blue LED that turns on according to the USER_SW2 button presses, and a Red LED whose intensity varies based on the rotation from the potentiometer. The following diagram aims to provide a better understanding for the flow of this application: Now, let’s break down the model into smaller pieces. Starting from the top left, the model uses a few variables. These have been grouped based on their purpose. For example, the Channel1 variable from the ADC is responsible for holding the value read from the ADC. Similarly, in the case of the CAN instances, the variables Data and Length represent the message that has been received across the CAN Bus. The last panel is the most important one, representing the values of the Dio and Aio peripherals right after the CAN message has been unpacked. Moving on to the Initializations section, this is where we perform the operations needed to prepare the components. In this specific case, we initialize the 2 CAN transceivers by setting 2 of their inputs to HIGH. In the initialization subsystem, a result buffer is set for the ADC conversion and the group notifications are enabled, so the configured ADC callback would be executed when the conversion on the group finishes. Finally, we turn the LEDs of the board off since this board uses inverted logic for the LEDs, which means they would normally turn on along with the board. The FreeMASTER Config block is used for enabling FreeMASTER functionality for this project. Moving on, there’s one more block to talk about before explaining the active parts of the model, which executes each step and which starts the group conversion for the ADC. Once the conversion is done, the hardware interrupt for the ADC will be triggered and the subsystem linked to the hardware interrupt callback block will output the ADC signal. The conversion to single data type takes place because the CAN Pack block is configured to accept a floating-point number which represents a voltage between 0V and 3.3V, corresponding to how much the potentiometer is turned. As specified, we start by collecting data from the inputs, the Aio and Dio. In the case of the Aio, we scale the value to represent the voltage read by the ADC. To be able to package the data and interpret it after the transfer, we are using a DBC file. DBC is a CAN Database file, which describes what kind of signals will be stored and sent through the CAN message. Afterwards, the data is then sent to a VNT packing block (VNT stands for Vehicle Network Toolbox TM ). By opening the CAN PACK block, we can see that the signals configured in the DBC file have been parsed properly and the block now expects them as an input. The ADC value will be a 32-bit variable, representing a voltage between 0V-3.3V, while the Dio variable will only have 1 bit, representing whether or not the button is pressed. In total, the variables take up 5 bytes, which becomes the length of the message. The next block, CAN Unpack, is used to extract the raw data from the CAN Frame, since that’s what will be sent by the CAN Transmission block. Can_Write is one of the available functions for the Can block and as the name suggests, it’s responsible for sending the CAN Message across the CAN Bus. The second dropdown item allows the user to select which CanHardwareObject will be sending the data. The items that appear here are the items configured as TRANSMIT in the menu seen in section 2.3.2. In this application, the data is being sent using an interrupt-based hardware object. The CAN FD Message checkbox selects whether the message being sent is using the CAN FD protocol and the Extended ID CAN Message selects the format for the ID. These should reflect the settings done in the configuration software. The second half of the application start with the CAN0 receiving the message sent by the CAN1. One important thing to note about how this works is that receiving the message is based on the CanIf_RxIndication, which triggers the Hardware Interrupt Callback. Afterwards, we can access the data. In the Hardware_Interrupt_Handler block, after selecting Can as the Interrupt Group, the following list of Can-related callbacks is made available. This application requires the ability to read incoming CAN Messages, so the CanIf_RxIndication is used for that purpose. CanIf_RxIndication is a callback which has an interrupt-based execution, being called whenever a CAN frame is received. Before obtaining the actual values from inside the CAN Message, we have to, once again, use the CAN Pack and Unpack blocks to extract the data and decode it according to the DBC file. Now that we have the values, we use the ADC value to proportionally change the brightness of the Red LED, and we use the value of the DIO to turn on or off the Blue LED. To validate the model, we can use the FreeMASTER tool to read and graph the values. As we can see, the received message is made up of 5 bytes of data, which represent the Adc Value and the Dio Value. Below you can see the variables' representaton on a graph made in real time in the FreeMASTER software. The red signal represents the value read from the potentiometer, situated between 0V and 3.3V. The blue signal corresponds to the state of the button: if the button is pressed, the blue signal will be equal to 1; otherwise the signal will be 0. On the bottom of the window, you can see the values of the signals at the time the screen capture happened. Apart from the ADC_Received and Dio_Received variables, which correspond to the red and blue signals from the graph, the other variables provide details about the last CAN message received.  By connecting the device capable of reading CAN messages, we can also see  them being transmitted through the CAN Bus. Here we use the PCAN-View software application to show the messages captured by the PCAN-USB Pro FD.     4. Conclusion After following the steps in the tutorial, you should now be able to include the MR-CANHUBK344 board into applications that require CAN Communications, either between the MR-CANHUBK344 board and a third party, or even between different CAN instances  from the same board. This article’s application also serves as an example on how to manage the workflow of adding multiple MBDT components into a single model.     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 and .dbc files 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 and Vehicle Network Toolbox is a trademark of The MathWorks, Inc. See mathworks.com/trademarks for a list of additional trademarks.
記事全体を表示
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.
記事全体を表示
1. Introduction In this series of articles, we demonstrate how to program the MR-CANHUBK344 board using the Model-Based Design Toolbox. The goal of this first article is to briefly present the hardware setup (the board and the connections that have to be made) and offer step-by-step instructions on how to create, configure and upload a simple program on the MR-CANHUBK344 development board. This article’s application consists of toggling onboard LEDs using the push button by configuring the Dio peripheral and the respective pins. The next articles in the series will showcase how to use different peripherals of the MR-CANHUBK344 board. 1.1. The MR-CANHUBK344 board The MR-CANHUBK344 evaluation board provides a T1 ethernet interface alongside 6 CAN (Controller Area Network) interfaces, two for each of the three different types, CAN-FD (Flexible Data-Rate), CAN-SIC (Signal Improvement Capability) and CAN-SCT (Secure CAN Transceiver). The board is designed for mobile applications, and it is based on the NXP ® S32K344, an Arm ® Cortex ® -M7 general-purpose automotive microcontroller, which features advanced safety, security and software support. Below you can find the block diagram for the MR-CANHUBK344 board. For more details about the MR-CANHUBK344 board, please follow the link:  https://www.nxp.com/design/development-boards/automotive-development-platforms/s32k-mcu-platforms/s32k344-evaluation-board-for-mobile-robotics-with-100base-t1-and-six-canfd:MR-CANHUBK344 1.2. Prerequisite Software To be able to follow the steps in this article, the following software is necessary: MATLAB ®  and Simulink ® (2021a or newer), including Stateflow ® , MATLAB ® Coder TM , Simulink ® Coder TM , Embedded Coder ® Model-Based Design Toolbox for S32K3xx 1.4.0 1.3. Prerequisite Hardware During this example, the following hardware is used: MR-CANHUBK344 evaluation board J-Link Debug Probe 12V power supply and adapters to allow powering up the board through the P27 port 1.4. Powering up the MR-CANHUBK344 First, the CANHUBK344 board accepts a wide range of input voltages, from 5V to 40V, which can be delivered through 2 different ports. P27 is the main power delivery port and it is used with a 5-pin JST-GH connector. This connector has 2 lines for power, 1 is not connected and the last 2 are ground lines. P28 is an alternate way of powering up the board and it consists of a 2-pin header. Regardless of the port chosen for powering up the board, precautions should be taken to make sure that the polarity is correct and that the pins align properly with the ports. Note: By default, the FS26 PMIC (Power Management IC) implements a challenger window watchdog that will reset the board’s MCU continuously if the challenge is not handled in software. To avoid this behavior, the FS26 must be put into debug mode. This is done by removing the JP1 jumper, then supplying 12V to the board and then inserting the JP1 jumper again. An example of how to connect both the power supply and the J-Link Debug probe will be discussed in the next chapter. 1.5. Connecting the J-Link Debug Probe When connecting the J-Link Debug Probe, pay attention to the connector, to make sure that you are aligning the red stripe of the connector with the pin number 1 on both sides. The associated J-Link software is not included in the Model-Based Design Toolbox and has to be installed separately. Installing the J-Link's software in the default location will allow it to work without having to select the location of the installation every time a new model is created.   2. Digital Inputs/Outputs Configuration So far, we have covered details about the board, how to power it up and how to connect the J-Link Debug Probe to it. This chapter will focus on designing the application that will run on the MR-CANHUBK344 board using the Model-Based Design Toolbox. 2.1. Creating and configuring the Simulink model Create a new model: Next, open the newly created model and head to the MODELING tab. To configure the hardware, click on the Model Settings option. If you have a tough time finding the button, you can use the Ctrl+E shortcut to open the Model Settings window. Moving forward, the correct Hardware board must be chosen from the Hardware Implementation tab. In this case, it is NXP S32K3xx. On the Solver tab, make sure to configure the Type to Fixed-step and set the Fixed-step size according to the needs of the application. This parameter controls how often the code in the model runs by setting the period time. For example, a Step Size of 0.1s would make the code run 10 times in a second, once every 0.1 seconds. In the current project, this value ends up affecting the frequency of the LED that is being toggled by itself, so setting it to a very small value might make it hard to see that the LED is indeed blinking. Setting it to a higher value would make the buttons feel unresponsive because the code would check for button presses rarely. A good value for this example is 0.1s, because the toggling LED will be ON, and respectively OFF 5 times in a second, since it changes every 0.1 seconds. This way, the LED’s change is visible, and the buttons feel responsive because their interaction is checked every 0.1 seconds. A few more options must be configured in Hardware Implementation. First, to access the submenu needed for the next changes, you have to click on the Target hardware resources option. From there, select Hardware and change the Hardware Part to S32K344-Q172. This will load the default configuration for the S32K344-Q172 hardware part. Later we will modify this configuration to work on the MR-CANHUBK344. Afterwards, head to the Download tab, still under the Target hardware resources submenu. Make sure that the Type is set to J-Link – JTAG and that the Target Memory is set to FLASH. If your J-Link software has been installed in a location that is different from the default location, you have to select the path to the JLink.exe executable by pressing the Browse button next to the J-Link location label and selecting the executable from the location where it was installed. The last step in the Target hardware resources submenu is to navigate to the Tools Paths and select S32 Config Tool in the Configuration Tool field. This setting changes the external configuration tool that will be used to configure the MCU’s pins, clocks and peripherals. This will allow the MCU to properly control all the components of the board. The Model-Based Design Toolbox for S32K3 uses integration with dedicated configuration tools to allow the configuration of the board's pins, clocks and peripherals, providing options for both Elektrobit Tresos (EB Tresos) and S32 Configuration Tools. More details on this configuration will be provided in the following sections. After all the changes have been made, do not forget to click Apply and Ok. Now, we are going to start designing the application model. To access the Model Based Design Toolbox provided blocks that control the hardware, click on the Library Browser button, which is going to open the Simulink Library Browser. From this window, navigate to the S32K3xx Core, System, Peripherals and Utilities menu under the NXP Model-Based Design Toolbox for S32K3xx MCUs and then select the IO Blocks from the right side of the window. In this example we will only use Dio blocks, so to start things off, we can drag-and-drop the Dio block into the Simulink Workspace. For the blocks to control the right pins, we must use the external configuration tool chosen to map the pins to the correct values. When creating an application for a supported Hardware Part, the Model-Based Design Toolbox comes with a default configuration project, enabling an initial set of peripherals, pins and clock settings for all the components it offers support for. The toolbox can be used with this default configuration project to design applications, without requiring any additional steps inside external configuration tools.   However, if the hardware or the application requires a different configuration than the default one, the external configuration tools allow you to open and modify the default configuration project to suit your needs. To quickly open the S32 Config Tool, you can double-click on the Dio block that has just been added and then click on the Configure… option. This opens the project’s configuration in the selected configuration tool. The configuration can also be done in EB Tresos in a similar manner, if it is the designated configuration software. 2.2. Pins Configuration The next step is to take note of the pins used for the project you intend on creating. In this example, we will be using 2 LEDs and one of the 2 push buttons available on the board, which are part of the Dio component. By studying the schematic, we can obtain all the information we need about the pins used. To be able to easily find a pin, search for its name and then look for the correspondence. In this example, by looking for the USER_SW1 pin, we can see that it is assigned to the PTD15 pin, also identified as GPIO111. After doing this for every pin, we can proceed with the configuration. While using the S32CT program, the pins’ MSCR (third column) will not be needed, but they will be required for the EB Tresos configuration. First, we will have to configure the pins to work as we expect them to, as inputs, outputs or even both. To do that, navigate to the Pins Tool by clicking on the Pins button. In this step, we will focus our attention on the top-left window, the Pins tab. First, we must check if there is any pin with the same name in the configuration. To do that for the button named USER_SW1 we can type its name value in the type filter text field. Here we can see that a pin with the same name already exists, and it is configured on the pin PTB19. To avoid further configuration issues, we must disable this pin. We can do that by clicking on the green Checkbox from the left side of the row. Then, we deselect the already selected item and click done, making sure nothing else is selected. To start the configuration process for the first pin, the button named USER_SW1, we can type its pin value in the type filter text field. As we can see, the pin is not configured for our intended behavior. To change that, we must update the identifier, the label, and click on the checkbox on the left. By doing that, the following menu will pop up: Here we will select the SIUL2:gpio,111 option since it matches our requirement. Afterwards, another window will pop up asking about the direction of the pin. In this case, we are configuring a button, so we only expect it to act as an Input. This process of removing the old configuration and adding the new one has to be repeated for every pin that will need to be configured. Keep in mind that when configuring the LEDs, you will have to set the direction as Input/Output since one of the LEDs will be toggled from one state to another, which requires the LED to be read before the output can be inverted. By taking a look at the bottom window, Routing Details, we can see more configuration options for the pins. You can use the type filter text field to limit the results to only the pins you are interested in seeing. The MR-CANHUBK344 board has its LED logic inverted, so, by default, the board's LEDs would turn on when powering the board. To avoid that, we assign an Initial Value to the LED. By setting the Blue LED's Initial Value to High, it is going to turn off as soon as the board starts. 2.3. Component Configuration Head back to the Peripherals Tool by clicking on the Peripherals button. Finally, after configuring the pins’ directions, we have to configure the Dio component so that the pins can be used during the execution of the program. This will be done in the DioConfig tab under the Dio Configuration tab. If it is not showing by default, you can press on the Dio component on the left side of the screen and it should bring it up. Understanding how the DioPort and DioChannel are organized might prove useful later. The number present under the DioPort label represents the corresponding value of the Dio port that you want to access. Below you can find a table with the correspondence between the values and the registers. AL=0 AH=1 BL=2 BH=3 CL=4 CH=5 DL=6 DH=7 EL=8 EH=9 Each of those is half of a register and together every line forms a 32-bit register. For example, AL and AH contain all the pin values that are assigned to PTA. AL contains the first 16 pins and AH contains the next 16 pins. For example, the RGBLED0_GREEN pin is assigned to PTA27. From that we can conclude that, since 27 is higher than 15 (the 16 th value of AL, since the first value is 0), the PTA27 pin must be assigned to the AH register. To reiterate, the PTA0-PTA15 pins belong to the AL register while the PTA16-PTA31 (the value must be offset by -16 when computing the Id) pins belong to the AH register, and this is true for the rest of the registers too, PTB, PTC, PTD, PTE. Given that the previous configuration did not match our setup, we should first prepare the registers by removing the components that we have already disabled in the section 2.2. For example, in the DioPort 0 we can see the old (disabled) LEDs, which can be removed by clicking the X button shown. This should be done for each DioPort Id to make sure there aren’t any incorrectly configured items. In the current case, we only have to remove the RGBLED0_BLUE, RGLED0_GREEN and USER_SW_1 items, which we will later replace with our own. After removing the LEDs’ configuration from the previous ports, since now the LEDs are routed to different pins, we can start adding the pins that we have configured in the prior step. Figuring out where each pin should go relies on the explanations from the beginning of this chapter. As an example, adding the ping RGBLED0_BLUE, which corresponds to PTE12, means going to the DioPort 4 because the value 12 is found in the first interval, 0-15, which points us to the EL register. To add a DioChannel, click on the + Button next to DioChannel. A new channel will be created and you have to fill in the details regarding the port. This has to be done for every of the 3 configured pins, in their respective registers. The last step is to save the configuration project and press the Update Code button. Afterwards, press Ok on the dialog window that popped up. Afterwards, feel free to close the configuration software. To update the configuration in the Simulink model, press the Refresh button inside the menu that pops up when double-clicking a block.   3. DIO Model Overview This article’s goal is to explain the workflow of creating a model that toggles the LEDs based on the push buttons available on the board. The logic will be the following: - The blue LED is toggled using the Push button 1; - The green LED is automatically toggled every simulation step. This means we will need blocks to read an input value, write an output value and flip an output value. These operations can be achieved using Dio blocks. A Dio block has multiple possible functions, which you can select from the Function dropdown. Once a new function is selected, the functionality and the block’s inputs and outputs will change accordingly. The pin that is going to be the target of the function can be chosen by selecting it from the dropdown list of the Channel option. The items that appear in the dropdown list correspond to the Dio channels that have been configured in chapter 2.3. The Input Simulation Enable option will not be used in this example, so it should be unchecked. Enabling this option will create an additional input for the block, which can be used to simulate the model’s behavior. For the functions Dio_ReadChannel, Dio_ReadChannelGroup and Dio_ReadPort, the block outputs the simulation input. For the Dio_FlipChannel function, the block will output the inverted simulation input The way the Dio Block is currently configured, it will read the input value from the button USER_SW1 which we can later use to control the LEDs. Since we want to toggle an LED when a button is pressed, it means we have to look for the rising edge of that input. To do that, a Trigger subsystem block will be used, that takes as input the value read from the button USER_SW1. The block’s Trigger type is configured to rising by clicking on the Trigger icon and when it detects that rising edge in its input, the subsystem will be executed. In this situation, we use the Dio block to invert the output of the LED. The contents of the newly added Trigger subsystem are seen below: Automatically toggling the green LED is a much simpler task due to the function FlipChannel available in the Dio block. The FlipChannel Dio block also has an output, which outputs the current state of the LED. Since that information is not going to be used anywhere else, a Simulink Terminator can be attached to that output, to avoid having errors. To upload and run the code on the MR-CANHUBK344 board, select the HARDWARE tab at the top of the window, and then click on the Build, Deploy & Start button. This will start the process of generating code from the Simulink model and uploading it to the board using the J-Link programmer. Note: If the J-Link’s path was not configured in the earlier steps, a dialog box will pop up requiring the path to the executable. If the software was installed in the default location, pressing on the Default option will be enough. Initially, after uploading the program or resetting the board, you will notice that the RGB LED is green and blinking. Keep in mind that the MR-CANHUBK344 board has its LED logic inverted, so writing a value of 1 to an LED output will turn it off, and writing a value of 0 to an LED output will turn it on. Pressing the SW1 toggles the blue LED, while the green one keeps blinking.   4. Conclusion After following the steps shown in this tutorial, you should now be able to create applications that use the MR-CANHUBK344 board’s LEDs and push buttons along with the Model-Based Design Toolbox. To continue learning about the MR-CANHUBK344 development board and how it can be used with the Model-Based Design Toolbox, check out the next articles in this series: Beginner's Guide for Model-Based Design Toolbox: Sending data via UART and monitoring signals with FreeMASTER Beginner's Guide for Model-Based Design Toolbox: Controlling LED intensity with ADC and PWM Beginner's Guide for Model-Based Design Toolbox: Communicating over the CAN Bus     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. Arm, Cortex are trademarks and/or registered trademarks of Arm Limited (or its subsidiaries or affiliates) in the US and/or elsewhere. The related technology may be protected by any or all of patents, copyrights, designs and trade secrets. All rights reserved. MATLAB, Simulink, Stateflow and Embedded Coder are registered trademarks and MATLAB Coder, Simulink Coder are trademarks of The MathWorks, Inc. See mathworks.com/trademarks for a list of additional trademarks.
記事全体を表示
The content of this article is identical to the AN13902: 3-Phase Sensorless PMSM Motor Control Kit with S32K344 using MBDT Blocks
記事全体を表示
Introduction   The RDDRONE-BMS772 is a standalone BMS reference design suitable for mobile robotics such as drones and rovers, supporting 3 to 6 cell batteries. The main components mounted on the board are: MCU: S32K144 (S32K1 Microcontroller for General-Purpose); BCC: MC33772B (6 Channel Li-Ion Battery Cell Controller IC); SBC: UJA1169TK (Mini High-Speed CAN System Basis Chip); RFID: NTAG5-Boost (NTAG 5 Boost: NFC Forum Compliant I2C Bridge for Tiny Devices) An overview of the pins available on the board and the connections between ICs can be consulted below. For further details, please check the datasheet and schematic available on the product's page.       Prerequisite software   To create, build and deploy a Simulink model onto the RDDrone BMS772, the following software is required: MATLAB ®  R2016a or later Simulink ® MATLAB ® Coder™ Simulink ® Coder™ Embedded Coder ® Support Package for ARM ® Cortex ® -M Processors S32K1xx MBDT Toolbox Version 4.3.0 JLink Debug Probe Segger FreeMASTER Run-Time Debugging Tool   Prerequisite hardware   The hardware required for this example is: RDDrone BMS772 CAN Bus Terminator resistor (DRONE-CAN-TERM) OLED Display 128x32 pixels 12V DC Power Supply (it's not included in the RDDRONE kit) External Thermistor with cable CAN interface for USB 6-Cell Battery Emulator (it requires a separate 12V DC power supply, consult User Manual) JLink Debug Probe Soldering iron: By default, the BCC is configured to work with a 3S configuration. To configure for 4S, 5S or 6S, multiple modification must be performed on the board. (Consult SPF-45742 for further details)   Create the model and configure the components Initialize the model To configure a model to work with blocks from S32K1xx toolbox, the MBD_S32K1xx_Config_Information block must be added. The RDDRONE is part of S32K144 family, with an External 32 MHz external crystal. The download interface is JTAG, using the Segger Link. Note! Segger JLink Software is not included in the toolbox and must be installed separately.     Initialize System Basis Chip   The System Basis Chip (SBC) mounted on the board is UJA1169TK, which is a mini high speed CAN transceiver. Moreover, it also features a watchdog and it can be configured via LPSPI0 (Low Power Serial Peripheral Interface). Out of the box, the SBC is running in Forced Normal Mode, which means that the watchdog is disabled, but CAN transceiver continues to work. If the SBC is initialized and configured, it exits the Forced Normal mode and enters Normal Mode operation. Now, the watchdog must be reset accordingly to the configuration made, otherwise it will trigger a reset.  A special operation mode is Software Development Mode Control and it allows the SBC to be configured (CAN, power regulator) while the watchdog is kept disabled. To enable the SDMC, the SBC must be in Forced Normal Mode (Further details can be found here: 7.11.2 Restoring factory preset values). Note! MCU configures the SBC via the SPI. Therefore, the LPSPI0 must be initialized before the SBC config block. A basic configuration for SBC can be found below.     Initialize FreeMASTER   FreeMASTER is a user-friendly real-time debug monitor and data visualization tool that enables runtime configuration and tuning of embedded software applications. The connection between MCU and FreeMASTER application can be done via the following: UART CAN Debugger Probe/On-board debugger interface In this example, the CAN0 interface is used to send/receive messages from FreeMASTER application. The RxD and TxD pins required are PTE4, respectively PTE5 (both are routed to J3 connector). The default bitrate is 1000 Kbit/s but depending on the use case, it can be lowered.   Note! FreeMASTER can add a lot of overhead if the user interface monitors multiples variables at a very fast refresh rate, and it can cause the step function to overrun.    Initialize BCC   Battery Cell Controller (BCC) MC33772B can be configured and used by the MCU via SPI/TPL. Similar to SBC, the communication interface (LPSPI1) must be initialized before initializing the BCC. As a feature, the BCC block can assist you to configure the LPSPI interface to properly work.  First of all, add the LPSPI config block and select the instance to 1 (as this instance is routed on the RDDRONE board from the MCU to the MC33772B). Go to Pins tab and select the pins used by LPSPI1 and BCC. The role, baud rate and other advanced settings are going to configured later from the BCC config block.  As there are no TPL transceiver added, the MC33772B communicates with the MCU via LPSPI instance 1 (previously configured). In the General tab, Instance refers to the instance of the BCC (not to be confused with the LPSPI instance). In the area "SPI Mode", the type of the BCC must be selected. In this case, the BCC mounted on the RDDRONE is MC33772B. The number of cells is 6. Going next to the SPI tab, the SPI Instance needs to be set to 1 and the SPI CS Selection to LPSPI_PCS0.  Lastly, in the Pack Settings, it is a must to set Shut Resistance to 500 uOhm (as this is the value of the shunt resistor R1 mounted on the board). In the MC33772B config block, the following settings must be modified: Configuration Tab General Settings Instance: 0 Mode: SPI SPI Mode Device: MC33772B Cell number: 6 SPI tab SPI instance: 1 SPI CS Selection: LPSPI_PCS0 Pack Settings Shut resistance: 500 uOhm (shut resistor R1 is mounted directly on the RDDRONE)     After the MC33772B is properly configured (especially the SPI instance is selected), you can click on the Config SPI for BCC as Master button from SPI tab (highlighted by the orange rectangle in the image above).   Note! MCU configures the BCC via the SPI. Therefore, the LPSPI1 must be initialized before the MC33772B config block.   Initialize SSD1306 OLED   The OLED display used in this example is a 128 x 32 pixels display that communicates with the MCU via LPI2C0 (J23).  The configuration for LPI2C is presented below: After the LPI2C is configured, the block to configure the OLED can be added and configured as below: LPI2C Instance: 0 SSD1306 Address: 60 (represented in decimal format, hex: 0x3C) Width: 128 Height: 32 Font: 11 x 18 Background color: Black Note! MCU configures the LCD via the I2C. Therefore, the LPI2C0 must be initialized before the LCD config block.   Initialize Gate Driver   The gate driver is controlled by a D-type flip flop and it allows the MCU to disconnect the electrical load (motors, servos) attached to Power OUT pads from the Power IN, when the battery is discharged or various faults occurs. GPIO PTC2 is connected to the 'Data input' pin of the D-type flip flop (U10) and it is active low (set pin to 0 to enable the gate driver and to 1 to disable it). GPIO PTC1 is connected to the 'CLK' pin of the flip flop which is a rising edge triggered clock signal input pin. So, to control the gate driver, the PTC2 must be set to the desired state, then the PTC1 is toggled 2 times. To assure that the sequence is kept in order, set the priority of each GPIO Write block.   Structure of the application One of the most recommended design style for an application in Simulink with NXP MBD Toolbox is to break down the application into three categories as: Input: Hardware dependent blocks that read/receive the values of interest from peripherals Algorithm: Hardware independent blocks that process the values received from the Input blocks. Output: Hardware dependent blocks which receive the processed values from the Algorithm blocks   One advantage of this approach is that a fully tested application can be converted to new hardware without any modification to the ALGORITHM part. Only the INPUT and OUTPUT blocks must be updated to the new hardware. Moreover, while developing an application, you can validate the ALGORITHM section in Software-in-the-Loop (SIL) or Processor-in-the-Loop (PIL). These two methods of simulation are useful to test cases that are not easy to replicate, as specific data can be fed as input. Taking these into account, this example can be structured like this: Input (green area): The blocks in this area read data from the MC3377xB BCC and store them in multiple data stores. In case there are any faults detected, MC3377xB_Fault_Get_Status reads the error and store it in FaultStatus data store memory. To make sure the MCU is not halted, an onboard LED (PTB13) is toggled at each step. Algorithm (blue area): As this example is more of a dummy one, the algorithm part only processes the PackVoltage and PackCurrent to be properly displayed on the OLED display. toggleLED variable is negated at every step to toggle the onboard LED. OUTPUT (pink area) Reset the SBC UJA116x's watchdog to avoid the forced restart of the board PackVoltage and PackCurrent received in INPUT area and processed in ALGORITHM area is then shown on the OLED display. Toggle the LED and save the new value in toggleLED data store memory.   Deployment Now that the application is completed (make sure the steps at Create the model and configure the components -> Initialize the model are correctly followed), it can be deployed on the target. First of all, the JLink probe must be correctly connected to the RDDRONE board to the J2 header. Then, power the board using a 12V power supply by using the J4 pads. Important! When soldering the header on J4 pads, make sure the polarity is properly respect, otherwise, you might risk to permanently damage the board. The CAN analyzer must be connected to J3 and the CAN terminator to J20 (located on the back of the board, right below J3 header). OLED display must be inserted into J23 header.  Important! Make sure to properly respect the polarity of the display, otherwise you might risk to permanently damage the display. The 6 Cell Battery Emulator must be connected to the JP1 header. Depending on the configuration made on the back of the RDDrone, connect the cells to its respective pin on the board (consult the overview pinout presented at the beginning of the article). Pin JP1[7] must be connected to the CTREF[33] pin of the battery emulator. Finally, the code can be generated based on the Simulink model, compiled and deployed on the target. To do this, go to Simulink -> Apps -> Embedder Coder then click on the Build button. Now, in the Diagnostic Viewer, the deployment process can be analyzed to see if there are any errors with the application and if the download was successfully completed on the target like in the image below, where we can see: The .elf file is successfully generated and its size The download is completed Important! In order to be able to download code on the target, the reset line from the SBC to S32K144 must be disconnected, remove the header on J5 during the deployment process.   FreeMASTER Now that the application is deployed on the target, FreeMASTER can be configured to connect to the target via CAN. Go to the TOOLS -> Connection Wizard and select the Connect over CAN BUS with CAN card or USB-to-CAN module. In the prompted window, configure the CAN Interface accordingly to your hardware and configuration made in the Simulink model.   Now that the FreeMASTER connection with target is completed, the .ELF file must be selected to access variables and monitor them in real-time. Finally, start the communication between FreeMASTER and the target and the data shown should be similar to this:   Conclusion In this article, we described how to use NXP Model Based Design Toolbox for S32K1xx to handle a custom hardware design (such as RDDRONE BMS772), from the configuration of the peripherals to the download on the target and validating the application. The example covers all the peripherals that the S32K1xx toolbox 4.3.0 supports for the RDDRONE. Feel free to comment below if you have questions.   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. Arm, Cortex are trademarks and/or registered trademarks of Arm Limited (or its subsidiaries or affiliates) in the US and/or elsewhere. The related technology may be protected by any or all of patents, copyrights, designs and trade secrets. All rights reserved. MATLAB, Simulink, Stateflow and Embedded Coder are registered trademarks and MATLAB Coder, Simulink Coder are trademarks of The MathWorks, Inc. See mathworks.com/trademarks for a list of additional trademarks.  
記事全体を表示
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
記事全体を表示
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 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 Apps Motor Control SPI configuration MODEL based design tool box- 32 bit instruction (SIMULINK) 
記事全体を表示
This page summarizes all Model-Based Design Toolbox videos related to HCP Product Family. Deploying Radar Applications to NXP´s S32R41 Processor Using Simulink® Link to the recording here This webinar shows how to use Radar Toolbox, Simulink ®  , and Embedded Coder ®  to generate C code for radar signal processing algorithms for range and speed estimation and deploy them to NXP ® ´s S32R41 high-performance processor for high-resolution radar. Based on MathWorks´ radar example models, we use Embedded Coder to generate optimized C code and run it in Processor-in-the-Loop (PIL) mode on the S32R41 processor. The code generation workflow will feature the use of NXP´s Model-Based Design Toolbox (MBDT), which provides an integrated development environment and toolchain for configuring and generating all the necessary software to execute complex applications on NXP MCUs and processors.
記事全体を表示
1. Introduction The NXP HCP Toolbox enables automatic code generation for applications prototyping from Simulink for NXP’s S32G2xx and S32S2xx MPUs. This article details the steps to build, deploy, and run the HEV demo on S32G2xx, and also collect telemetry data using AWS IoT Greengrass. 2. Hardware overview The following hardware components are needed for running the HEV demo: an S32G274A RDB2 Evaluation Board Configure the evaluation board to boot from the SD card. a microSD card We'll flash and boot the GoldVIP Linux from this card a micro USB cable Connect the cable to the UART0 port and your host machine. This connection will be shown in Windows as a serial port and we'll use it to connect from a terminal emulator for the initial Linux setup. two Ethernet cables Connect another Ethernet cable to the P3A port and to your LAN network. This connection will be used for AWS data telemetrics. Connect one Ethernet cable to the P3B port and to your LAN network. This connection will be used for PIL communication between MATLAB and the application running on the board. a Logitech F310 or compatible gamepad Connect the gamepad to your host machine before opening the HEV model. We'll use it to drive the car in the virtual 3D environment: to steer, accelerate, and brake. The following figure shows the USB, UART, CAN and power connectors on the S32G2 RDB2 evaluation board. The following figure shows the Ethernet connectors on the S32G RDB2 evaluation board. 3. Software overview To run the HEV demo we must perform the following steps to install the required software. 3.1 Mathworks MATLAB and Add-Ons Install the following software from Mathworks required to build and run any model that uses the NXP Model-Based Design Toolbox for HCP : MATLAB 2020a or newer MATLAB Embedded Coder, the key component that allows us to generate the C code that will be cross-compiled to be executed on the target Embedded Coder Support Package for ARM Cortex-A Processors Install the following additional toolboxes from Mathworks required to build and run the HEV demo: Powertrain Blockset Vehicle Dynamics Blockset Automated Driving Toolbox Simulink 3D Animation Mapping Toolbox All these toolboxes can be installed from MATLAB, by opening Get Add-Ons window and searching for each of these toolboxes.   3. 2 NXP Model-Based Design for HCP Toolbox Install NXP MBDT HCP Toolbox to add the HCP target support to the MATLAB environment to allow code generation and deployment. Following are the steps to install NXP’s Model-Based Design Toolbox for HCP Series of MPUs: 1. Go to nxp.com and sign in to your NXP account. If you don't have an NXP account, create one from the Registration page. Toolbox is for free but an account is required to download the tool and access training & support on NXP Model-Based Design Toolbox Community). 2. Go to NXP Model-Based Design Toolbox (MBDT) page, select the DOWNLOADS tab and press the Download page, which will open the Model-Based Design Toolbox download page. 3. From the Model-Based Design Toolbox download page select the Model-Based Design Toolbox for HCP 1.0.0, and then on the next page, you will be asked if you agree to the Software Terms and Conditions. 4. On the Model-Based Design Toolbox for HCP download page, download the following files: SW32_MBDT_HCP_1.0.0_EAR_D2111.mltbx, the toolbox installer MBDToolbox_HCP_1.0.0_S32S2xx_Tools.zip, the S32G2xx build toolchain Some browsers will download the .mltbx file as .zip file.  To avoid that, please press right click on the download link and select Save link as. 5.  Open MATLAB, navigate to where you downloaded the toolbox installer, and run the installer (press double click or right-click and select Install). 6. After a few minutes (~4-5min), the NXP’s Model-Based Design Toolbox should be visible as a new add-on in the Add-On Manager. 7. The Model-Based Design Toolbox uses the toolchain mechanism exposed by the Simulink to build the  code generated with Embedded Coder toolbox. By default, the toolchain is configured for the MATLAB R2020a / R2020b / R2021a releases. For any other MATLAB release, the user needs to execute a toolbox m-script to generate the appropriate settings for his/her installation environment. This is done by running the mbd_hcp_path.m script.     >> mbd_hcp_path No compatible target currently available for NXP S32G2xx. Creating one.. Creating folders for the target 'NXP S32G2xx' in the folder 'C[…]\NXP_MBDToolbox_HCP\mbdtbx_hcp\codertarget\2021b\s32g2'... Creating the framework for the target 'NXP S32G2xx'... Registering the target 'NXP S32G2xx'... Done. No compatible target currently available for NXP S32S2xx. Creating one.. Creating folders for the target 'NXP S32S2xx' in the folder 'C[…]\NXP_MBDToolbox_HCP\mbdtbx_hcp\codertarget\2021b\s32s2'... Creating the framework for the target 'NXP S32S2xx'... Registering the target 'NXP S32S2xx'... Done. Successful.       3.3 Gold Vehicle Integration Platform (GoldVIP) In the case of S32G2 at the start of the PIL simulation a Linux application is cross-build on the MATLAB host machine, deployed to the evaluation board via SSH, and executed inside a Linux operating system running on that board. We'll use the Linux image from Gold Vehicle Integration Platform (GoldVIP) package that supports telemetry to cloud using AWS IOT Greengrass. Telemetry statistics are fetched from the device, calculated and sent to the cloud counterpart of the application. Statistics received in the cloud are then displayed into user-friendly graphs. The statistics include but may not be limited to: Networking accelerator usage statistics, Realtime cores load, Domain-0 VCPU load and Domain-0 Memory utilization statistics. The GoldVIP is a reference software platform for a vehicle service-oriented gateway running on NXP vehicle network processors like the S32G274A. Following figure shows the GoldVIP high-level architecture. NOTE: GoldVIP is available upon NXP approval as an Early Access Release. Please contact your NXP sales representative for more information. Once you get the approval, go to the GoldVIP download page and download the following files: GoldVIP-0.11.0-binaries.zip GoldVIP-0.11.0_User-Manual.pdf Next we unzip the GoldVIP-0.11.0-binaries.zip archive and  we'll find the Linux image fsl-image-goldvip-s32g274ardb2.sdcard in GoldVIP-0.11.0-binaries\binaries folder. 5. Toolbox setup NXP Model-Based Design Toolbox for HCP offers a Setup GUI to select which toolchain to use, flash the Linux image card, configure and test the network connection. After the installation of the toolbox has finished the GettingStarted.mlx file is opened. To run it go to the LIVE EDITOR tab and push the Run button. Running it will open the Setup GUI that will help you configure the toolbox. 5.1 Select Target We are going to select S32G274A and push the Next button. 5.2 Setup Toolchain  Select I need to acquire the toolchain and push the Next button. In case you already have the toolchain the steps are a subset of the one below. 5.3 Download Toolchain Next download the S32G2xx toolchain by following the steps from 3.2, step 4, if you haven't already done so, and then select the path to the downloaded toolchain archive. Then select the folder to where the archive should be unzipped. Next press the Unzip button to unzip the selected toolchain archive. This step will take around 10 minutes. If the toolchain archive is unzipped successfully, the Next button is enabled. 5.4 Validate build toolchain Select the toolchain folder using the Browse button to verify it. Push the Validate button. If everything is alright the message is Toolchain is valid, otherwise the message is Toolchain is not valid. If the toolchain is valid the Next button is enabled and should be pushed to continue the configuration 5.5 Write Linux on the microSD card This page helps you to write the Linux on a microSD card. First, insert the microSD card, then push the Refresh button to actualize the drive list. If the microSD is available in Windows the list should be not empty. Select a drive from the list and push the Next button. Select the Linux image using the Browse button. Finally, push the Write button to write the Linux image. 5.6. Get additional software In order to connect to the S32G2 board we'll need to install additional software. You can use Terminal Emulator familiar to you, such as Tera Term, Putty or other. Also install FTDI CDM WHQL driver for serial configuration from FTDI chip, otherwise you will not be able to connect to the board using the serial port. 5.7 Connect Hardware Connect the board using the following instructions: 1. Remove the memory card from the host computer and insert into the S32G2 board micro SD card slot. 2. Connect two Ethernet cables to S32G2 board, one to P3A port and another one to P3B port. Connect the other ends of the cables to your LAN or HOME network. 3. Connect an USB cable between the UART0 port on the S32G2 board and your host computer. 4. Connect the 12 V power supply to the S32G2 board and power on the board. 5. Open the terminal emulator (e.g. putty) to connect to the board and configure the network settings. Select the serial port added to Ports (COM & LPT) in Device Manager when the micro USB cable is connect to the host machine, and select 115200 as the baud rate. If you didn't install the FTDI driver in the previous steps, a new COM port will not be added when you connect the USB cable. Once you connect over the serial to the board, you will be asked to log into Linux in the terminal emulator. The default username is root, without a password.  If your network assigns IP address automatically via DHCP, you don't need to do any network configuration on Linux. Otherwise, you will have to configure the network settings for pfe2 interface. Run ifconfig pfe2 to get the IP address that we'll use for PIL simulation. The field that we are looking for is inet, and in the bellow output the IP address is 192.168.2.152.     root@s32g274ardb2:~# ifconfig pfe2 pfe2: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500 inet 192.168.2.152 netmask 255.255.255.0 broadcast 192.168.2.255 inet6 fe80::6da:49da:68c3:24d9 prefixlen 64 scopeid 0x20<link> ether 00:01:be:be:ef:33 txqueuelen 1000 (Ethernet) RX packets 190 bytes 14318 (13.9 KiB) RX errors 0 dropped 0 overruns 0 frame 0 TX packets 186 bytes 18928 (18.4 KiB) TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0 device memory 0x46000000-46ffffff     Copy this IP address as we'll need it in the next step of the toolbox setup. 5.8. Setup network connection Fill in the Device Address, Username, Password, and Download folder, and then push the Test Connection button. This tests if the device address is valid, and also if the a SSH commands can be run. For the Device Address use the IP address copied from the output of ifconfig pte2. Default username is root, and no password is set. Default download folder is the home folder of the root use, /home/root. 5.9. Setup done Congratulations! You are ready to use the Model-Based Design for HCP toolbox. Note: Press the Finish button to save the toolchain path and network connection settings. 7. GoldVIP setup By default, the GoldVIP deliverable includes Xen hypervisor. Xen is a type 1 hypervisor (bare metal) that makes possible running multiple instances of the same operating system seamlessly on the hardware. Xen allows creation of virtual machines from the command line or automatically at startup. Xen virtualizes CPUs, memory, interrupts and timers, providing virtual machines with virtualized resources. Two types of virtual machines are defined by Xen: Privileged (Dom0 or Domain-0): The first machine that runs natively on the hardware and provides access to the hardware for unprivileged domains. Unprivileged (DomUs): Virtual machines spawned by Dom0. These machines use the hardware resources allocated from the privileged domain (CPU, Memory, Disk, Network). In the GoldVIP, two virtual machines are started by default, before the user logs in: Domain-0, which has access to all the system resources and creates a network bridge for the unprivileged guest. This bridge, namely xenbr0 is the network interface that forwards packets to the DomU; v2xdomu, unprivileged domain, which has access only to a limited number of resources. The HEV demo will run in Domain-0, in the privileged domain. Telemetry data is collected from Domain-0 and passed to v2xdomu through a TCP client-server communication. To switch to v2xdomu type: xl console v2xdomu The username on the v2xdomu is root without a password. To exit from v2xdomu press Ctrl + ] 7. AWS setup 7.1 Prerequisites You will need an AWS account with SSO enabled. Follow the steps in this guide to enable SSO: https://docs.aws.amazon.com/singlesignon/latest/userguide/getting-started.html Enabling SSO will grant you access to the SSO console. SSO is also required to use the SiteWise Dashboard. 7.2 AWS IAM Permissions A policy for an AWS IAM user, it contains the necessary permissions for the deployment and use of the telemetry use case:     { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": [ "cloudformation:*", "cloudwatch:*", "iot:*", "lambda:*", "logs:*", "s3:*", "greengrass:*", "sns:*", "iotsitewise:*", "iam:*", "sso:*", "sso-directory:*" ], "Resource": "*" } ] }     AWS IAM documentation: https://docs.aws.amazon.com/IAM/latest/UserGuide/getting-started_ create-delegated-user.html 7.3 Deployment of the Telemetry Stack in AWS 1. Go to the AWS SAR console: https://console.aws.amazon.com/serverlessrepo/ 2. Go to Available applications tab; then to Public applications and search for goldvip. 3. Check Show apps that create custom IAM roles or resource policies to see the application. 4. Click on nxp-goldvip-telemetry. You can modify the application parameters. 5. Check I acknowledge that this app creates custom IAM roles. 6. Click Deploy. The deployment will take a few minutes. You will be redirected to another page. The name of the stack is on the top of the page, starting with serverlessrepo-, if you changed the application name you will need this name in the next step. You can go to the Deployments tab and see the status of the deployment. Wait for the status to change from Create in progress to Create complete. Note: you may need to refresh the page to see the status change. This CloudFormation stack creates on your account: A Greengrass V2 telemetry component, this is a python function which runs on v2xdomu and sends data to AWS IoT Core. The provisioning script described in chapter 7.4. Connecting the board to AWS creates a Greengrass V2 continuous deployment which will run the telemetry component on your board. A SiteWise Portal with multiple Dashboards; after the board is connected to AWS a live visual representation of the telemetry data received via the Greengrass V2 component is displayed in these. 7.4. Connecting the board to AWS 1. Log into the v2xdomu virtual machine using the command: xl console v2xdomu 2. Configure environment variables for Greengrass provisioning script: From the v2xdomu console, set the AWS credentials as environment variables:     $ export AWS_ACCESS_KEY_ID=<access key id> $ export AWS_SECRET_ACCESS_KEY=<secret access key>     One way of obtaining your AWS credentials is the following: From the AWS SSO console select your account and retrieve the environment variables by clicking on Command line or programmatic access. From section macOS and Linux copy the variables and paste them on your board. Use Option 1: set the AWS credentials as environment variables. Please check the AWS documentation for additional information: https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-envvars.html Note: IAM credentials should never be used on a device in production scenario. These variables are temporary and are erased at reboot. 3. Run the Greengrass provisioning script on your board:     $ python3 ~/cloud-gw/greengrass_provision.py --stack-name <stack-name> --region-name <region-name>     Where <stack-name> is the name of the deployed stack. If you did not change the application name you do not need to specify this parameter. In <region-name> put the region you have selected from the supported ones: us-west-2 or eu-west-1. This will setup the network interface, start the Greengrass V2 Nucleus, and create a Greengrass V2 continuous deployment, which will run the telemetry component created by the Telemetry Stack. Note: the provisioning script will try to setup the internet connection using the eth0 network interface by default. To get more details about the script parameters use:     $ python3 ~/cloud-gw/greengrass_provision.py -h     The board is now connected to your AWS account and it will begin to send telemetry data. 7.6. Accessing the SiteWise dashboard 1. Go to the SiteWise console: https://console.aws.amazon.com/iotsitewise/ 2. Click on Portals from the list on the left. 3. Click on the name of your portal, it starts with SitewisePortal_serverlessrepo. 4. Click on Assign administrators. 5. Add your account and any other you want to have access to the SiteWise Dashboard. 6. Click Assign administrators. 7. Click on the Portal’s Url (or Link). 8. Close the Getting started pop up window. 9. Click on one of the dashboards to visualize the telemetry. You will now see the live telemetry data from your board. For more information check the GoldVIP User Manual. 8. Running HEV demo 1. A Logitech F310 gamepad is needed to control the car. Connect the gamepad before opening the model. 2. We recommend to make a copy of the HEV demo folder from HCP toolbox in another working folder. Run the following command in Matlab to navigate to S32G2xx examples folder.     cd(fullfile(mbd_find_hcp_root(), 'HCP_Examples', 's32g2')     Copy the HEV_P4_Ext_TV to another working folder, e.g. C:\workspace\. 3. Open the HEV_P4_ExternalDriver_v3_TV_v4_fixedStep.slx model. The HEV demo is already configured for PIL simulation mode. 3. Run the PIL simulation by pressing the Start button from . Simulink generates the code for the model, compiles it, downloads it on the board, and then starts the simulation.  
記事全体を表示
      Product Release Announcement Automotive Processing NXP Model-Based Design Toolbox for HCP – version 1.0.0 EAR       The Automotive Processing, Model-Based Design Tools Team at NXP Semiconductors, is pleased to announce the release of the Model-Based Design Toolbox for HCP version 1.0.0. This release supports automatic code generation from MATLAB/Simulink for S32G2xx and S32G2xx Automotive MPUs. This new product adds support for running Processor-in-Loop simulation on S32G274A (ARM Cortex-A53) and S32S247TV (ARM Cortex-R52).   FlexNet Location: https://nxp.flexnetoperations.com/control/frse/product?child_plneID=683951   Technical Support: NXP Model-Based Design Toolbox for HCP issues will be tracked through NXP Model-Based Design Tools Community space. https://community.nxp.com/community/mbdt     Release Content Automatic C code generation from MATLAB® for NXP S32G2xx derivatives: S32G274A Automatic C code generation from MATLAB® for NXP S32S2xx derivatives: S32S247TV Supported Evaluation Boards GoldBox Development Platform (S32G-VNP-RDB2 Reference Design Board) GreenBox II Development Platform Support for MATLAB versions: R2020a R2020b R2021a Simulation mode: We provide support for Processor-in-Loop (PIL) simulation mode with code execution profiling:   Includes the HEV demo:     Includes an Example library that covers: Software-in-Loop, Processor-in-Loop   GUI to help you setup the toolbox and the evaluation board :     For more details, features and how to use the new functionalities, please refer to the Release Notes document attached.   MATLAB® Integration The NXP Model-Based Design Toolbox extends the MATLAB® and Simulink® experience by allowing customers to evaluate and use NXP’s S32G2xx and S32S2xx  processors and evaluation board solutions out-of-the-box with: NXP Model-Based Design Toolbox for HCP version 1.0.0 (EAR) is fully integrated with MATLAB® environment in terms of installation:       Target Audience This release (1.0.0 EAR) is intended for technology demonstration, evaluation purposes and prototyping S32G2xx and S32S2xx and Evaluation Boards.   Useful Resources Examples, Trainings and Support: https://community.nxp.com/community/mbdt  
記事全体を表示
This article details the SPI communication setup between S32K1xx boards and MC3377xBSPI 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 up to 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. 
記事全体を表示
In this video we show how to build, simulate and test a speed estimator based on Hall Sensors for a BLDC motor. The estimator is first tested under Matlab Simulink environment and then ported into the Open Loop Control Simulink model and tested on the MPC5744P Development Kit with FreeMASTER over CAN interface.   We discuss about: - How to compute the speed; - How to build a speed estimator based on Hall sensors; - Step-by-step model building an enhancements; 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上的视频
記事全体を表示
In this video we discuss about Open Loop Control strategy and for the first time in this course we will put together all the models we have created so far and build the Simulink model that will allow us to rotate the BLDC motor. We discuss about: - Open Loop Control diagram; - Step-by-step model building an enhancements; - Test the open loop control system on the BLDC motor;   NOTE: Chinese viewers can watch the video on YOUKU using this link 注意:中国观众可以使用此链接观看YOUKU上的视频
記事全体を表示
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上的视频
記事全体を表示
In this video we discuss about practical implementation of the motor phase commutation algorithm and how to validate and test such algorithm using different approaches in Model Based Design.    We discuss about: - How to build the commutation table starting from the hall sensor measurement experiment; - How to implement the Software Look Up Tables for rotating the motor in clockwise (CW) or counter clockwise (CCW) directions; - Simulink model that implement the commutation algorithm;   NOTE: Chinese viewers can watch the video on YOUKU using this link 注意:中国观众可以使用此链接观看YOUKU上的视频
記事全体を表示