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:
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
This page summarizes all Model-Based Design Toolbox tutorials and articles related to HCP Product Family.   S32G2 Hybrid Electrical Vehicle (HEV) demo on S32G2 
View full article
This page summarizes all Model-Based Design Toolbox tutorials and articles related to S32K3xx Product Family.
View full article
    Product Release Announcement Automotive Processing NXP Model-Based Design Toolbox for S32K3xx – version 1.0.0 RTM       The Automotive Processing, Model-Based Design Tools Team at NXP Semiconductors, is pleased to announce the release of the Model-Based Design Toolbox for S32K3xx version 1.0.0. This release supports automatic code generation for S32K3xx peripherals and applications prototyping from MATLAB/Simulink for NXP S32K3xx Automotive Microprocessors. This new product adds support for S32K344 MCU and part of its peripherals, based on RTD MCAL components (ADC, PWM, MCL, DIO, CAN, SPI, GPT). It also adds support for FreeMASTER, AMMCLib, and Simulink simulation modes – Software-in-Loop, Processor-in-Loop, and External mode. Moreover, this release adds the option to configure everything (pins/peripherals/clock) via an external configuration tool - S32 Configuration Tools or EB Tresos. The product comes with over 70 examples, covering everything that is supported, including a motor control application demo. FlexNet Location: https://nxp.flexnetoperations.com/control/frse/download?element=12747097 Technical Support: NXP Model-Based Design Toolbox for S32K3xx issues will be tracked through the NXP Model-Based Design Tools Community space. https://community.nxp.com/community/mbdt   Release Content Automatic C code generation from MATLAB® for NXP S32K3xx derivatives: S32K344 Support for the following peripherals (MCAL components): ADC PWM MCL CAN SPI GPT DIO Support for profiling execution times Support for register R\W and memory R\W operations Provides 2 modes of operation: Basic User Mode – using pre-configured configurations for peripherals; useful for quick hardware evaluation and testing Advanced User Mode – using S32Configuration Tool or EB Tresos to configure peripherals/pins/clocks Integrates the Automotive Math and Motor Control Library release 1.1.24 for: All functions in the Automotive Math and Motor Control Functions Library v1.1.24 are supported as blocks for simulation and embedded target code generation.   FreeMASTER Integration We provide several Simulink example models and associated FreeMASTER projects to demonstrate how our toolbox interacts with the real-time data visualization tool and how it can be used for tuning embedded software applications.   Support for MATLAB versions We added support for the following MATLAB versions: R2020a R2020b R2021a S32Design Studio Integration We added a simple mechanism to provide users the opportunity to export the generated code from Simulink and import it directly into S32Design Studio. This functionality can be useful if the model needs to be integrated into an already existing project, as well as for debugging purposes.   Simulation modes: We provide support for the following simulation modes (each of them being useful for validation and verification): Software-in-Loop (SIL) Processor-in-Loop (PIL) External mode   Examples for every peripheral/function supported: We have added over 70 new examples, including: Motor control application Communication (SPI, CAN) AMMCLib Timer control (GPT) DIO FreeMASTER SIL / PIL / External mode MATLAB® Integration The NXP Model-Based Design Toolbox extends the MATLAB® and Simulink® experience by allowing customers to evaluate and use NXP’s S32K3xx MCUs and evaluation board solutions out-of-the-box with: NXP Model-Based Design Toolbox for S32K3xx version 1.0.0 is fully integrated with MATLAB® environment in terms of installation: Target Audience This release (1.0.0) is intended for technology demonstration, evaluation purposes, and prototyping S32K3xx MCUs and Evaluation Boards.    Useful Resources Examples, Training, and Support: https://community.nxp.com/community/mbdt    
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
      Product Release Announcement Automotive Processing NXP Model-Based Design Toolbox for HCP – version 1.0.0 EAR       The Automotive Processing, Model-Based Design Tools Team at NXP Semiconductors, is pleased to announce the release of the Model-Based Design Toolbox for HCP version 1.0.0. This release supports automatic code generation from MATLAB/Simulink for S32G2xx and S32G2xx Automotive MPUs. This new product adds support for running Processor-in-Loop simulation on S32G274A (ARM Cortex-A53) and S32S247TV (ARM Cortex-R52).   FlexNet Location: https://nxp.flexnetoperations.com/control/frse/product?child_plneID=683951   Technical Support: NXP Model-Based Design Toolbox for HCP issues will be tracked through NXP Model-Based Design Tools Community space. https://community.nxp.com/community/mbdt     Release Content Automatic C code generation from MATLAB® for NXP S32G2xx derivatives: S32G274A Automatic C code generation from MATLAB® for NXP S32S2xx derivatives: S32S247TV Supported Evaluation Boards GoldBox Development Platform (S32G-VNP-RDB2 Reference Design Board) GreenBox II Development Platform Support for MATLAB versions: R2020a R2020b R2021a Simulation mode: We provide support for Processor-in-Loop (PIL) simulation mode with code execution profiling:   Includes the HEV demo:     Includes an Example library that covers: Software-in-Loop, Processor-in-Loop   GUI to help you setup the toolbox and the evaluation board :     For more details, features and how to use the new functionalities, please refer to the Release Notes document attached.   MATLAB® Integration The NXP Model-Based Design Toolbox extends the MATLAB® and Simulink® experience by allowing customers to evaluate and use NXP’s S32G2xx and S32S2xx  processors and evaluation board solutions out-of-the-box with: NXP Model-Based Design Toolbox for HCP version 1.0.0 (EAR) is fully integrated with MATLAB® environment in terms of installation:       Target Audience This release (1.0.0 EAR) is intended for technology demonstration, evaluation purposes and prototyping S32G2xx and S32S2xx and Evaluation Boards.   Useful Resources Examples, Trainings and Support: https://community.nxp.com/community/mbdt  
View full article
This page summarizes all Model-Based Design Toolbox tutorials and articles related to i.MX RT Product Family Facial Recognition Application in Co-Simulation mode for IMXRT117X Sensor application for IMXRT1060
View full article
This page summarizes all Model-Based Design Toolbox videos related to i.MX RT Product Family
View full article
Introduction This article is going to show how to use the IMXRT117X board in co-simulation mode to run a Deep Learning application of facial recognition. Given that a development board has limited resources, the deployment of a Deep Learning application should be done as efficiently as possible. For now, since the latest version of Matlab (2021a) does not offer support for CNN optimization for Arm Cortex-M processors, we will restrict to developing an application in co-simulation mode. That means that while the data will be provided by the target board, the actual processing will take place in a Matlab environment. By running in co-simulation mode, we will exploit both hardware and the Matlab software capabilities.  The goal of this article is for the user to be able to: use a pre-trained CNN model from Matlab; use the MBDT IMXRT Board Object for co-simulation; develop a standard facial recognition application; Hardware overview For the development of this application, the i.MX RT1170 Evaluation board was used with a MIMXRT1176 CPU, and the attached ON Semiconductor OV5640 camera. Additionally, the RK055AHD091 LCD panel can be used to visualize the frames from the camera. The i.MX RT1170 EVK provides a high-performance solution in a highly integrated board. It consists of a 6-layer PCB with through hole design for better EMC performance at a low cost, and it includes key components and interfaces. Some of the i.MX RT1170 EVK main features are: MIPI camera sensor connector and MIPI LCD connector JTAG connector and On-board DAP-Link debugger Connectivity: 2x Micro-USB OTG connectors, Ethernet (10/100/1000M) connector, Ethernet (10/100M) connector, SIM card slot, CAN transceivers 5V Power Supply connector For a more comprehensive view and a more detailed description regarding hardware specifications and user guides, please check the documentation here. For this example, we are going to make use of the following peripherals and components hence make sure you have all of them available and you are familiar with their intended scope: ON Semiconductor OV5640 camera used for capturing the frames from the board; A CAT-5 ethernet cable will be used for getting video frames from the IMXRT on-board camera to be processed in MATLAB; Mini/micro USB cable for downloading the executable on the target; (Optional, if LCD is used) 5V power supply Software overview Software delivered by MathWorks: MATLAB (version 2021a) (we assume you have already installed and configure this). As a hint, please make sure the MATLAB is installed in a path with empty spaces; MATLAB Embedded Coder is the key component that allows us to generate the C code that will be cross-compiled to be executed on the target; Deep Learning Toolbox allows us to use pre-trained networks or re-train and re-purpose them for other scenarios; Image Processing Toolbox for preprocessing the images before training the network; Computer Vision Toolbox for performing face detection using the Viola-Jones algorithm; Software delivered by NXP: NXP MBDT IMXRT Toolbox as IMXRT embedded target support and plug-in for MATLAB environment to allow code generation and deployment. Make sure you install this toolbox in MATLAB 2021a. Deep Learning – Facial recognition Facial recognition is the process of verifying a person’s identity through their facial features in order to grant access to a service, application, or system. Recognition needs to be performed in 2 steps: 1) face detection – so identifying and isolating the face area from an image and 2) face recognition – analyzing the features of the image and classifying them. In this example, face detection is performed with the CascadeObjectDetector, from the Matlab Computer Vision Toolbox, which is based on the Viola-Jones algorithm, and face recognition will be performed with AlexNet, a pre-trained neural network specialized for object classification. source: https://test.neurohive.io/en/popular-networks/alexnet-imagenet-classification-with-deep-convolutional-neural-networks/ 1.Datasets In order to train the network for our application, custom datasets will need to be generated containing the faces of the people we want to recognize. A challenge that arises regarding the dataset are the changes that occur to a person’s appearance: during the day the mood of a person can change, which may affect their facial expressions; also, the lighting of the room can affect the features, by enhancing or diminishing them; nevertheless, the appearance of a person might vary depending on make-up, hairstyle, accessories, facial hair, etc. Thus, this is something that needs to be taken into consideration when creating the dataset used in training. A recommendation for better performance would be to take samples of a person's appearance multiple times during the day and in different lighting conditions. Another challenge is dealing with the category of unknown people since it is impossible to have and use a picture of every unknown person. A possible approach is to use a threshold value for classifying the pictures so that a person is accepted as “known” only over a certain probability.  Another solution would be to create an additional dataset for the “Unknown” category, which should contain various faces of different people. This way the model should be able to generalize and differentiate between known and unknown people. One of the datasets that can be used for this purpose is the Flickr-Faces-HQ Dataset (FFHQ) which contains over 70,000 images with a high variety in terms of ethnicity, age, emotions, and background. For this example, 6 classes were used, 5 of them representing known people and 1 for unknown people. In order to generate a dataset using the attached OV5640 camera, the Matlab client will connect to the Board Object on the target, it will request frames from the camera and it will save them as BMP files. %% Establish communication with the target board board_imxrt = nxpmbdt.boardImxrt('162.168.0.102', 'Video', 'GET'); %% Request frames from the camera and save them as bmp images count = 0; while (1) % Camera snapshot img = board_imxrt.step(); imwrite(img, [num2char(count) '.bmp']) end The next step is to extract the face area from an image and resize it to 227x227x3 so that it can be given as input to AlexNet. For that, we can create a directory with all the images that we want to train/test the network with and run the following script, which will perform face detection, then crop and resize the images to the desired dimensions. All the scripts and code snippets presented are also included in the attached archive. % Create Face Detector Object faceDetector = vision.CascadeObjectDetector; inputFolder = 'datastorage/to_process'; outputFolder = 'datastorage/processed/'; pictures = dir(inputFolder); for j = 3 : length(pictures) imgName = pictures(j).name; img = imread([inputFolder '/' imgName]); % Perform face detection bboxes = step(faceDetector, img); if(sum(sum(bboxes)) ~= 0) detectedFace = imcrop(img, bboxes(1, :)); % Resize image to fit AlexNet requirements detectedFace = imresize(detectedFace, [227 227]); imwrite(detectedFace, [outputFolder imgName]); end end       2.Training the network For training the network, we need to modify the output layer of the AlexNet network to match the number of classes we use, in this example 6. To improve the results for the case where we might not have enough input data, we can augment the images, and for that, we use the imageDataAugmenter from Matlab, where we set the images to be flipped horizontally and/or vertically, and rotated with a random angle between -90 and 90 degrees. This will help the model to avoid overfitting and generalize better. allImages = imageDatastore('datastorage', 'IncludeSubfolders', true,... 'LabelSource','foldernames'); % Split into train and validation sets [imgSetTrain, imgSetTest] = splitEachLabel(allImages, 0.7, 'randomized'); augmenter = imageDataAugmenter('RandXReflection', true,... 'RandYReflection', true,... 'RandRotation', [-90 90]); augimds_train = augmentedImageDatastore([227 227], imgSetTrain,... 'DataAugmentation', augmenter); augimds_test = augmentedImageDatastore([227 227], imgSetTest,... 'DataAugmentation', augmenter); Set the training options, these can be configured by the user as they wish, for this example, we have used a learning rate of 0.001 and batch size of 64, and have run the model for 7 epochs. opts = trainingOptions('sgdm', 'InitialLearnRate', 0.001,... 'Shuffle', 'every-epoch', ... 'MaxEpochs', 7, 'MiniBatchSize', 64,... 'ValidationData', augimds_test, ... 'Plots', 'training-progress'); trained = trainNetwork(augimds_train, layers, opts); save('trained_50_50_ep7_6classes', 'trained'); Save the trained network into a .mat file. It will be used for classifying the frames received from the camera. 3.Setup For the installation and usage of the MBDT IMXRT Toolbox please refer to this article. Running in co-simulation mode means that the target board is able to communicate with the host (in this case, Matlab) through the TCP/IP protocol, thus exploiting both hardware and Matlab software capabilities. The logic of the application is presented in the following figure: the attached camera will send the captured frames to the computer through an Ethernet connection; there, the frame will be processed using a Matlab script, which will perform Face detection and be further sent to the AlexNet trained classifier, which will return a label and the probability of that label being correct. Then, based on whether the person was recognized or not, a signal will be sent to the IMXRT board to toggle the USER LED. In order to create the executable that will act as the server part of our application, we will create a new Simulink model containing the IMXRT Board Object. For this example, the Board Object is sufficient for creating the co-simulation environment and running the application, for it makes use of both Camera and LWIP functionalities: The next step would be to configure the Board Object in order to be able to communicate with the host: open the Block Parameters window and input the IP address and port number you want to use. In the case of the server, it does not matter whether it is configured in SEND or GET mode, because it will wait for commands from the client. Then the model’s Ethernet parameters need to be configured. Open the Configuration Parameters window from Simulink, select Hardware Implementation from the left menu and then go to the Ethernet tab: here insert the values of the board IP address, subnet mask, and the gateway address.   Connect the board through USB to the computer. Go to the Download tab and select the drive you want to download the executable to. More information about this process is presented here. Also, please make sure that you have selected the NXP MIMXRT117Xxxxxx Hardware Board. The selection of the MIMXRT117X Hardware Board should copy the default ConfigTool MEX file which you can modify, but you can also create or use another MEX file as long as it has the name <model_name>_<core>Config.mex. In the MEX file are configured the peripherals and pins settings, in this case the Camera peripheral and the GPIO User LED. For better performance, we recommend using a low-resolution for the Camera. Build the model and the generated executable will be copied on the target board. Restart the board. Next step is to connect to the target board from Matlab and start receiving frames from the attached camera. For this, we will use a Matlab script that will create a board object configured to request frames from the target. The nxpmbdt.boardImxrt object is the same type as the one used in the previous Simulink model: here we can use it as a function call in a script, so we need to configure it accordingly. For information about how to use the Board Object, use the following command:  The Matlab script that will run in co-simulation and will connect to the target board: load trained_50_50_ep7_6classes.mat trained; faceDetector = vision.CascadeObjectDetector; board_imxrt = nxpmbdt.boardImxrt('162.168.0.102', ... 'Video', 'GET'); while (1) img = board_imxrt.step(); bboxes = step(faceDetector,uint8(img)); if (sum(sum(bboxes)) ~= 0) es = imcrop(img, bboxes(1,:)); es = imresize(es, [227 227]); [label, ~] = classify(trained, es); if ~strcmp(char(label), 'Unknown') board_imxrt.led_on(); else board_imxrt.led_off(); end else board_imxrt.led_off(); end end When running simulation mode from a Matlab script, please make sure that the configuration structure (the script mscripts\target\imxrt_code_gen_config) is configured accordingly with the desired hardware. After the application has received the camera frame from the board, it can start the preprocessing required for classification. We create a face detector object using the CascadeObjectDetector, to which we will input the camera frame and we receive in exchange the margins of the box where it detected a face. In the case a face was detected, we crop the image and resize it to 227x227x3, which is the size the AlexNet network requires, and we classify the image using the loaded model. The USER LED on the board will be switched on if the person was identified. The script also provides a Matlab UI Figure for better visualization.   Conclusions The NXP MBDT Toolbox provides a solution for developing Computer Vision applications targeted for Arm Cortex-M processors. This aims to be a temporary approach until the Matlab support required for generating CNN optimized C code is added.
View full article
1.  Introduction The NXP i.MX RT1xxx Toolbox enables automatic code generation for peripherals and applications prototyping from MATLAB/Simulink for NXP’s i.MX RT 117x, 106x & 101x Series of crossover MCUs. The toolbox can be installed from Matlab add-ons page:   The novelty of this NXP toolbox is the integration with MCUX Configuration Tool for platform initialization. This configuration tool is being leveraged for pins settings, clock configuration and peripheral initialization. The toolbox is also integrated with the MCU SDK and will use the SDK API for code generation. This article details the steps to start building new models and deploy them on the i.MX RT106x, i.MX RT1010 & i.MX RT 117x MCU, showcasing also the integration with the MCUX Configuration Tool. 2.  Start creating your model Below are the steps to start creating a Simulink model that will be deployed on the i.MX RT1xxx boards. Step 1: Better to start on clean so first lets create folder to be used as workspace and switch MATLAB current folder to point to this workspace location:   Step 2: Create a Simulink Blank Model.   Step 3: Save and name your new model (E.g. mytest.slx). Step 4 : Choose the NXP IMXRT hardware board from the Model Settings in the MODELING tab.         Step 4.1: Open  Model Settings -> Hardware Implementation menu         Step 4.2: Select the NXP target from Hardware Board. This selection should match the             evaluation kit you plan to test the code for. After the selection is made, press the Apply button. After the target is set, the workspace will be populated with new files and folders: A file with extension <model_name>Config.mex – this is the file created with MCUX Configuration Tool that is used for pins, clock, and peripherals initialization. This configuration file will have enabled the peripherals that are supported by the toolbox. Starting from this, the user can change the default configuration for any of the peripheral instances (add new instances, disable instances, etc.) and also any of the configured pins.   A folder with naming pattern <model_name>Config -  this folder will have a structure that is similar to the MCUXpresso IDE projects, and will contain the SDK files that are needed to build the model and generate a binary application that will run on the board. The user can now add Simulink blocks in the model from the NXP i.MXRT1xxx Simulink library from Simulink Library Browser:   Choose the desired block to add to the model:   Alternatively, if the user will add in his/her model a peripheral block without configuring the target, a default one will be set that the user can change it afterwards.  3.  Modify default platform initializations and settings values As mentioned at the beginning of this article, the platform initialization, including pins, clock and peripherals settings is done using the MCUX Configuration Tool. As seen in the previous chapter, when a Simulink model is being created with one of the NXP IMXRT targets, the workspace will be populated with a file having the extension .mex – this is the configuration file that will be used in the initialization code of the platform. The user has the option to modify the default selections found in the .mex file. For this, open any peripheral block within the model and press the Configure button. This action will open the MCUX Configuration Tool.   From MCUX Configuration Tool, the user can change default settings of the peripherals – enable or disable instances, from Pins view, it can configure/update pins settings of the platform. After the user is done with configuration in MCUX Configuration Tool, he/she must go back in Simulink and press the Update button in the same block, for the changes to be visible in Simulink also. The new initialization settings, will be included in the Build Model step. The Toolbox will trigger a code generation starting from the .mex file. The generated files will be saved in the <model_name>Config folder, in board folder.   Note, that is not a prerequisite for the user to have MCUX Configuration Tool installed, the toolbox incorporates all the tools that are need for the user to create, configure,  build and deploy the model.  The default MCUX Configuration Tool used can be changed from Model Settings/Hardware Parameters / Tools Path, and the user can provide his/her own installation of the tool. Same approach is used with the SDK platform. The toolbox incorporates the release version of the SDK for the IMXRT1xxx targets. Also this path can be changed by the user, but it must consider possible integration issues of the toolbox with the user specified SDK.     4.  Deploy on NXP Hardware After the Simulink model is completed, follows the build and deployment of the model on the target board. Before Build and Deploy, the user must set the download method of the application. Step 1: Select the Download method from Hardware Implementation in Model Settings.   The default Download method (without the need for additional software and/or hardware probes) is OpenSDA. For this, the user must select the Drive on his/her machine where the OpenSDA firmware of the board is mapped after the NXP evaluation board is plugged in via USB. Step 2: Build & Deploy Model Step 3: After the code is generated and downloaded on the board a window will pop up and tell you to restart the evaluation board. Restart the board and then press OK. Congratulations! You have successfully created and deployed your Simulink model to the hardware.
View full article
Speed up development time with NXP Model-Based Design Toolboxes
View full article
Product Release Announcement EDGE PROCESSING  NXP Model-Based Design Toolbox for i.MX RT Crossover MCUs – version 1.2.0     The Edge Processing Tools Team at NXP Semiconductors is pleased to announce the release of the Model-Based Design Toolbox for i.MX RT 1xxx Series version 1.2.0. This release supports automatic code generation for peripherals and applications prototyping from MATLAB/Simulink for NXP’s i.MX RT 117x, 106x & 101x Series of crossover MCUs.   NXP Download Location https://www.nxp.com/webapp/swlicensing/sso/downloadSoftware.sp?catid=MCTB-EX   MATHWORKS Download Location https://www.mathworks.com/matlabcentral/fileexchange/81051-nxp-support-package-imxrt1xxx   Version 1.2.0 Release Content Automatic C code generation based on MCUXpresso SDK 2.9.1/2.9.2 drivers and MCUXpresso Configuration Tools 9.0 initializations from MATLAB®/Simulink® for: i.MX RT 1176: MIMXRT1176DVMAA,MIMXRT1176AVM8A,MIMXRT1176CVM8A i.MX RT 1175: MIMXRT1175DVMAA,MIMXRT1175AVM8A,MIMXRT1175CVM8A i.MX RT 1173: MIMXRT1173CVM8A i.MX RT 1172: MIMXRT1172DVMAA,MIMXRT1172AVM8A,MIMXRT1172CVM8A i.MX RT 1171: MIMXRT1171DVMAA,MIMXRT1171AVM8A,MIMXRT1171CVM8A i.MX RT 1061: MIMXRT1061CVJ5A,MIMXRT1061CVL5A,MIMXRT1061DVJ6A,MIMXRT1061DVL6A i.MX RT 1062: MIMXRT1062CVJ5A,MIMXRT1062CVL5A,MIMXRT1062DVJ6A,MIMXRT1062DVL6A i.MX RT 1064: MIMXRT1064CVJ5A,MIMXRT1064CVL5A,MIMXRT1064DVJ6A,MIMXRT1064DVL6A i.MX RT 1011: MIMXRT1011CAE4A,MIMXRT1011DAE5A   Multiple options for configuration of MCU packages, Build Toolchain and embedded Target Connections are available via Simulink Model Configuration UI       Multiple MCU peripherals and Drivers supported. The following subsystems highlighted in red as supported in Simulink environments in various forms: blocks, files, options i.MX RT 117x derivatives   i.MX RT 106x derivatives i.MX RT 101x derivatives     Basic and Advanced Simulink Block configuration modes via MCUXpresso Configuration Tools 9.0 UIs for Pins, Clocks, and Peripherals       MATLAB/Simulink versions 2019a – 2021b are supported for Design, Simulation, Code Generation, and Deployment of applications on i.MX RT 117x,106x & 101x Series. Other i.MX RT devices will be supported in future versions of the toolbox. Support for Software-in-Loop (SiL), Processor-in-Loop (PiL), and External Mode; RTCESL – Real-Time Control Embedded Software Motor Control and Power Conversion Libraries (limited support designed for Motor Control applications). A future update will enhance the number of functionalities supported by Simulink.     Simulink Example library with more than 190 models to showcase various functionalities:   Integrated PMSM Motor Control Sensor/Sensor-less application for both IMXRT1060-EVK and IMXRT1170-EVK:     Target Applications with MATLAB/Simulink This release of the Model-Based Design Toolbox can be used to design, build, and test applications from multiple domains: INDUSTRIAL AC Meters Motion Control Robotics HMI SMART CITY/HOME Video Surveillance Identification Appliances Speakers   AUTOMOTIVE HVAC ECU     Target Audience This release is intended for technology demonstration, evaluation purposes, and prototyping for i.MX RT 1xxx MCUs and their corresponding Evaluation Boards: EVK-MIMXRT1170 EVK-MIMXRT1060 EVK-MIMXRT1064 EVK-MIMXRT1010   Useful Resources Examples, Training, and Support: https://community.nxp.com/community/mbdt Technical by System Tools: https://web.microsoftstream.com/channel/618ab630-c8da-4fa8-ade8-5aa70a353124    
View full article
This article details the SPI communication setup between S32K1xx boards and MC3377xBSPI Battery Cell Controllers. It covers both hardware and software setup for the Battery Management System models designed using Model-Based Design Toolbox for battery packs up to 14 cells in series.  At the end of this article, the user will be able to setup the Battery Cell Controller hardware and to design a Simulink model that reads the cell and pack voltages, current, temperatures and faults status. The measured values will be displayed on the host PC using FreeMaster. 
View full article
Model-Based Design Toolbox supporting i.MX RT Crossover MCU. System modeling, simulations, automatic code generation, validation, and verification MATLAB & Simulink workflows are now available on the i.MX RT microcontroller by reusing MCUXpresso ecosystem: MCUXpresso SDK MCUXpresso Configuration Tool MCUXpresso IDE,GCC
View full article
Model-Based Design Toolbox supporting Kinetis-V Series. System modeling, simulations, automatic code generation, validation, and verification MATLAB & Simulink workflows are now available on the Kinetis V microcontrollers by reusing MCUXpresso ecosystem: MCUXpresso SDK MCUXpresso Configuration Tool MCUXpresso IDE,GCC
View full article
Four-Part How-To Series Model-Based Design Toolbox (MBDT) is an integrated development environment and toolchain for configuring and generating all the necessary software automatically to execute complex applications. The MBDT includes integrated Simulink® embedded target for NXP processors, peripheral device blocks and drivers, the Math and Motor Control library set, and bit-accurate simulation results. Watch on-demand each of our Model-Based Design Toolbox four-part How-To series and learn the basics of MBDT, also its SPI and CAN communication and its PWM control blocks.   Session 1/4 = Get to Know the User-Friendly NXP MBDT for Application Development in MATLAB/Simulink dumitru-daniel.popa‌ will show you how to configure and use the MBDT, engineered to help you speed up application development in MATLAB/Simulink Environment for NXP hardware. Get to know its main features and capabilities through the creation, simulation, built, deployment, and validation of a basic "hello world" type of application on theS32K144EVB.  Session 2/4 = Introducing the SPI Communication Blocks from NXP MBDT nxf46081‌ will highlight the key aspects of communication in the automotive industry while showing you how to configure and use designated blocks that implement the SPI communication inside the MATLAB/Simulink Environment for creating a quick and easy data transfer application using MBDT and the S32K144EVB. Session 3/4 = Introducing the CAN Communication Blocks from NXP MBDT constantinrazvan.chivu‌ will highlight the key aspects of communication in the automotive industry while showing you how to use MBDT and the S32K144EVB to simplify CAN applications with only a few blocks: configuration, transmit, and receive. Session 4/4 = Introducing the PWM Control Blocks from NXP MBDT mariuslucianandrei‌ will showcase how to start using PWM, its features and functionalities while showing you how to build a first application able to generate different types of PWM signals using MBDT and the S32K144EVB; also, learn to sample the external signals to determine the key values: duty-cycle, period, among others.   Your software development processes can speed up by using the free-of-charge NXP Model-Based Design Toolboxes for MATLAB and Simulink development environments, providing full integration, an out-of-the-box configuration, and action blocks for basic/advanced features for designing complex automotive solutions.
View full article
      Product Release Announcement Automotive Processing   NXP Model-Based Design Toolbox   for S12ZVMx – version 1.4.0     Austin, Texas, USA September 9, 2020 The Automotive Processing, Model-Based Design Tools Team at NXP Semiconductors, is pleased to announce the release of the Model-Based Design Toolbox for S12ZVMx version 1.4.0. This release supports automatic code generation for S12ZVM peripherals and applications prototyping from MATLAB/Simulink for NXP S12ZVMx Automotive Microprocessors. This new release adds extended MATLAB version support (R2015a-R2020a), integrates with AMMCLib v1.1.21, is compatible with MathWorks Automotive Advisory Board checks, adds over 50 new examples and more.   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   Technical Support: NXP Model-Based Design Toolbox for S12ZVMx issues are tracked through NXP Model-Based Design Tools Community space. https://community.nxp.com/community/mbdt   Release Content Automatic C code generation from MATLAB® for NXP S12ZVMx derivatives: S12ZVM 32/L31/16: MC9S12ZVM16 MC9S12ZVML31 MC9S12ZVM32 S12ZVML/C 128/64/32: MC9S12ZVML32 MC9S12ZVML64 MC9S12ZVMC64 MC9S12ZVML128 MC9S12ZVMC128 S12ZVMC256: MC9S12ZVMC256   Integrates the Automotive Math and Motor Control Library release 1.1.21: All functions in the Automotive Math and Motor Control Functions Library v1.1.21 are supported as blocks for simulation and embedded target code generation for: Bit Accurate Model for 16-bit fixed-point implementation Bit Accurate Model for 32-bit fixed-point implementation Bit Accurate Model for floating-point single precision implementation             Extended support for MATLAB versions We extended support for our toolbox to cover a wider range of MATLAB releases – starting from R2015a and going up to R2020a. This way we want to avoid locking out users that have constraints regarding MATLAB versions. Motor control examples We have added new motor control examples – BLDC (closed loop) and PMSM (closed loop, sensorless):   MAAB Checks (MathWorks Automotive Advisory Board) The toolbox is compatible with MathWorks Automotive Advisory Board checks – reports can be generated from Model Advisor:   Updated examples: We have added over 50 new examples, including: Motor control (both BLDC and PMSM) AMMCLib GDU (Gate Drive Unit) Profiler 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 S12ZVMx MCUs and evaluation boards solutions out-of-the-box with: NXP Support Package for S12ZVMx  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 S12ZVM version 1.4.0 is fully integrated with MATLAB® environment in terms of installation: Target Audience This release (1.4.0) is intended for technology demonstration, evaluation purposes and prototyping S12ZVMx MCUs and Evaluation Boards.   Useful Resources Examples, Trainings and Support: https://community.nxp.com/community/mbdt                                                    
View full article
In the following articles, we are going to detail the capabilities of our BMS blocks and how to use them on the NXP battery cell controller DevKits.
View full article
This article details the TPL communication setup between S32K1xx boards and MC3377xBTPL Battery Cell Controllers.  It covers both hardware and software setup for the Battery Management System models designed using Model-Based Design Toolbox for battery packs of more than 14 cells in series.  At the end of this article, the user will be able to setup the Battery Cell Controller hardware and to design a Simulink model that reads the cell and pack voltages, current, temperatures and faults status. The measured values will be displayed on the host PC using FreeMaster. 
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