NXP Model-Based Design Tools Knowledge Base

cancel
Showing results for 
Show  only  | Search instead for 
Did you mean: 

NXP Model-Based Design Tools Knowledge Base

Discussions

Sort by:
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.
View full article
Introduction The application is based on an example of basic GPIO for S32K144 (gpio_s32k14_mbd_rtw). The application is extended to fit the needs of motor control application running a sensorless PMSM Field Oriented Control algorithm. Therefore, certain modes (states) and transitions (events) are implemented. NOTE: Theory of Finite state machines defines states and events (transitions). Following design uses approach which may seem to mix states and transitions at some point. Some states are run just once, thus they may be considered as transitions only. However, the design is considered as an example and may be extended in terms of additional checks for external events, making these "one-shot" states the actual states. The design has been well known from NXP Automotive Motor Control Development Kits and it has been well accepted by majority of customers. Therefore, the same concept is presented for MATLAB Simulink. Finite State Machine Design The application structure should introduce a systematic tool to handle all the tasks of motor control as well as hardware protection in case of failure. Therefore, a finite state machine is designed to control the application states using MATLAB Simulink Stateflow Chart (Stateflow library/Chart). The motor control application requires at least two states - "stop" represented by "ready" state and "run" represented by "run" state. However, some additional states need to be implemented to cover e.g. power-on situation, where the program waits for various auxiliary systems (system basis chip, DC-bus to be fully charged, memory checks, etc.). In addition, the motor control application and specifically the sensorless field oriented control requires additional states to calibrate the sensors and to start the motor with known position. Therefore, transition from READY state to RUN state is done through an initialization sequence of CALIB (sensors calibration) and ALIGN (initial rotor position alignment or detection) states. To stop the motor, the application goes back to the READY state via INIT (state variables initialization). While the INIT state is designed to clear all the internal accumulators and other variables (but the parameters can be changed in the run time and not reset to the default settings), the RESET state is introduced to enable power-on or "default configuration" or "soft reset" initialization in the case of the motor control parameters are changed using FreeMASTER or other user interface. All the states are linked with an output event which is traced out of the state machine chart block. These events can be used as trigger points for calling the handlers (state functions). The transitions are driven by the input value of the state machine, treated as an event using a simple comparison (e.g. [u==e_start]). To change the state, the event/input value should be changed. If the event has changed, the state machine changes the state only in case of there is an existing action linked with the current state and the event. The state machine is designed to be used in the application using Event input (to signal the event), State output (to indicate the current state) and Event triggers outputs (to call the state functions / handlers). Following application has been built to show an example of the state machine usage. Following tables show the nomenclature of the states and events: State Purpose Value Reset Power-on / Default settings / Soft-reset state. May include some HW checking sequence or fault detection. 1 Init Initialization of control state variables (integrators, ramps, accumulators, variables, etc.). May include fault detection 2 Ready Stand-by state, ready to be switched-on. Includes fault detection, e.g. DC-bus overvoltage or high temperature 3 Calib Calibration state to calibrate ADC channels (remove offsets). Includes fault detection 4 Align Alignment state to find the rotor position and to prepare to start. Includes fault detection 5 Run Motor is running either in open-loop or sensorless mode. Includes fault detection 6 Fault Fault state to switch off the power converter and all the peripherals to a safe state. 7 Input events are the triggers which initiate a change of current state. Input Event Purpose Value e_init_done Asserted when the Init state has finished the task with success 1 e_start Asserted when a user sends the switch-on command 2 e_calib_done Asserted when all the required ADC channels are calibrated 3 e_align_done Asserted when the initial rotor alignment / position detection is done 4 e_stop Asserted when a user sends the switch-off command 5 e_fault Asserted when a fault situation occurs 6 e_fault_clear Asserted when a user sends the "clear faults" command or when the situation allows this 7 e_reset Asserted when a user sends the "reset" command to start over with default settings 8 Output events are used to trigger the Motor Control State Handlers and correspond to actual state. These events are triggered with every state machine call. Therefore, the state machine shall be aligned with the control algorithm. For example, it shall be placed within the ADC "conversion completed" interrupt routine or PWM reload interrupt routine. Finite State Machine Usage The state machine shall be used in good alignment with the control algorithm. The usual way of controlling a motor is to have a periodic interrupt linked with the ADC conversion completed or with the PWM reload event (interrupt). The state machine shall be called within this event handler, right after all the external information is collected (voltages, currents, binary inputs, etc.) to let the state machine decide, which state should be called next. Internal event/state handling inside of the state machine is clearly described by the state machine block definition. Output event triggers are configured to provide clear function-based code interface to the state machine. That means, the output events shall be connected to a function designed to handle the state task. For example, in Run state, the run() output event is triggered with every state machine call, while within the Run state function the whole motor control algorithm is called. If an input information is supposed to switch the state, a simple condition shall be programmed to change the Event variable (defined as a global variable). For example, if a user sends the "stop" command, the Event is set to "e_stop" and the state machine will switch to the Init state. For more complex triggering of output functions, additional output events can be programmed within the state machine definition. Template state handler function is based on the function caller block. In general, the function blocks can work with global variables, thus there is no need for inputs or outputs. Thanks to global Event variable, event-driven state machine can react on events thrown inside a state handler function or outside of the state machine (e.g. based on other asynchronous interrupt). An example of a simple template is shown below. In this example, the function represents the Reset state, which is supposed to be run after the power-on reset or to set all the variables to its default settings. Therefore, the first part is dedicated to hardware-related settings, the second part is covering the application-related settings. The third part checks whether all the tasks are done. If yes, the e_reset_done event is thrown (stored into the Event variable). In this case, the ResetStatus variable is obviously always going from zero to two with no additional influence. Therefore, the final condition may be removed (even by the MATLAB optimization process during compilation). If there is an external condition, such as a waiting for an external pin to be set, then it makes sense to use such "status" variable as a green light for completing the state task and throwing the "done" event. Embedded C code Implementation In default settings, MATLAB Embedded Coder generates the state machine code in a fashion of switch-case structure. This might be not very useful for further code debugging or for manual editing. Therefore, the function call subsystem block parameters should be changed as shown below. The function packaging option is set to "Nonreusable function", other settings might be left at default values. This will keep the state machine code structure in switch-case, however the state handlers function calls will be generated as static functions (instead of putting the code inside the switch-case). Following code sample is a part of the state machine code generated in the stateMachineTest.c example code. The state machine decides based on the State variable, which is internally stored in the stateMachineTest_DW.is_c1_stateMachineTest. Based on the stateMachineTest_DW.Event, a transition is initiated. Finally, the state handler function is called, in this case stateMachineTest_Resetstate(). void stateMachineTest_step(void) { /* ...  */       switch (stateMachineTest_DW.is_c1_stateMachineTest) { /* ... */       case stateMachineTest_IN_Reset:             rtb_y = 1U;             /* During 'Reset': '<S5>:35' */             if (stateMachineTest_DW.Event == stateMachineTest_e_reset_done) {               /* Transition: '<S5>:37' */               stateMachineTest_DW.is_c1_stateMachineTest = stateMachineTest_IN_Init;               /* Entry 'Init': '<S5>:1' */               rtb_y = 2U;             } else if (stateMachineTest_DW.Event == stateMachineTest_e_fault) {               /* Transition: '<S5>:46' */               stateMachineTest_DW.is_c1_stateMachineTest = stateMachineTest_IN_Fault;               /* Entry 'Fault': '<S5>:18' */               rtb_y = 7U;             } else {               /* Outputs for Function Call SubSystem: '<Root>/Reset state' */               /* Event: '<S5>:49' */               stateMachineTest_Resetstate();               /* End of Outputs for SubSystem: '<Root>/Reset state' */             }             break; /* ... */       }‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍ /* ... */ }‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍ The reset state function is compiled based on priorities set in each block of the Simulink model. If no priorities are set, the default ones are based on the order of adding them to the model. Therefore, it is very important to verify and eventually change the priorities as requested by its logical sequence. This setting can be changed in the block properties as shown below. The priority settings is shown after the model is updated (Ctrl+D) as a number in the upper right corner of each block. State Machine Test Application Testing application is designed to test all the features of the state machine, targeting the S32K144EVB. To indicate active states, RGB LED diode is used in combination with flashing frequency. On-board buttons SW2 and SW3 are used to control the application. The application is running in 10 ms interrupt routine (given by the sample time). There is an independent LPIT interrupt controlling the LED flashing. After the power-on reset, the device is configured and the RESET state is entered, where additional HW and application settings are performed. Then, the application runs into the INIT state with a simulated delay of approx. 2 seconds, indicated by the blue LED diode flashing fast. After the delay, the READY state is entered automatically. Both buttons are handled by another state machine, which detects short and long button press. While the short press is not directly indicated, the long press is indicated by the red LED diode switched on. By a short pressing of the SW2, the application is started, entering the CALIB state first, followed by the ALIGN state and finally entering the RUN state. The CALIB and ALIGN states are indicated by higher frequency flashing of the blue LED, while the RUN state is indicated by the green LED being switched on. The application introduces a simulation of the speed command, which can be changed by long pressing of the SW2 (up) or SW3 (down) within the range of 0 to 10,000. Moreover, to simulate a fault situation, the e_fault event is thrown once the speed command reaches value of 5,000. The FAULT state is entered, indicated by the red LED flashing. To clear the fault, both SW2 and SW3 should be pressed simultaneously. The INIT state is entered, indicated by the blue LED diode flashing fast. Following tables show the functions and LED indication. Button Press lenght Function SW2 short press Start the application SW2 long press Increase the speed command (indicated by the red LED diode ON) SW3 short press Stop the application SW3 long press Decrease the speed command (indicated by the red LED diode ON) SW2+SW3 short press Clear faults State LED Flashing Reset - Init Blue period 50 Ready Blue period 500 Calib Blue period 250 Align Blue period 100 Run Green always on Fault Red period 100 any Red always on when a long press of SW2 or SW3 is detected Running the example The example can be built and run along with the Model Based Design Toolbox for S32K14x, v3.0.0. This version has been created using MATLAB R2017a. Please follow the instructions and courses on the NXP Community page prior to running this example. Usage of the S32K144EVB with no connected extension boards is recommended, however this example doesn't use any HW interfaces except of (please refer to the S32K144EVB documentation): S32K144 pin S32K144EVB connector Usage PTD15 J2.2 GPIO output / strength: High / Red LED PTD0 J2.6 GPIO output / strength: High / Blue LED PTD16 J2.4 GPIO output / strength: High / Green LED PTC12 J2.10 GPIO input / Button SW2 PTC13 J2.12 GPIO input / Button SW3 PTC6 J4.4 UART1 / RxD / FreeMASTER PTC7 J4.2 UART1 / TxD / FreeMASTER The application works also with the FreeMASTER application. Users can connect to the target and watch or control the application. The FreeMASTER project is attached as well, however, the ELF file location needs to be updated in the FreeMASTER project settings after the application is built and run.
View full article
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.
View full article
MODEL BASED DESIGN TOOLBOX FOR PANTHER (MPC574xP) Family of Processors 2.0   Model Based Design Toolbox for MATLAB/Simulink supporting Panther (MPC57xP) version 2.0 is now available.   The product is FREE OF CHARGE and it is available for public.   DOWNLOAD Model Based Design Toolbox MBDT      Release Highlights – Model Based Design Toolbox for Panther (MPC574xP) Support for new Panther XDEVKIT-MPC5744P board (ARDUINO style) which works with the new chassis XDEVKIT-MOTORGD for motor control applications. Incorporation of latest Automotive Math and Motor Control Library release 1.1.7. Support for latest MATLAB versions including 64 bits (2015/2016 a/b) New DMA blocks, allowing ADC sampled data to be transferred to memory without CPU intervention through DMA module. New LINFlexD blocks for serial communication support now allowing data send/receive operations through UART. New Memory Read/Write blocks are added and they can now be used to read/write any memory zone. New Custom Initialization block is added and it can be used to extend the configuration of any module outside the default setup prior to the model first step. Support for S32 Design Studio for Power Compiler v1.1 in addition to new compilers versions Wind River DIAB v5.9.4.8 and Green Hills MULTI for PowerPC v2015.1 New Advanced Motor Control blocks, were added and now new functions like Track Observer or Back EMF Observer are provided as Simulink Blocks. Aligned ADC clock frequency from 20MHz to 80MHz (max speed). New ADC channel configuration block is redesigned to be allow configuration without sampling for the ADC channel, making now DMA scenario for transfers possible. New Diagnostics panel can be used to enable/disable multiple consistency checks. New Bootloader build to support UART1 communication. Support in sync with FreeMASTER release 2.0.2.   new!!! HOT-FIX:  Add support for the latest e200 compiler that is released with S32 Design Studio for Power v1.2 . Refer to HotFix_3 setup to have the MBD Toolbox working with latest e200 compiler.   Community Support Available   Support available via the NXP community at: https://community.nxp.com/community/mbdt
View full article
 MODEL BASED DESIGN TOOLBOX for S32K14x Automotive MCU rev2.0  Download the product from Model Based Design Toolbox official webpage   Model Based Design Toolbox: Assists Automotive customers with rapid prototyping and accelerates code development on NXP Automotive MCUs Provides an integrated development environment and tool chain for configuring and generating all the necessary software (including initialization routines, device drivers and a real-time scheduler) Automatic ANSI C code generation from MATLAB/Simulink™ Seamless integration with embedded coder including SIL and PIL models      S32K Automotive MCU rev2.0 Enablement Support for the new S32K144 MCU, S32K144EVB evaluation board and new chasses XDEVKIT-MOTORGD for motor control and XDEVKIT-COMM Integrate the latest Automotive Math and Motor Control Library release 1.1.8 for ARM M4 cores Integrate the latest SDK release version 1.0.0 for S32K Automotive MCU; Integrates FreeMASTER version 2.0.2 Support for latest MATLAB versions including 64 bits (2015b, 2016a/b and 2017a); Example Library for S32K peripherals and Motor Control scenarios; S32K supported peripherals are highlighted on block diagram Multiple enhancements and fixes over the previous version of the Toolbox version 1.0    Help and Support  Please join our Model Based Design Toolbox community for updates and support. Click here to watch a quick install guide video   Click here to watch motor control demo with S32K rev2.0  
View full article
      Product Release Announcement Automotive Microcontrollers and Processors NXP Model-Based Design Toolbox for S32K1xx - 2018.R1     Austin, Texas, USA July 23, 2018 The Automotive Microcontrollers and Processors’ Model-Based Design Tools Team at NXP Semiconductors, is pleased to announce the release of the Model-Based Design Toolbox for S32K1xx 2018.R1. This release supports automatic code generation for S32K1xx peripherals and applications prototyping from MATLAB/Simulink for NXP’s S32K1xx Automotive Microprocessors.   FlexNet Location: https://nxp.flexnetoperations.com/control/frse/download?element=10221477   Activation link https://nxp.flexnetoperations.com/control/frse/download?element=10221477     Technical Support NXP Model-Based Design Toolbox for S32K1xx issues are tracked through NXP Model-Based Design Tools Community space. https://community.nxp.com/community/mbdt   Release Content Automatic C code generation based on S32K SDK 2.0.0 RTM drivers from MATLAB® for NXP all S32K14x derivatives: S32K142 MCU Packages with 16/32KB SRAM (*updated) S32K144 MCU Packages with 48/64KB SRAM (*updated) S32K146 MCU Packages with 128KB SRAM (*new) S32K148 MCU Packages with 192/256KB SRAM (*new) Multiple options for packages and clock frequencies are available via Model-Based Design Toolbox S32K Simulink main configuration block New S32K peripheral support added for DMA, RTC, Registers were added to extend the existing toolbox capabilities. The 2018.R1 peripheral coverage for each of the S32K14x derivatives is shown below: Redesigned the FlexTimer configuration block to support additional features for PWM generation and triggering events Added support for System Basis Chip (SBC) UJA116x configuration Redesigned the main Simulink Embedded Target library for supporting future additions of other S32K derivatives and External Devices for S32K products Implement communication port auto discovery to allow easy configuration for downloading the generated code to NXP targets and new Diagnostic options to helps with model creation or migration. 100% S32K supported peripheral coverage with examples. Currently there 115 examples available as part of the toolbox that exercise all the functionalities supported Add support for External Mode that enables Simulink on the host computer to communicate with the deployed model on NXP hardware board during runtime Enable MATLAB code profiler for NXP targets for measuring the function execution time using Processor-in-the-Loop 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 S32K1xx MCUs and evaluation boards solutions out-of-the-box with: NXP Support Package for S32K1xx Online Installer Guide Add-on allows users to install NXP solution directly from the Mathwork’s website or directly from MATLAB IDE. The Support Package provide a step-by-step guide for installation and verification. NXP Model-Based Design Toolbox for S32K1xx 2018.R1 is fully integrated with MATLAB® environment in terms of installation, documentation, help and examples;   Target Audience This release (2018.R1) is intended for technology demonstration, evaluation purposes and prototyping for S32K142, S32K144, S32K146 and S32K148 MCUs and Evaluation Boards  
View full article
Introduction The aim of this article is to help any user of Model-Based Design to enjoy his/her own custom C libraries or to call any C drivers or components that are not yet supported by NXP's toolbox. This uses the Matlab Coder and requires to include only a MATLAB function block in which the model will call a C function. For more details, you can have a look on the Mathworks Help Center at Integrate C Code Using the MATLAB Function Block- MATLAB & Simulink.   BMS System In my opinion, the greatest way to learn something is "learning-by-doing". So in this tutorial, we will add support for the BMS System in Model-Based Design for S32K. You are already familiar with our toolbox supported boards so let's talk a bit about this BMS system. NXP has a great cell controller IC designed for automotive and industrial applications, more details can be found here MC33772B | 6-Channel Li-ion Battery Cell Controller IC | NXP. For this tutorial, we will use the FRDM33772BSPIEVB | MC33772 SPI EVB | NXP  board, which handles up to 6 battery cells and connects to many NXP controllers via SPI. This is also compatible with the S32K family with some minor jumpers adjustments, but all the instructions can be found on the product page.  So the goal of this project is to be able to read the cell voltages from an MBDT Simulink model. Main Steps In order to include custom code, the user should follow these steps: 1. Add the directory path from which the Simulink will include the directories under Settings > Code Generation > Custom code > Include directories. 2. Insert a Matlab Function block in the Simulink model. This will be used for initialization. The goal here is to include the c headers in the generated code files. This requires to declare coder constant using the coder.const function. That has to be updated in the Build info using coder.updateBuildInfo . Here, the headers and the sources has to be included following this template: %% Adding  header information to the generated code coder.cinclude('driver.h'); %% Adding source files to MakeFile coder.updateBuildInfo( 'addSourceFiles', 'driver.c' ); This operation has to be performed only once. 3. When the user needs to call a custom function from the Simulink, the user must add a Matlab Function block, declare the inputs and outputs as required. Inside the Matlab Function code, the coder.ceval function must be called using the parameters provided as inputs. For example, if the user needs to call a C function called BMS_Init with no parameters, the following line of code will perform that: %% Initializing the BMS driver coder.ceval('BMS_Init'); If the user needs to provide an input parameter, then it will be provided either directly, either using coder.ref  as an argument or using coder.rref if the reference to that value has to be passed. function BMS_Init(parameter)    if( coder.target( 'Rtw' ) )          coder.ceval('BCC_Init', parameter);          coder.ceval('BCC_Init', coder.ref(parameter));     end end This will generate the following code: BCC_Init(true); BCC_Init(&parameter); But if the code is more complex, the easiest way is to declare a wrapper function and to call the wrapper using the coder.ceval. BMS Support This scenario fits on most of our users requirements: to use a piece of code unsupported yet on MBDT. For this IC, NXP already provides the KIT3377x_DRV driver together with an example in S32DS which measures cell voltages and displays it using FreeMaster.   We created an S32K project for the S32K144 board, added the FreeMaster block and an LPSPI Instance according to the settings and the pin requirements by the MC33772 board. The Initialize variable will only be used to call the initialization sequence for the BMS. Now, as we described in the previous chapter, we declared a folder "bcc" that contains the required drivers and some wrappers, also inserted in the Configuration parameters. The initialize function contains a Matlab Call Function. This one includes all the steps described at the second point. What should be noticed here is the check from line 7. All that cinclude code will be called only when the coder.target is Rtw. If the user adds an else condition, that code will be called only when simulate. Now, MBD_MCC_Init is wrapper designed to perform all the initialization steps from the driver. It was easier like this. The MC33772 has been initialized so whenever the user needs the values, he/she must add a Matlab Function block that will provide the values to the model.   The code behind this block has been attached in the next image. The output values from the getCellMeasurements are provided as outputs and inside the get_cellVoltages, it will call the C updateMeasurements function using the coder.wref function. Running BMS Now, after we solved some bugs during code generation   and had successfully built the code, we can run the generated code on the board. The following screenshot represents the Voltages and a variable Current measurement converted by the MC33772.   Conclusions In this article, we presented a method of getting the needed C libraries/drivers/code in the Simulink model using custom code and Matlab Coder. We provided a short step list and a more detailed tutorial for an actual application, a Battery Management System, using NXP hardware. This approach can be successfully achieved either if we use the S32K or MPC Toolboxes. Later edit (1): As requested, I attached the model and the FreeMaster project for achieving the measurements from the MC3377xB (FRDM3377xBSPIEVB) with the S32K144 board using Model-Based Design and custom code. In order to run it, you must follow the steps: 1. Download and unzip the archive there is a bcc folder inside, next to the s32k_mc3377x.mdl. 2. Download the SDK (Embedded SW: MC33771/MC33772 SW Driver | NXP )  BCC SW Driver package for MC33771B/MC33772B (Lite version) and from the SDK folder bcc copy all the files to the bcc folder of the model.  I can not add the SDK driver in the archive since for the BCC SDK there is an agreement that you must read before download. 3. Open the s32k_mc3377x model, go to the BMS_Init function and replace the line 4 string with the full path of the model bcc location folder. 4. After this, the code should be generated and run successfully. Later edit (2): If you are interested to get the solution alongside the instruction on how to connect the MC3377xB and the MPC5744P via Model-Based Design Toolbox, please have a look at this question here: MPC5744P &MC33771B Configuration Later edit (3): As many of you requested, we've added the example code for the S32K144 & FRDMDUALMC33664 to communicate with the MC33771C. See the attached archive. bms_s32k_frdm2_771c_tpl_cc. The bcc driver for the MC33771C is different than the one for the MC33771B and you have to download the missing files from here.   Happy hacking! Marius
View full article
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.  
View full article
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.  
View full article
1. Introduction This article discusses various algorithms for controlling trajectory and speed for an autonomous vehicle.  The car is built with S32K144 and the NXP's Cup car chassis as explained in depth in this article: https://community.nxp.com/docs/DOC-341984. All software used for programming the car is done using MATLAB/Simulink toolbox called Model-Based Design Toolbox for S32K1xx - NXP Support Package S32K1xx - File Exchange - MATLAB Central. The goal of achieving imposed performances for this system is approached in a classical manner using a PID (Proportional Integral Derivative) controller and also by using modern control algorithms: LQG (Linear Quadratic Gaussian), LTR (Loop Transfer Recovery), H2 and H∞.   2. Vehicle Dynamics Model A logical way of creating a formal representation of the physical system is described in the following section. The significant contribution of such representation is outlined in the control algorithms design process. Validation of these algorithms in a simulation environment, where a mathematical model approximates the real system, is a procedure which is going to be undertaken to ensure rectitude and precision for the developed solutions. Simplifying assumptions must be made to create the context of ease in manipulating such a formal representation, considering the existing numerical algorithms. Therefore, the mathematical model will possesses a certain level of compromise between the simplicity of the representation and accuracy related to the real system. Before starting to model the car’s dynamics, a brief analysis of the system is introduced to offer a clear image on the process. The car can be controlled through three independent inputs, duty cycles which are given as inputs to the Simulink blocks: the duty cycle for the servomotor; the duty cycle for the 1st rear wheel and the duty cycle for the 2nd rear wheel. The output of the process is represented by the image camera sees in front of it, the array Y with the converted values of the analog signal transmitted by the sensor. Hence, a Multiple Input Single Output (MISO) process is modeled in the current section of the paper. The actuators are represented by the three motors, two to ensure traction of the car, and one servomotor responsible for the steering. The plant is represented by the actual vehicle, and the sensor is constituted by the camera which provides the image in front of the car. Thereby, Figure 2.1 illustrates the correspondence between the physical ensemble and the control theory components. Figure 2.1 Actuators, plant, sensor Before exposing the equations that describe the dynamics of the system, a representation of the forces that affect the vehicle is illustrated in Figure 2.2, where: XR and YR define the robot frame, δ represents the turning angle of the front wheels, F is the traction force generated by the two DC motors of the rear wheels, Ff denotes the friction force that the vehicle must overcome during its movement, L is the length of the car, measured from the center of the front wheels to the center of the rear wheels, Cx and Cy reactive forces depending on the movement velocity and ω the angular velocity. Figure 2.2 Forces acting on the vehicle Now, writing Newton’s law for the translation motion and considering the decomposition of the forces on the robot’s frame axis, the motion is described as well as longitudinal as latitudinal by: The traction and resistance forces can be expressed based on the two DC motors parameters: where: ui - voltage applied on the inner wheel motor, uo - voltage applied on the outer wheel motor (related to turning behavior), km - DC motor constant, rw - rear wheels diameter, R - winding resistance, Bv - resistance coefficient for the translation motion, μ - friction coefficient, M - mass of the vehicle, g - gravitational acceleration. When it comes to the rotational motion, the equation which describes the vehicle dynamics is given by: where: MFx - moment of Fx force, Md - moment caused by the difference of speeds on the two rear wheels which triggers the car to change its orientation, MFfx - moment of Ffx force, which opposes to the rotational movement, Cw - reaction dependent to the angular velocity and J - moment of inertia. Considering thus the previous formulas for the traction and friction force, the final equation of the rotational movement is: where all the variables have the same meanings as already specified and more than that, Bw represents the resistance coefficient for the rotational motion.  To express the position of the vehicle on the track, an approach based on angles is going to be used to provide a suitable functional description of the process. Therefore, θ represents the angle between the YR-axis of the robot and the XI-axis of an inertial frame, like in Figure 2.3 The θ angle provides information about the car’s position on the given track, and it represents the variable to be measured to ensure the desired behavior of the vehicle.  Figure 2.3 System output - θ angle Therefore, the differential equations that model the vehicle’s dynamics are written in the inertial coordinate system and obtained considering a Newtonian approach as in: The mathematical representation given by the previous differential equations is characterized by nonlinear dynamics. A linearization procedure is therefore implemented to obtain a state-space representation of the given model. For the particular model developed so far, considering the variables and their signification related to the vehicle’s dynamics, the state array is formed by: x' = [θ vx vy ω], while θ represents the output and u' = [δ ui uo] defines the control signals array. The differential equations of the vehicle dynamics are introduced in the Simulink environment for obtaining the linear system. Input and output ports are used for the controlled and measured variables, while a simple logic of mathematical operations blocks, integrator blocks, and signals connections are implemented. Before using the linmod Matlab function to obtain the linearized model, a static operating point must be chosen. When it comes to this, the following assumptions are made: the car travels a straight road, the front wheels are straight, no turning angle, the rear wheels have equal rotational speed and the car is perpendicular on the X-axis of the inertial system coordinate. All these specifications correspond to a duty cycle equal to 0.03, as mentioned previously. For the two rear wheels, a 10% speed is chosen. However, the transfer from the duty cycles transmitted to the motors and the inputs considered for the system in the current model should also be computed. For the two rear DC motors, the voltage applied is proportional to the duty cycle control signal. A 0% duty cycle (no rotational speed) is equal to a 0V power voltage. While the maximum voltage of the DC motors is 5V, and the maximum duty cycle is 100%, it is easy to determine the proportionality factor, which is equal to 5. When it comes to the conversion between the duty cycle of the servomotor and the turning angle of the front wheels, it must be taken into account that the maximum angle physically achievable for the front wheels is equal to 45 degrees. Therefore, the transfer can be modeled by: With all the transfers modeled and all the model's constants replaced with numerical values, a state-space representation is computed for the entire process and the system is described by the following minimal state-space representation: 3. Control Algorithms 3.1 Experimental PID Position Control The actual position of the car on the track is compared to a defined reference and it is desired to maintain the error between these variables as small as possible, with the purpose mentioned in the previous paragraph. The inputs on the rear motors are given by a constant duty cycle equal to 0.1, which represents 10% of the maximum speed that the car can reach. All these information are represented in a schematic manner in Figure 3.1.1 Figure 3.1.1 Position control loop 3.1.1 Position Computing and Reference Defining Relying on the array of intensities returned by the ADC, the following procedure was undertaken to gain knowledge about what the camera sees. The robot was firstly placed on one side of the track, and connected to the FreeMaster tool for real-time data collecting. The experiment was repeated for different positions of the vehicle, and the results are illustrated in the figures below:                              Figure 3.1.1.1 Exemplification of what camera sees for different positions of the car on the track Noticing how the image in front of the camera changes related to its position, it is desirable for the two dips on the graphics to be equally distant from the center of the array. A position finding algorithm is therefore implemented for searching the edges of the road. 3.1.2 Parameters Tunning Based on the error value, the steering input is computed. Bearing in mind the fact that the duty cycle for the servomotor should be in the range of 0.02 – 0.04, the control signal given to the actuator should be bounded for this particular input range. Thus, a scaling factor is introduced before the error is transmitted to the controller. Considering the error range, a convenient scaling factor is chosen. Irrespective of the correspondence of the errors to left or right halves of the road displacements, the magnitude of the signal should be processed by the controller in the same way. The symmetry has then to be dismissed because different values of the duty cycle should be computed to make the car turn left or right. Therefore, the PID controller can return a control signal which is maximum equal to 0.01, for an maximum error value, which then, based on the sign of the position index algorithm returned value, should be added to 0.03 (wheels not steered) for a movement to the left, or subtracted from 0.03 for a movement to the right. Following all the introduced information, the first step into the procedure of tuning the PID controller is to build a proportional controller. A maximum error value, divided by the scaling factor corresponds to a maximum 0.01 control signal. Moreover, knowing that for a proportional controller, which is discrete considering its use directly on the real process: the proportional parameter of the PID controller is computed from the previous formula. The result of the designed controlled system is now illustrated in Figure 3.1.2.1, extracted from the FreeMaster debug tool in real time, while the car completes multiple laps on the given track.The output of the system is illustrated on the Y-axis, the reference is marked with a black line, and the time scale is represented on the X-axis, in seconds. The dips on the graphical representation of the system’s output correspond to the curvatures of the road, where a significant error triggers the wheels steering to keep the car on the track. The wavy portion is the system’s output on the wavy piece of the road, and the almost straight area is the output provided when the car is on the straight piece of the track. It is noticeable that on the straight part of the track, the reference is not completely followed. Also, on a long straight road, only the proportional component is not able to ensure a steady state error equal to zero.                                          Figure 3.1.2.1 System reference and output with P controller Figure 3.1.2.2 Track components: straight, curve, wavy Rising even more the KR factor value does not solve this problem, because the risk of the system’s instability appears in this scenario. Thus, the integrative component should be used, and now the controller is a PI, with the following control law: The Ti value is chosen experimentally, and satisfying results are illustrated in the following figure:                                 Figure 3.1.2.3 System reference and output with PI controller A derivative component is not necessarily required, considering the form of the track (without sudden changes of direction). Inside the PID block which implements the controller in the Simulink environment, besides the parameters choice and also the upper and lower saturation limits of the control signal, the clamping anti-windup method is also used for preventing the controller output from saturating. The sampling time is left to be inherited, this option allowing the Matlab environment to choose the right sampling period considered regarding the timing in the given Simulink model. 3.2 Experimental PID Speed Control The center of the track is now followed, and the behavior of the vehicle is as desired. On longer tracks, the vehicle movement seems like a crawl, and the particularities of the system allow the control of three different inputs. A speed control algorithm is thus implemented to ensure a reduced time in completing a lap. Like any other car, the robot should be able to adapt its speed depending on the track to be traversed. Acceleration and deceleration features should be implemented into the current application to emulate the behavior of a real-life vehicle. Also depending on the road’s particularities, curvatures, distances, a speed limit should be left to be user’s choice. Intuitively, from a driver perspective, the speed should be reduced at the beginning of the curve and then gradually increased on the second part of the curve, as the car leaves it and heads to a straight piece of the road. Taking into consideration this real life behavior, the graphic evolution of the output of the system controlled with the PID position controller seems to illustrate this exact idea. It is noticeable that inside a curve, the error slowly increases as the car approaches the center of the turn, and then decreases while the exit becomes close. A proportional control signal to the speed of the two wheels can be thus computed to take care of this operating mode.The error signal is consequently fed to a P controller which amplifies it considering, for the beginning, that the maximum speed allowed is equal to 0.15 (15%). Therefore, the control loop is completed, as illustrated in the figure below: Figure 3.2.1 Position and speed control loop Assuming that the imposed speed limit is provided by a duty cycle equal to 0.15, as specified in the previous paragraph, and also that, during a turn, it must be reduced to 0.1, the KR factor of the two controllers, one for each rear wheel is given by: The KR general formula can be modified under the desired speed range (how fast should the car go and how fast should it take turns). The control signal given to the rear motors, uk = KRϵk is subtracted from the imposed speed limit to achieve the desired behavior on the curvatures of the road. The car travels the track faster now, but increasing the speed, even more, causes a side-slip of the vehicle during turns. This shortcoming could be improved by taking advantage of the fact that the two rear wheels can be controlled independently. Hence, inside a turn, the outer wheel should have a bigger rotation speed than the inner one, in the same way, an automobile operates. This differential control of the traction wheels is used to increase the stability of the system, improving, therefore, the performances of the vehicle. However, a way of computing the difference between the speeds of the two rear wheels must be implemented. The overall speed of the moving vehicle is given by the two duty cycle control signals, and it is: The ratio between the outer wheel speed and the inner wheel speed is experimentally chosen based on the formula: The experimental procedure is undertaken for obtaining a suitable value for the speed ratio started by choosing this factor equal to 1. For a speed ratio equal to 1 there is no differential control of the rear wheels, both of them having the same rotation speed. The speed ratio produced satisfactory results for a value equal to 1.3. A 1.4-speed ratio factor is also suitable for the application, but increasing it more could cause unwanted behaviors such as the car turning around its axis. With a 1.3-speed ratio factor, a 20% (0.2) speed limit was achieved, with a lower value of 15% (0.15) during turns. Increasing the speed, even more, 25% (0.25) and keeping the lower value at its previous setting produces, in some cases, side-slips of the vehicle outside the track. By reducing the vehicle turning speed, for example, 10% (0.1) does not solve the side-slip issue. The leading cause of this behavior is related to the oval shape of the track, with short straight segments. As on a winding road, the robot should also limit its speed because sudden acceleration and deceleration actions cause undesired system’s reactions and safety issues are definitely to be considered during control algorithms design. Mixing this way of computing two different duty cycles for the two rear wheels, with the proportional controller introduced in the first part of this subsection, which will provide the overall DT, the vehicle shows more stability during the turns than it did without the differential speed control and a bigger speed can be achieved without losing the position requirements. Figure 3.2.2 Computing the rear wheels control signals 3.3 LQG and LTR Unlike the PID regulator, the LQG and LTR control laws are going to be designed in a theoretical manner, based on the mathematical model of the system, obtained in the previous section. However, before implementing the controllers in the Simulink environment for proper simulation and validation of their results, a short analysis of the open loop system is going to be depicted in the next subsection. 3.3.1 Position Computing and Reference Defining As illustrated in the previous chapter of the thesis, the output of the mathematical representation is the angle θ measured between the Y-axis of the robot frame and the X-axis coordinate of the inertial frame. There are also three inputs of the system given by the values of the duty cycles transmitted to the motors. Thereby, the four matrices,A,B,C and D  are introduced as a state-space block in a newly created model in the Simulink environment. However, the simulation does not recognize the output of the system as an angle. Considering the work in a digital environment, its values are increasing and decreasing following the given inputs. This behavior is as expected, assuming that a constant speed on the rear wheels and a certain angle of the front ones produces a variation of the output, increasing or decreasing its value based on the steering direction. However, the output θ is an angle, so the subsequent processing of the signal is realized. The following assumptions are made: the value of θ is measured trigonometrical; the minimum value for θ is 0 radians, and the maximum value for θ is π. It is natural that for bigger angles than π, the real value of the angle is computed by theta real = theta measured − π. Before applying this verification and then modification of the measured value, it must be made sure that the output of the system is not negative; therefore a Simulink block is used to compute its absolute value. Figure 3.3.1.1 Theta angle conversion As noticeable in the previous figure, the system’s output changes its value when the vehicle is going inside curvature of the road, for example. As assumed during the linearization procedure, the car starts its movement from a position which is perpendicular on the X-axis of the inertial coordinate system, thus leading to a θ equal to π/2 . If the camera spots a dark value in front of the car, which represents a black edge that needs to not be crossed, based on the position where the edge is seen, a deviation angle α will be computed in order to express the fact that the car needs to change its direction, less or more abruptly.  Based on this deviation angle, the reference of the control loop is going to change its value to determine the vehicle to turn when edges are spotted. Therefore the reference of the system will be given by: θ+α, with θ the system’s output. From the way of measuring the α angle, given by the following figure, it can be concluded that a positive α angle determines to steer to the left, while a negative one determines the steering to the right, as explicitly illustrated in the following figure: Figure 3.3.1.2 Deviations regarding the trajectory to be followed 3.3.2 Controller Implementation Firtsly, an LQG controller is implemented in the Simulink environment using the lqg Matlab function: where sys is the state-space representation of the system given by the A,B,C and D matrices. QXU is the penalty matrix considering that the cost function to be minimized by the algorithm is written as: The QWU noise covariance matrix is given by: The control signal u is computed with the help of an LQR (Linear Quadratic Regulator) such that J reaches is minimum value. A Riccati equation depending on the state-space representation of the system and the penalty matrices Q and R is solved with this purpose, but these details are not subject of the current description. However, for obtaining such a controller, a full state array x is required. The feasibility of this assumption is not guaranteed considering that in many control problems, not all the state components are measurable. If moreover, the process is affected by noise, a Kalman filter has to be used. After the Kalman filter estimates the full state of the system, the LQR algorithm computes optimally the control signal, based on the state estimation. This procedure is called the synthesis of a LQG controller.  Considering the penalty of the state deviation which needs to be accomplished and also the control signals limitations required for a safety operation mode, the values of these matrices are chosen conveniently. The returned controller is given by a state-space representation which is introduced into a state-space block in Simulink, and connected to the system considering a classical control loop. However, before doing so, the obtained controller is sampled with a convenient sampling period to ensure the functionality of the given process, using the c2d Matlab command. The control signals given by the discrete controller, before being fed to the system, are added to their linearization values and saturation blocks are also used to prevent the damages a very high control signal can produce on the system’s actuators. The implementation on the real system is illustrated in the figure below, where the deviation based on the array returned from the camera is given to the controller as an error signal, as mentioned previously. Figure 3.3.2.1 LQG control loop on the real system As mentioned previously, LQG controller is formed by a LQR and a Kalman filter.  However, when using a Kalman estimator together with a linear quadratic regulator, the robustness of the designed algorithm deteriorates. To overcome this loss of robustness, the LTR methodology is used in this example, as a second control option, to recover the robustness of the linear-quadratic regulator through a modified computation of this controller.  The same reference defining and position computing apply also for the LTR algorithm as well. No modifications are brought to the control loop, except for the controller, which is now computed using the ltrsyn command: where sys is the state-space representation given by the A,B,C and D matrices in. Kf represents the optimal gain filter matrix, while Qf and Rf are identity noise covariance matrices. The recovery of the full-state feedback linear quadratic loop is thus realized with a gain specified by RHO.  3.4 H2 and H∞ Considering the particularities of the current application, the requirements defined for the H2/H∞ control problem are: small errors in reference tracking; rejection of the disturbances which appear at the system’s output; (Considering that the sensor of the system is the camera, which operates as described in the previous chapters, disturbances on the system’s output can be caused by light fluctuations, shadows, etc.) and bounds for the control signals, knowing their technological limits. These requirements translate into the following transfers between the mentioned signals. ϵ = Sr, u = KSr and y = Sdo. The transfers are written considering a standard control loop as in the following figure: Figure 3.4.1 Standard control loop Computing a controller that satisfies the imposed performances requires the consideration of the system in a generalized form given by: In such a configuration, the partition of the inputs and the outputs has the following signification: u1 - external inputs (disturbances, noises, references); u2 - controlled inputs; y1 - controlled outputs (errors to be minimized, control signals to be bounded); y2 - measured outputs. In the case of the current application, this translates into: The closed-loop system is obtained by connecting the controller to the generalized system as in Figure 3.4.1. Figure 3.4.2 Closed loop system The purpose of the H2/H∞ controller computing can be now expressed as: Given a generalized system T with the corresponding partitions of the inputs and the ouputs, the H2/H∞ algorithms design the controller K which measures the system output y2 and computes suitable commandu2. In the same time, the controller K must be computed in order to ensure a stable closed loop system Ty1u1 and such that it minimizes the H2 norm of the closed loop system; respectively it bounds the H∞ norm of the closed loop system, ||Ty1u1 ||∞ < γ, for a given γ > 0.  Considering the imposed performance requirements the generalized system is written in the following form: T represents the system in the generalized form, 1 stands for the number of outputs to be measured and 3 stands for the number of inputs to be controlled. G denotes the transfer function associated with the state-space representation of the system. A discretization procedure is applied in this case too. All the procedure described explicitly for solving the H2 control problem is applicable for the H∞ suboptimal problem too. The only difference is made by the Matlab command which computes the controller which is now hinfsyn and used as: 4. Results and Conclusions For each of the computed controllers, simulations are realized to validate their functionality on the given system. Each closed loop is analyzed for a step reference signal and the results are illustrated in the figures below:                                           Figure 4.1 Reference tracking and control signals computed by the LQG controller for a step reference                                                         Figure 4.2 Reference tracking and control signals computed by the LTR controller for a step reference                                                     Figure 4.3 Reference tracking and control signals computed by the H2 controller for a step reference                                                                                                     Figure 4.4 Reference tracking and control signals computed by the H∞ controller for a step reference The signals evolution over time, as noticeable in the illustrated graphics, does not highlight significant differences between the designed control algorithms. Control signals evolution over time also reflects with accuracy the real behavior of the car. For a positive error, one of the duty cycles of the rear wheels increases, while the other one decreases. For a negative error, they change their evolution symmetrically, thus differentiating between the two types of turning, to the left, respectively to the right. In the same time, the duty cycle control signal given to the servomotor shows a variation between 0.04 for a positive error and 0.02 for a negative one, keeping its values constant at 0.03 when no error is computed. However, H2 and H∞ algorithms represent powerful tools which do not exhibit their full-capacity advantages due to the low complexity of the system’s model. Therefore, a proportionate effort should be put into solving a real-life problem, considering its complexity and performance requirements. The LQG and LTR can also be interpreted as a particular case of the H2 control problem, as detailed in, this explaining the similarity between the time domain solutions between these two algorithms and H2. When it comes to the H∞ method, no significant advantages are enlightened by the time domain graphical evolution either. What is yet remarkable at this control option is represented by the advantages presented in the case of unstructured perturbations affecting the system’s model. As already mentioned in the paper, the nominal model approximates the real system. Therefore a behavioral uncertainty is present throughout the entire design process. Robustness related to this estimations is achieved with the H∞ control option. However, a statistical comparison is illustrated in the following table, which contains the values of the step-response characteristics, computed for the closed loop systems. Considering that the sampling time used for the simulation is equal to 0.02s, as mentioned in the previous chapter, the results are as in the following table: LQG LTR H2 H∞ RiseTime 0.016s 0.0121s 0.0076s 0.0068s SettlingTime 0.022s 0.0196s 0.015s 0.0144s Table 4.1 Step-response characteristics for the closed loop system The required performances are accomplished both with the classical and modern approaches. As concluded previously from the simulation results, no noticeable differences are in the real behavior of the four algorithms illustrated in the current chapter. The system’s model influences the car behavior slightly, compared to the classical PID perspective. Considering the neglect of some of the forces which affect the system, together with model parameters approximation, these results are as expected. Improved performances can be achieved as a future work by including the model uncertainties in a H∞ controller design procedure.
View full article
        Product Release Announcement Automotive Microcontrollers and Processors Model-Based Design Toolbox v3.0.0 2017.R1         October 16, 2017 Model-Based Design Toolbox v3.0.0 for NXP’s S32K1xx Automotive Microprocessors    Main Features: Embedded target support for S32K144 and S32K142 MCUs with example for S32K144EVB-Q100 and S32K142EVB-Q100 evaluation boards Online installer available directly from MathWorks website Add-On Explorer. Installation Guide step-by-step application to provide an improved user experience for toolbox download, installation and license generation from NXP website   Documentation, help and S32K1xx examples fully integrated into MATLAB development environment for ease of use and fast prototyping New peripherals support for: Watchdog (WDOG) Power Management Controller (PMC) Low Power Timer (LPTMR) Cryptographic Services Engine (CSEC) FlexIO for supporting I2C, SPI and UART communications  Add new functionalities for: CAN with Flexible Data Rate (CAN-FD) CAN with Rx FIFO CAN Pretended Networking Blocking or Non-Blocking transmit/receive modes for Communication blocks FreeMASTER configuration block for embedded driver Support for SRAM application download  Enhance the support for all existing Simulink blocks to support basic and advanced mode of peripheral configuration Support for MATLAB 2017b release Integrates the Automotive Math and Motor Control Library release 1.1.9 for ARM M4 cores Integrates the SDK release version 0.8.4 EAR for S32K1xx MCU. NXP’s Model-Based Design Toolbox generates codes based on standard SDK API, covering most of the functionalities exposed by SDK   Download NXP’s Model-Based Design Toolbox for S32K1xx: https://nxp.flexnetoperations.com/control/frse/download?element=9501347 or browse for file here: Model-Based Design Toolbox|NXP    Getting Started Videos: How to install Model-Based Design Toolbox for S32K1xx How to get help with NXP's toolbox for S32K1xx Basic & Advanced modes for configuration of S32K1xx Motor Control example with S32K1xx FlexIO Communication example with S32K1xx Low Power Modes example with S32K1xx   Support: https://community.nxp.com/community/mbdt        
View full article
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.
View full article
This video shows: - motor control typical setup with S32K144 rev2.0 Evaluation Board; - Simulink model for a BLDC motor control; - how to setup Simulink to generate ANSI C code for S32K144 rev2.0 MCU; - quick tour of the Model Based Design Toolbox; - quick tour of the FreeMASTER data visualizer; - Motor Control example running with DevKit S32K144EVB and MotorGD shield;
View full article
  1. Introduction 1.1 A New Control Option For NXP Cup Race Car    NXP Cup car development kit is usually based on NXP's Freedom KL25Z board for motors control and image evaluation. However the control of the race car can be done with multiple NXP solutions.    In this article, a solution based on S32K144EVB board will be presented along with a programming approach based on MATLAB/Simulink Model-Based Design Toolbox for S32K. Additionally another tool provided by NXP - FreeMASTER - will be used to debug in real time the application.     As S32K144 pinout is not compatible with the default Landzo board pinout, an additional board to route the pins to the desired destination has been built. Complete details on the mapping of the pins are provided in the tutorial.   This article is structured as a tutorial detailing all the steps and providing all the source code to enable one to use this solution. However the control application is done very simple - on purpose - and uses just 10% of the speed to prove the concept.  Table 1. Freedom KL25Z vs. S32K144 features Freedom KL25Z Board Features S32K144 Board Features 32-bit ARM Cortex-M0+ core, up to 48 MHz operation 32-bit ARM Cortex-M4F core,  up to 112 MHz operation Voltage range: 1.71 to 3.6 V Voltage range: 2.7 V to 5.5 V • Up to 128 KB program flash memory • Up to 16 KB SRAM • Up to 512KB program flash memory • Up to 64 KB SRAM • Clock generation module with FLL and PLL for system and CPU clock generation • 4 MHz and 32 kHz internal reference clock • System oscillator supporting external crystal or resonator • Low-power 1kHz RC oscillator for RTC and COP watchdog •  4 - 40 MHz fast external oscillator (SOSC) with up to 50 MHz DC external square input clock in external clock mode •  48 MHz Fast Internal RC oscillator (FIRC) •  8 MHz Slow Internal RC oscillator (SIRC) •  128 kHz Low Power Oscillator (LPO) • 16-bit SAR ADC • 12-bit DAC • Analog comparator (CMP) containing a 6-bit DAC and programmable reference input  • Up to two 12-bit Analog-to-Digital Converter (ADC) with up to 32 channel analog inputs per module • One Analog Comparator (CMP) with internal 8-bit Digital to Analog Converter (DAC) •  Low-power hardware touch sensor interface (TSI) •  Up to 66 general-purpose input/output (GPIO) •   Non-Maskable Interrupt (NMI) •   Up to 156 GPIO pins with interrupt functionality • Two 8-bit Serial Peripheral Interfaces (SPI) • USB dual-role controller with built-in FS/LS transceiver • USB voltage regulator • Two I2C modules • One low-power UART and two standard UART modules   • Up to three Low Power Universal Asynchronous Receiver/Transmitter (LPUART/LIN) modules with DMA support and low power availability • Up to three Low Power Serial Peripheral Interface (LPSPI) modules • Up to two Low Power Inter-Integrated Circuit (LPI2C) modules • Up to three FlexCAN modules • FlexIO module for emulation of communication protocols and peripherals (UART, I2C, SPI, I2S, LIN, PWM, etc) • Six channel Timer/PWM (TPM) • Two 2-channel Timer/PWM modules • 2 – channel Periodic interrupt timers • 16-bit low-power timer (LPTMR) • Real time clock • Up to eight independent 16-bit FlexTimers (FTM) modules • One 16-bit Low Power Timer (LPTMR) with flexible wake up control • Two Programmable Delay Blocks (PDB) with flexible trigger system • One 32-bit Low Power Interrupt Timer (LPIT) with 4 channels • 32-bit Real Time Counter (RTC) • 4-channel DMA controller, supporting up to 63 request sources • 16 channel DMA with up to 63 request sources 1.2 Resources Model-Based Design Toolbox – Tool used to create complex applications and program the S32K144 MCU directly from the MATLAB/Simulink environment. This tool allows automatic code generation for S32K144 peripherals based on configuration of the Simulink model done by the user. S32K144-Q100 Evaluation Board – Evaluation board from the S32K14x family used for quick application prototyping and demonstration. NXP Cup Development Kit – Information about the hardware components of the development kit and instructions regarding the car assembling. Software which is helpful for the project design is also presented. FreeMaster Debugging Tool – Real-time data monitor tool which shows in both graphical mode (as a scope for example) and text mode the evolution of variables in time. It is suitable to monitor application behavior in real time during execution of the code.  TSL1401 Datasheet – Information regarding the camera configuration. Excel Spreadsheet (attached at the end of the document) with routing information to map pins from Landzo to S32K144 board. 2. Hardware Setup    After assembling all the hardware modules as indicated in the development kit the car will look like in the next image. It should be mentioned that for the S32K144 EVB to system board connection an S32K adapter board was created. Fig 1. Hardware setup 2.1  Hardware Modules    The hardware modules of this application and the way the peripherals of the S32K144 MCU are communicating with those is summarized in the Fig. 2. To understand more about the control of the motors, please check chapters 3.4.4 and 3.4.5. For learning how to debug the application using the Freemaster software, take a look at the chapter 4 where a detailed description is presented. A similar indication is given also for the camera information collecting. Chapter 3.4.1 and 3.4.2 provide a close-up image of the operations that need to be done in order to make the car “see”. Fig 2. System block diagram 2.2  Hardware Validation Steps    After connecting all the hardware modules, connect a USB cable to the PC. Connect other end of USB cable to mini-B port on FRDM-KEA at J7. When powered through USB, LEDs D2 and D3 should light green like in the picture below. Also, once the S32K144 board is recognized, it should appear as a mass storage device in your PC with the name EVB-S32K144.        Fig 3. LEDs to validate the correct setup 3. Model-Based Design Application 3.1  Application Description    The Model-Based Design approach consists of a visual way of programming, which is based on blocks. A block implements a certain functionality, such as adding two numbers. In case of the NXP's Model-Based Design Toolbox which is specifically developed for the S32K14x family, a block implements a functionality of a MCU peripheral, such as turning on the green led on the board. Each block has a different functionality and for a complex application, multiple components should be used together so they can provide the best solution for the problem proposed. For example, if you want to toggle the green led at every 10 seconds, you are going to add a new block to your design, one that can count those 10 seconds and then trigger an action when the count is over, which is toggling the led. Connection between the blocks should be made accordingly to your application system model. When building the model, the code that stands behind the blocks and implements the connection logic between them is automatically generated and downloaded on the embedded target. Doing so, code errors are certainly eliminated, and a faster design process is accomplished.    For using the Model-Based Design Toolbox for S32K, the MATLAB programming platform should be installed on the PC you are working on. Make sure that you respect all the System Requirements that you can find on the following link (Model Based Design Toolbox). Follow the installation steps from the Install and Configuration Steps and now you are ready to develop your own model-based design application.           3.2  Application Scheme    The generated code from the Simulink model is downloaded on the S32K144 MCU. A mapping between hardware and software for this application is illustrated in the figure below: Fig 4. Hardware to software mapping    The hardware components are controlled by the application through the peripheral functions of the S32K144 MCU. This board is connected to the other hardware modules by using an adapter board. In the link NXP Cup Development Kit there are information regarding how to connect the camera, servo and motors modules on the System and Driver Boards. Thus, the software generated signals are transmitted to the modules that need to be configured and controlled (camera, servo, motors). Fig 5. Application Scheme    When you open the Simulink model, this structure shown in Fig. 6 will be displayed. The functionalities are grouped in areas, which area containing a small description of what it is computed inside it. There are blocks and connections between them like mentioned before. Based on the image given by the camera, the steering and the speed of the car should be controlled. More details about how each of the subsystems works are provided in the following chapters. Fig 6. Simulink top level system 3.3 Application Logic    The application logic is described by the following block diagram. The signal from the camera is converted and the data is stored in an array. Based on the elements of the array (description of the image in front of the car), an algorithm will compute how much does the car have to steer its front wheels. This is expressed in a duty cycle value of a signal, signal which will be directly transmitted to the servo module. A constant speed, 10% of the maximum reachable of the car, it is also given as a duty cycle of the signal which will control the two rear motors. Fig 7. Application logic diagram   3.4 Simulink Model Components 3.4.1 Camera Configuration                 The camera module has a major importance in the project, because it is used to scan and process the track in front of the car. Firstly, for the main purpose of the application: control the car and maintain its position on the desired direction, the camera module should be configured so it can receive the analog signal properly. After the camera receives the analog signal, the application converts it into 128 digital values on the basis of which control decisions will be taken. There are 128 digital values for a conversion because the line scan camera module consists of a linear sensor array of 128 pixels and an adjustable lens. As specified in the datasheet, for the camera module configuration, two signals must be generated, a clock and a serial input (CLK and SI). Fig 8. Waveforms for camera configuration    To validate the functionality of this module, you should open the FreeMaster and check that the camera is working properly. Open the .pmp file and watch the conv variable evolving on the recorder. Put a white paper in front of your camera and then move an object in front of it. Every time the camera spots a dark color, its graphical evolution presents easy observable dips like in the picture below (blue graphic).                                                                                      Fig 9. Dips caused by dark objects CLK Signal    For the CLK signal generation, a FTM (FlexTimer) block is used. This block generates a PWM signal with a duty cycle given as an input (DTC – Dutcy Cycle Camera). The duty cycle has to be 0.5 (50%) as specified in the datasheet. The PWM signal is then passed to the corresponding pin of the camera module through the S32K144 board.    Check the Landzo_car pins to S32K144EVB file for the mapping and connections.     The frequency of the clock signal was chosen considering the imposed value range in the datasheet. (fclock between 5 and 2000 kHz).       Fig 10. Generating the CLK signal      When configuring the FTM block, the following block parameters will be available:                    Fig 11. FTM block parameters    The FTM functionality has 4 different modules, each of them with 8 channels grouped in pairs (for each channel an output pin can be selected). After checking the Landzo_car pins to S32K144EVB file for the corresponding pin of the camera CLK, the choice of the FTM module and the pair should be done (FTM0_CH1 means that the pin is connected to the FTM0 module, pair 0-1). It should also be mentioned that the camera module is connected on the CCD1 interface of the System Board in the hardware setup of this application. Another linear interface CCD2 is available for user usage, as specified in the description of the development kit. The frequency of the signal can also be set from the editbox in the Frequency Settings groupbox. An initial duty cycle value equal to 0.5 was set according to the datasheet.    There are two operation modes for each pair of channels and they can be chosen from the popup box next to the pair selection. These modes are called independent and complementary. Let’s give them a short description.    By setting channel n in the Complementary mode, the output for the channel n+1 will be the inverse of the channel n output and the block will have only one input. In the Independent mode, the channels have independent outputs, each one depending on the duty cycle given as an input on that channel (2 inputs for the block in this case). The CLK signal of the camera is transmitted to a single pin of the hardware module, so there is no need for two channels to be configured. Only one is enough to output the desired waveform (in complementary mode, only the first channel of a pair will be set; ex: channel 0, channel 2, channel 4, channel 6). That is why the Complementary option is chosen in this case. The input will be the 50% duty cycle on the basis of which the CLK signal will be generated. The channel 7 will now be the inverse of the channel 6 but in the next picture it can be observed that the channel 7 does not have a pin to output the signal to, because the inverted CLK signal is not needed in the current application.                   Fig 12. FTM output signals SI Signal      The SI signal’s period must provide enough time for 129 CLK cycles, as the timing requires (datasheet). 129 CLK cycles are needed with the purpose of acquiring 128 samples of the analog signal received by the camera. In order to meet all the specified conditions for a normal operation mode, the algorithm to create the CLK and SI waveforms as required uses two Periodic Interrupt Timers (PIT) blocks. Fig 13. PIT blocks    An interrupt represents a signal transmitted to the processor by hardware or software indicating an important event that needs immediate attention. The processor responds to this signal by suspending its current activities, saving its state and executing a function called an interrupt handler to deal with the event. The interruption is temporary, and, after the interrupt handler finishes, the processor resumes its normal activities.    A PIT block is used to trigger an interrupt handler to execute at every timeout of a counter. The Function-Call Subsystems linked to the PIT blocks represent the actions inside the interrupt handler. The interrupt handler will be triggered every Period(us). For the first PIT, it will be triggered every 20000us and for the second one every 100us. This means that every time the counter reaches the value specified in the block configuration parameters, the Function-Call Subsystem is triggered, the actions inside of it executed and the counter reinitialized. Fig 14. PIT block parameters    The PIT functionality has 4 channels, and they are implemented based on independent counters. The channel 0 is not available for user usage because it is configured to trigger the execution of the entire model at every period of time specified in the model configuration parameters.    The last checkbox from the block parameters is used to start the counter immediately after the application initialization, without waiting for other events.    Considering all the information mentioned above, the timing of creating the waveforms as required involves the following actions:      at every 100µs (CLK signal’s period) the next things happen: Fig 15. Actions in the 100us interrupt           C variable, which counts the clock cycles, is incremented; If C >=2, the SI signal is turned from high to low. (value 2 was chosen to keep the SI signal high for the convenient amount of time as specified by the tw, tsu, th and ts parameters. Their values can be found in the datasheet)                    Fig 16. Timing for camera configuration    A GPIO (General Purpose Input/Output) block is used for this and its role is to send the value given as an input to the selected pin which can be selected from the dropdown menu available in the block configuration parameters). Fig 17. Setting SI signal LOW Fig 18. GPIO block parameters A conversion is started and if C < 128, the converted values (analog-digital conversion of the received signal from the camera) are stored in an array of 128 elements (Store the converted values into an array subsystem is triggered) and into the conv array. Conv variable is used for the debugging process which will be later detailed.          at every 20ms (SI signal’s period) the next things happen:        SI signal is turned from low to high using the same GPIO functionality;       The clock cycles counter C is reinitialized;             Based on the values of the array (high values for white, low values for dark) and on their indexes, the duty cycle (DTS – Duty Cycle Servo) which controls the              Servo is computed (it controls the car to turn left or right with a certain angle); Fig 19. Actions in the 20ms interrupt 3.4.2 Camera Reading    After the camera module is configured (SI and CLK signals generated as specified), the data acquisition can be started. The signal given by the camera is converted into digital values which are stored in an array. The conversion implies the usage of the ADC (Analog to Digital Converter) functionality. Taking this into consideration, a configuration block for the ADC should be added to the Simulink model.         Fig 20. ADC configuration block    The ADC of the S32K144 has two modules (ADC0, ADC1) each of them with up to 16 external analog input channels and up to 12-bit conversion resolution. The camera module is connected to the CCD 1 linear interface of the System Board. The Landzo_car pins to S32K144EVB file specifies that the pin of the camera module which receives the analog signal is ADC1_CH10, so the ADC 1 module should be configured. A 12-bit conversion resolution was chosen for improving the accuracy of the sampled data.     An analog to digital conversion should happen every 100us as specified in the Timing section, because 128 samples of the input signal need to be acquired (every time the C variable is incremented, a value should be stored in the conversion array). Fig 21. Start of conversion    Considering the facts mentioned in the previous paragraph, every time the subsystem of the PIT block is triggered, the conversion is started (an ADC Start block is used) and if C < 128 the sampled data is stored into the array that will consist the information on which basis the servo control decision will be taken. Variable C is the index of the array elements and each result of the conversion represents the value of an element. Following this algorithm, the Y array is created and it is going to be used in the next chapter where the algorithm which computes how much the car should steer, based on the image of the track in front of it, is described. For putting the values into the array an assignment block is used. Fig 22. Storing conversion values to Y array     3.4.3 Camera To Steering Algorithm    The algorithm presents a basic approach and uses an if-else logic. Before giving it a short description, a couple of things should be mentioned.   Considering the reference voltage of the ADC module of the microcontroller which is 5V and the 12 bit resolution of the conversion, the resolution on a quantum is 5 / 4095. But the camera is powered by a voltage approximately equal to 3.4V, thus resulting a value which varies around 3.4 / ( 5/4095) = 2785. This value is the maximum that the ADC can provide when the camera spots white in front of it. The light conditions in the room represent a major factor that contributes to variations of this value.   The Servo of this kit needs a 20ms period PWM signal with the pulses duration equal to 600µs for a neutral position of the wheels, 400µs for the wheels turned maximum left, and 800µs maximum right. This results in the following values for the duty cycle (0.03 - the car goes forward, 0.02 – the car turns maximum right, 0.04 – the car turns maximum left). The 0.02 value should be replaced by 0.023 in order to obtain a proper operation mode due to the servo’s construction particularities.      The array with the converted values (Y) is iterated. If a dark value is found (the difference between ‘maximum white’ and the value of the current element is bigger than a threshold), the duty cycle is computed to determine how much right or how much left the front wheels should turn. If a dark value is spotted in the first half of the array, the car should turn right, or left if found in the other. But the camera gives the image from right to left so the turning ways are opposite (left if a dark value is spotted in the first half of the array, right for the second one).    After determining the way of the steering, left or right, the DTS is computed proportionally with the index of the array where a dark value is found. If a value representing a dark color is spotted at the beginning or at the ending of the array, it means that the what needs to be avoided is not exactly in front of the car, but more to one side of it, so a steering with a small angle should be effective in order to keep the car on the runway. On the other hand, if a small value is found more to the middle of the array, a wider angle of steering should be computed in order to ensure the avoidance of the dark color and the car moving off the track.     Fig 23. Matlab function for computing the DTS 3.4.4 Set The Servo    The DTS is then passed to another FTM_PWM_Config block to generate the signal needed to control the Servo.       Fig 24. FTM block for controlling the servo      In order to do so, the block should be configured with the following parameters, which have the same signification as mentioned in chapter 3.4.1:                 Fig 25. FTM block parameters    According to the hardware connections from the S32K adapter board and the current setup, only one Servomotor is used, and this is the STEERINGPWM1 mentioned in the file with the mapping between the Landzo car pins and the S32K144 board. The allocated peripheral for this module is the FTM0_CH1, which means that the module 0 should be chosen from the configuration parameters together with the 0-1 pair of channels. To control the servo, only one signal is needed, so there is no need to use 2 channels. The complementary mode could have been used here, like in the camera CLK signal configuration, but doing so, only the configuration of channel 0 would have been possible and channel 1 is requested for the application. By choosing the independent mode, a duty cycle input will be available for the both channels of the pair, and because only channel 1 is needed for the control of this module, an input equal to 0 will be given to the other one. The frequency is set to 50Hz considering the motor construction particularities and a duty cycle equal to 0.03 (wheels not steered) is set as an initial value.     Fig 26. FTM output signals 3.4.5 Set The Motors    For the two rear motors, the same principle applies. The duty cycle (DT) is configured by default at the 0.1 value which will cause the car to move along the track with 10% of its maximum speed.     The frequency of the PWM signal that controls the motors is 5000Hz. This value is in the range specified in the datasheet of the motor drivers mentioned in the schematics.                 Fig 27. FTM block for controlling the traction motors     For the control of a single motor, two signals are needed. The schematics of the Motor Driver board indicate that for the control of each motor two integrated circuits are used (BTN7960). They form an H bridge which looks as in the picture below.                 Fig 28. H bridge    To make the motor spin, the potential difference of the points the motor is connected between must be different from 0. It can be observed that each integrated circuit needs an input signal. The pins that give the input signals to the circuits are corresponding to the output channels of the FTM block. Let’s take for example the 1st rear motor. It is controlled by a FTM Config block which outputs on the following channels.                     Fig 29. FTM output signals    By setting and keeping channel 3 of the FTM Config block channels to 0, an input equal to 0 will be transmitted to one of the BTN modules as an input on the IN pin (for example, to the right one). This will trigger the right lower transistor to act like a closed switch. The transistor above it will remain opened, so the voltage of the OUT point will be 0V. The channel 2 corresponds to the other integrated circuit, and a positive input will be received by this one on the IN pin (left side of the picture). Now, the left upper transistor will act like a closed switch, and the one below will remain open, making the OUT point’s potential to represent a positive value (depending on the duty cycle given as an input to the FTM block). Thus, a potential difference is created and the motor will start spinning. 3.4.6 Configuration Block    In addition to all these, the model needs also a configuration block which is used to configure the target MCU, the compiler, the system clock frequency, etc. A configuration block is needed in all the models because it ensures the communication with the target. Fig 30. Model configuration block    The operation frequency can be chosen from the MCU tab of the block parameters window. For this model, it was set at 80Hz. The board model, the SRAM and the clock frequency can also be set from the MCU tab. Fig 31. Configuration block MCU tab    If you want to change the compiler and also the optimization levels, click the Build Toolchain tab and take a look at the available options presented in the picture below. From this tab you can also choose the target memory for the model which can be FLASH or SRAM.                   Fig 32. Configuration block Build Toolchain tab    The application is downloaded on the target through OpenSDA. OpenSDA is an open standard serial and debug adapter. It bridges serial and debug communications between a USB host and an embedded target processor. Make sure that the Download Code after Build option is checked in order to see your application running on the target.                   Fig 33. Configuration block Target Connection tab    For additional information about the blocks used in this model, right-click on them and choose the ‘Help’ option available in the menu. 4. How To Debug The Application Using FreeMaster    In order to use FreeMaster for debugging and managing the information from your application, a FreeMaster configuration block must be used in the Simulink model. Fig 34. FreeMaster configuration block    The block parameters should be configured as in the following picture: Fig 35. FreeMaster configuration block parameters    The interface field specifies the communication interface between the application and the FreeMaster. LPUART1 is chosen in this example because it is directly connected to the OpenSDA. OpenSDA is an open standard serial and debug adapter. It bridges serial and debug communications between a USB host and an embedded target processor.    The BaudRate represents the speed of data transmission between the application and the FreeMaster and it is expressed in kbps. The receive data pin and the transmit data pin should be always configured to PTC6, respectively PTC7 (for the LPUART1 interface) because these pins are connected to the OpenSDA Receive and Transmit pins, as specified in the HMI Mapping.       Fig 36. OpenSDA to LPUART1 connection    By clicking the Show Advanced Options checkbox, multiple settings are available and their functionalities are all specified in the Help file which will open after clicking the Help button in the Block Parameters tab.    The variables that need to be observed changing over time must be declared Volatile. The variables already added to the FreeMaster project are declared using the Data Store Memory block.                 Fig 37. Global Variables    The Volatile option can be chosen from the Block Parameters Tab. After double clicking the Data Store Memory block, click the Signal Attributes tab and in the Code Generation groupbox, set the Storage Class option to Volatile (Custom), as in the picture below.  Fig 38. Data store memory block parameters    For calling the FreeMaster data acquisition each time a subsystem is triggered, a FreeMaster Recorder Call block should be added in the subsystem where the variables that you want to record are computed. Thus, a recorder block is placed in the subsystem which is triggered at 100us for recording the evolution of C and conv variables. Fig 39. FreeMaster recorder call    To check the functionality of the FreeMASTER, open the .pmp file with the same name as the Simulink model and click on the red STOP button in order to initialize the communication with the S32K144 evaluation board. Fig 40. Start/Stop FreeMaster communication    If errors appear, click on the Project menu and open the Options window. Make sure that the port value is the same as the one on which your S32K144 is connected (you can check the COM number of the evaluation board in the Device Manager window). Make sure also that the Speed is the same as the baud rate of the FreeMaster Config block.       Fig 41. FreeMaster communication setup    Click on the MAP Files tab and ensure that the default symbol file is the .elf file from the folder that is created when you build your Simulink model. It should be called (your_model_name.elf).           Fig 42. FreeMaster .elf file    Once the connection is set and the app working, you will observe how the values of the variables in the Variable Watch are changing.    Click on the Recorder option from the left side of the window in order to see the graphical evolution of the variables.    You can add or remove variables from the watch by right-clicking inside the Variable Watch area and choosing the Watch Properties options.    Right clicking on the Recorder will provide a Properties option as well. Use that for selecting the variables that you want to display and for many other options.           Fig 43. FreeMaster recorder properties 5. Autonomous Intelligent Car Demonstration And Hints For Improvement 5.1 Demo    If you want to make sure that everything works as it is supposed to before actually putting the car on the track, you can use the FreeMaster tool to visualize the evolution of the variables of your project. Considering every setup was made as specified, here is what you should expect to see. Fig 44. Variable Watch    The two rear motors duty cycle and also the one for the camera CLK signal should have constant values all the time (0.1 respectively 0.5). The DTS should vary its values between 0.023 and 0.04 as mentioned in the Camera to Steer algorithm chapter. C variable must be incremented every 100us and reset every 20ms, this meaning that when it reaches 200, it should be set back at 0. This evolution can also be graphically observed by using the recorder option. Conv variable and Y array represent the conversion result and all the bottoms of the conv graphical evolution represent the existence of a dark color in the visual field of the car.    A demonstration video with the car following the track for a lap is attached to the current content.   5.2 Improvement Areas    The application proposed uses a basic if-else algorithm in order to compute the steering of the front wheels based on the track in front of the car. A proof of the concept that the vehicle can be controlled and kept on the path using a S32K144 board and a Model Based Design approach is realized in the presented solution. Major improvements regarding the lap time could be achieved by developing a way to control also the car speed which now is at a constant value. Many other hardware and software solutions can be designed and implemented with the purpose of obtaining the fastest autonomous self driving car for the NXP Cup. NXP CUP - LINE FOLLOWER WITH MODEL-BASED DESIGN TOOLBOX FOR S32K MICROPROCESSOR
View full article
      Product Release Announcement Automotive Microcontrollers and Processors NXP Model-Based Design Toolbox for S32K1xx – version 4.1.0     Austin, Texas, USA July 22, 2019 The Automotive Microcontrollers and Processors, Model-Based Design Tools Team at NXP Semiconductors, is pleased to announce the release of the Model-Based Design Toolbox for S32K1xx version 4.1.0. This release supports automatic code generation for S32K1xx peripherals and applications prototyping from MATLAB/Simulink for NXP S32K1xx Automotive Microprocessors. This new release adds support for S32K116 and S32K118 microcontrollers, AUTOSAR applications code generation, Local Interconnect Networks (LIN) support and many other various new functionalities to help customers with rapid prototyping with NXP S32K microcontrollers.   FlexNet Location: https://www.nxp.com/webapp/swlicensing/sso/downloadSoftware.sp?catid=MCTB-EX   Activation link: https://www.nxp.com/webapp/swlicensing/sso/downloadSoftware.sp?catid=MCTB-EX     Release Content Automatic C code generation based on S32K SDK 3.0.1RTM drivers from MATLAB® for NXP all S32K1xx derivatives: S32K116 MCU Packages with 32QFN and 48LQFP (*new) S32K118 MCU Packages with 48/64 LQFP (*new) S32K142 MCU Packages with 48/64/100LQFP (*updated) S32K144 MCU Packages with 48/64/100LQFP and 100BGA (*updated) S32K146 MCU Packages with 64/100/144LQFP and 100BGA (*updated) S32K148 MCU Packages with 144/176LQFP and 100BGA/QFP (*updated) Multiple options for packages and clock frequencies are available via Model-Based Design Toolbox S32K Simulink main configuration block Integrates the Automotive Math and Motor Control Library release 1.1.17 for: S32K11x based on ARM M0+ cores; S32K14x based on ARM M4F cores; Multiple S32K1xx peripheral support. The peripheral coverage for each of the S32K1xx derivatives is shown below: S32K116 S32K118   S32K142   S32K144     S32K146 S32K148 Add support for Local Interconnect Network (LIN) for all S32K1xx devices Add support for Motor and Solenoid Drivers devices MC33GD3000, MC34GD3000, MC33937 and MC34937 Extend support for System Basis Chip (SBC) with UJA113x blocks 100% S32K1xx supported peripheral coverage with examples. More than 230 examples available as part of the toolbox that exercise all the functionalities supported Add support for CLASSIC AUTOSAR Application Layer Simulation and Code Generation for S32K1xx devices. This feature allows customers to build, simulate and test AUTOSAR Application directly on S32K1xx microcontrollers to check for correct functionality and performance using build in profilers. 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 S32K1xx MCUs and evaluation boards solutions out-of-the-box with: NXP Support Package for S32K1xx Online Installer Guide Add-on allows users to install NXP solution directly from the Mathwork’s website or directly from MATLAB IDE. The Support Package provide a step-by-step guide for installation and verification. NXP Model-Based Design Toolbox for S32K1xx version 4.1.0 is fully integrated with MATLAB® environment in terms of installation, documentation, help and examples;    Target Audience This release (4.1.0) is intended for technology demonstration, evaluation purposes and prototyping for S32K116, S32K118, S32K142, S32K144, S32K146 and S32K148 MCUs and Evaluation Boards       
View full article
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.  
View full article
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.  
View full article
This video shows how to build a simple S32K application with NXP's Model-Based Design Toolbox that consists in: Read the SW2 push button state at each 0.1 seconds Switch on/off the Blue LED Record the value of the push button and display its state via serial communication in FreeMASTER
View full article
1. Introduction The scope of this article is to show how easy it is to use MBDT, FreeMASTER and some knowledge in electronics to create a simple and useful project: monitor USB voltage and current consumption.  I used this setup it to monitor USB voltage and current while my smartphone is charging, but it can be used in other purposes too, like monitoring power consumption of some devices connected on USB charger/power bank/PC, or it can be used to find some charging issues, or maybe you just want to find out if your phone charger supports fast charging, or to characterize a power bank.  2. Overview 2.1 Functional Description This project can measure USB voltage and current by measuring USB voltage and a voltage drop across a resistor through which current flows from a USB power source to a USB load. The voltage given by current flow is amplified by an electronic circuit and sampled by MPC5744P-DEVKIT board through the ADC converter, then data is sent to PC and then are displayed through a FreeMASTER project as numerical values and as oscilloscope chart. The MPC5744P-DEVKIT board is programmed by MBDT. To build this simple project, you need three components: Matlab with MBDT toolbox installed, FreeMASTER Run-Time Debugging Tool, a very simple electronic circuit, and an MPC5744P-DEVKIT.  As can be seen in fig.1, the project can be split into two main parts: Hardware Setup and Software Setup. Fig. 1: USB Voltage And Current Monitor block diagram 2.1 Hardware Setup Custom Electronic Board The simplest way to measure current is to use a simple resistor connected in series with the load (USB output in our case). The Ohm law gives us a linear relationship between voltage and current in an electrical circuit: U = R * I  U is the voltage (measured in volts V) drop across the resistor, R is the resistance of the resistor (measured in ohm Ω) and I is the current (measured in amps A) which we need to measure. Most of the USB chargers can supply a maximum of 3A and most of the smartphones can drain less than 3A. Giving that I considered designing this circuit to measure around maximum 3A. Let suppose that we use a simple 1ohm resistor. If we do simple math using Ohm formula, then it can be seen that for 3A the voltage across our resistor (there) will be 3V (U = 1 * 3). Fig. 2: USB connectors and current "sensor" In Fig. 2 on the left side is a USB input connector, on the right side is the output USB connector and both GND lines are connected through R1 current sensor. The current "I" will flow, as can be seen in Fig. 2, from USB input through VBUS  line to VBUS on USB output, than will flow through our load connected to USB output and then through GND on the same connector thru R1 and at least to GND on USB input connector. This current will create a voltage across R1 (UR1) equal with 3V (if we use 3 amps current and 1-ohm resistor). One of USB standard charging it specifies that the lowest (standard) voltage it's 5V. In our case, using this 1 ohm resistor will cause 3V loss, then the voltage at USB outputs will be 2V (unacceptable). In most of the digital electronic circuits, when it's used 5 volts power, the voltage tolerance it's about 10% (0.5V) which means the voltage can be between 4.5V and 5.5V. Let's try to create a maximum voltage drop across this resistor about 3 times lower than the 0.5V, e.g.: 150mV. Then the current sensor resistor is R1 = 0.15V / 3A = 0.05ohm.  To measure this drop voltage we could use any ADC channel on MPC5744P-DEVKIT, but if the voltage reference of ADC is set to 5V, the resolution of ADC is 5V/4096 = 1.22mV, which means the equivalent ADC resolution corresponding to current measurement is about 24mA (1.22mV correspond to 24mA). If we consider electrical noise on USB connectors, it's very possible that the out signal will be "drowned" in electrical noise or the results will be not very satisfactory.  The solution to that problem is to "rescale" this 0V --> 0.15V range to 0V --> 5V. We can do that by using operational amplifier circuits.  I used what I found on the moment in my electronic components, an LM358 IC.  This IC is not the best, but for the demo, it's ok to be used.       Fig. 3: USB current and voltage monitor A few ideas of this electronic design:  this IC contains two operational amplifiers,  first amplifier coefficient is set thru R5 and R4 (34 amplification coefficient) and the signal is connected on his noninverting input, the lowest current that can be measured is approx. 0.7mA, the second amplifier is set as a buffer amplifier, note: if the maximum current used by the load is maximum 3A, the Zenner diode it's not necessary. By using this amplifier, the range is rescaled to 0 --> 5.1V.  To measure the voltage at USB input we use R9 and R10 divider resistor and will use the formula U_R9 = U_USB * ( R9/(R9 + R10)). And by using for R9 10K and for R10 33K  the voltage measured by ADC for maximum USB standard charging is U_R9 = 20V * (10/(43)) = 4.65V. This circuit has been developed on prototyping PCB. The outputs of this circuit are connected to two ADC (current signal to PTB13 and voltage signal to PTB14) channels of MPC5744P-DEVKIT and those can be found on CN1 connector ("USB voltage", "USB current" and GND). MPC5744P-DEVKIT Evaluation Board The main scope of this devkit is to get current and voltage data from the custom board and to convert it to digital data and send it to the PC through the UART interface.  As can be seen in fig. 4, I used three wires to connect the custom electronic board to the devkit (two ADC and GND).  On MPC5744P-DEVKIT the ADC voltage reference must be set to 5V (jumper J19 --> 2-3) and the data will be sent to PC through UART (USB --> OpenSDA). The MPC5744P-DEVKIT must be connected to PC thru USB cable. All other jumpers can be let in the default state. Fig. 4: Hardware setup (load is a USB led light) 2.1 Software Setup MBDT Application Model            For software development, I used Matlab with the MBDT toolbox. The first step is to create a new Simulink project using MBDT. The project contains three main parts: configuration blocks variable declaration blocks main loop, where the values are taken from the output of ADC block, and after using some simple maths functions, resulted in values are stored in current and voltage variables. After getting the values from ADC blocks, we must apply some math functions to reverse the effect created in the electronic circuit. Part of the configuration blocks contain: MPC5744P configuration block, ADC configuration block, which has two channels are configured, FreeMASTER block used to observe the current, voltage, and other parameters over UART through the FreeMASTER protocol. Part of the variables declaration is used to declare all variables used to get values from ADC peripheric, intermediate values, and final values.  Part of the main loop consists of simple mathematical functions that have the role to convert ADC values to current and voltage values. The first thing executed is taking the ADC current and voltage values, then those values are converted to floating-point type the multiplied with a constant (ADC_Vref /ADC_resolution = 5/4095) which represent ADC voltage resolution. Then, for USB current value, the result must be divided with operational amplifier factor (34), after that, we could subtract from the result that operational amplifier input offset (if it is measured any relevant value) and the last thing to do to get the USB current is to convert from voltage to current using ohm law (U = R * I).  To get the USB voltage, the first step is similar to the USB current value, using the resistor divider formula we get the final value. For using different opamp IC, if the non-inverting input is too high, it is recommended to be measured while the electric circuit is on and the value to be updated in the model (variable Current_offset).  Fig. 5: MBDT Application Model FreeMASTER project To view data in real-time, the first thing is to open the FreeMASTER project and, select "Tools", then "Connection Wizard ...", then hit "Next" button, select the first option "Use the direct connection to an on-board USB port", then select the serial com port assigned to MPC5744P-DEVKIT and 115200 baud rate. The USB current and voltage can be observed In the FreeMASTER project as a numerical value and as an oscilloscope view by selecting "RAW data" to plot raw ADC USB current and voltage values. To plot the real USB current and voltage values, in the Project Tree, please select "Voltage and current" oscilloscope. Fig. 6: FreeMASTER USB current and voltage monitor In Fig. 6 it can be seen current and voltage variations in time for fast charging transitions when my smartphone is connected to the original charger.
View full article
Here you can find a short&focused presentation with main capabilities for the FreeMASTER tool. It is a very useful tools for real-time data visualization and MCU real-time control. You can create some very interesting Web interfaces for your applications - have a look at this video to find out more. Video Link : 7933 In case you have comments and questions - please leave a reply bellow. 
View full article