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

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

NXP Model-Based Design Tools Knowledge Base

ディスカッション

ソート順:
General Tip of the day Tip of the day  Licensing MBDT license missing error  Toolbox functionality Registers, Linkers not displaying options  Profiler/Execution S32k144 Simulation Time and Profiler  Peripherals How to put MCU into sleep? Apps Motor Control
記事全体を表示
General Installer and Setup  How to install the license of MBDT for S32K3?  How to setup the S32K344 toolbox and EVB?  How to export the generated code to S32DS3.4? Export generated projects in MBDT for s32k3XX  Programming methods MBDT for S32k3 using P&E Multilink Custom code usage SENT Protocol Support in S32K3 MBDT Custom project usage How to use custom project configuration Sequential reset S32K344-Q172 sequential reset SIL / PIL / External Mode External mode External mode example wouldn't compile after update  S32K3X4EVB-Q257 with MBDT PIL Example: Not able to run Simple PIL S32CT example Peripherals ADC How to add a new ADC channel using the external configuration tool  SPI How to send 32 bit frames  DIO S32K3x4-Q172P_with_MBDT_Blink_Project DIO and PWM configuration issues ICU PWM Duty cycle measurement PWM PWM raising edge and falling edge detection Interrupt based PWM generation CAN FreeMASTER over CAN connection issue  Apps Motor Control SPI configuration MODEL based design tool box- 32 bit instruction (SIMULINK) 
記事全体を表示
This page summarizes all Model-Based Design Toolbox topics related to the S32K3xx Product Family. Model-Based Design Toolbox for S32K3xx - Release Notes: Rev 1.2.0 - Model-Based Design Toolbox for S32K3xx Automotive MCU rev 1.2.0   Rev 1.1.0 - Model-Based Design Toolbox for S32K3xx Automotive MCU rev 1.1.0  Rev 1.0.0 - Model-Based Design Toolbox for S32K3xx Automotive MCU rev 1.0.0 
記事全体を表示
This page summarizes all Model-Based Design Toolbox videos related to i.MX RT Product Family
記事全体を表示
Having fun with MBDT for MPC57xx 3.1.0 and MPC5744P for Xmas tree by controlling the lights and sounds
記事全体を表示
This video shows how to program the GPIO with Model Based Design Toolbox to obtain the speed reference for the BLDC speed closed loop control system.   We discuss about: - How to implement a simple program to read data from the GPIO - How to test in real time with FreeMaster - How to transform GPI pulses into a speed reference data that represents the rpm. - How to implement from scratch a Simulink model to cover the GPIO functionality NOTE: Chinese viewers can watch the video on YOUKU using this link. 注意:中国观众可以使用此链接观看YOUKU上的视频
記事全体を表示
  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
記事全体を表示
    Product Release Announcement Automotive Processing NXP Model-Based Design Toolbox for HCP – version 1.3.0 RFP   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.3.0. This release supports automatic code generation from MATLAB/Simulink for S32G2xx, S32R41x, and S32S2xx MCUs. This new product adds support S32R41 Cut 1.1 and S32G3, C++ code generation for S32G2 and S32G3,  Radar examples for S32R41, and support for MATLAB versions R2021a - R2023b for running in Software-in-the-Loop and Processor-in-the-Loop modes.   FlexNet Location: https://nxp.flexnetoperations.com/control/frse/download?element=3742498   Technical Support: NXP Model-Based Design Toolbox for HCP 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 S32G2xx derivatives: S32G274A Automatic C code generation from MATLAB® for NXP S32G3xx derivatives: S32G399A Automatic C code generation from MATLAB® for NXP S32R4x derivatives: S32R41 (including Cut 1.1) Automatic C code generation from MATLAB® for NXP S32S2xx derivatives: S32S247TV Supported Evaluation Boards GoldBox 2 Development Platform (S32G-VNP-RDB2 Reference Design Board) GoldBox 3 Development Platform (S32G-VNP-RDB3 Reference Design Board) X-S32R41-EVB Development Board GreenBox 2 Development Platform Support for MATLAB® versions: R2021a R2021b R2022a R2022b R2023a R2023b S32G2 and S32G3 support: SIL and PIL simulation modes with code execution profiling. C++ code generation. S32R41 support: SIL and PIL simulation modes. Code execution profiling using PMU cycle counter. Tools updates: S32 Flash Tool v2.1.4, S32 Debugger v3.5 Includes an Example library with 20+ examples that cover: Software-in-Loop (SIL), Processor-in-Loop (PIL) MathWorks Automotive Adaptive Cruise Control Using FMCW and MFSK Technology examples ported to S32R41: MSFK Radar Range and Speed Estimation of Multiple Targets FMCW Radar Multiple Targets Range and Speed Estimation       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, S32G3xx, S32S2xx, and S32R41 MCUs and evaluation board solutions out-of-the-box with: Model-Based Design Toolbox for S32M2xx version 1.3.0 is fully integrated with MATLAB® environment in terms of installation:     Target Audience This release (1.3.0 RFP) is intended for technology demonstration, evaluation purposes and prototyping of S32G2xx, S32G3xx, S32R41, and S32S2xx MCUs and Evaluation Boards..   Useful Resources Examples, Training, and Support: https://community.nxp.com/community/mbdt      
記事全体を表示
This page summarizes all Model-Based Design Toolbox videos related to BMS. Speed-Up BMS Application Development with NXP's High-Voltage Battery Management System Reference Design and Model-Based Design Toolbox (MBDT) Link to the recording here  This webinar shows how to design and develop Battery Management Systems, with NXP's High-Voltage BMS Reference Design and Model-Based Design Toolbox for S32K3xx, with Simulink® and Embedded Coder. During this webinar, we will introduce the ASIL D High Voltage Battery Management System Reference Resign that comprises a Battery Management Unit (BMU), Cell Monitoring Units (CMU), and a Battery Junction Box (BJB). NXP's HV-BMS Reference Design is a robust and scalable solution including hardware designs, production-ready software drivers, and safety libraries, as well as extensive ISO 26262 Functional Safety documentation. The design significantly reduces the development effort and enables an improved time to market with the latest chipset innovations. Speed Up Electrification Solutions Using NXP Tools Link to the recording here  This video provides an overview of the NXP Software and Tools solutions, designed to help customers to speed up application development with design, simulation, implementation, deployment, testing, and validation. During this session, you will learn about all the steps required to build complete solutions like battery management systems with NXP in-house solutions and NXP Model-Based Design Toolbox with simulation and code generation.
記事全体を表示
This page summarizes all Model-Based Design Toolbox tutorials and articles related to BMS on S32K3xx & S32K1xx Product Family   MBDT for BMS & MBDT for S32K3xx:   MBDT for S32K1xx: How to use RDDRONE-BMS772 with MBDT   
記事全体を表示
This page summarizes all Model-Based Design Toolbox topics related to the BMS Product Family. Model-Based Design Toolbox for BMS- Release Notes: Rev 1.1.0 - Model-Based Design Toolbox for BMS rev 1.1.0  Rev 1.0.0 - Model-Based Design Toolbox for BMS rev 1.0.0 
記事全体を表示
1. INTRODUCTION    This article presents how to use NXP’s Model-Based Design Toolbox (MBDT) to implement an Air Quality Monitor that integrates multiple sensors, which will be configured to run on the 3S32K144 EVB.    The Model-Based Design Toolbox offers a solution for deploying complex applications on NXP hardware directly from Simulink. It incorporates hardware-optimized software, including drivers, libraries, and tools, allowing users to concentrate solely on algorithm development. The toolbox manages the hardware integration, ensuring the applications are hardware-aware. By integrating with the MathWorks ecosystem, the Model-Based Design Toolbox leverages the model-based design paradigm. This enables a programming process based on models, where users create logical diagrams using Simulink blocks for dedicated functions, eliminating the need to write C code for their designs.     This article aims to show how this tool can be used for designing and deploying on an S32K144 Evaluation board an air quality monitor application. Therefore, the steps meant to accomplish this are parted in the following sections:       II. General purpose – what is the aim of the application;       III. Application overview – how the application works and how the sensors are integrated;      IV. Hardware design – the description of the components used;       V. Software design – the execution flow of the application and the model implementation explained in detail;      VI. Conclusion – results of the application.    2. GENERAL PURPOSE    This application shows how easily an Air Quality Monitor can be implemented when using the MBD toolbox for S32K1xx, which helps the users simplify their job by providing the means to use a graphic and visual way to put their idea into use and generate the C code from it, which will be uploaded on the EVB.    3. APPLICATION OVERVIEW     The application displays in FreeMASTER the values of temperature, humidity, dust density, pressure, and the values of eCO2 and TVOC. Those values are read from the sensors connected to the EVB and computed using the algorithms from the libraries corresponding to each sensor, such as Adafruit’s libraries for BMP280 and CCS811, Sparkfun library for HTU21D and the GP2Y1010AU0F library, which are then adapted in Simulink logic. The application will be split into four subsystems, each covering a sensor and its algorithm.    BLOCK DIAGRAM                                                        Figure 1: Block Diagram     4. HARDWARE DESIGN     4.1. Hardware components   The required components for this application are:  S32K144 Evaluation Board  HTU21D, temperature and humidity sensor CCS811, eCO2 and TVOC sensor  BMP280, pressure sensor  GP2Y1010AU0F, dust density sensor        1) S32K144 Evaluation Board  The S32K144EVB is a low-cost evaluation and development board for general-purpose industrial and automotive applications. The board represents the main part of the application as it collects the data from the sensors and applies the algorithm to compute the values shown in FreeMASTER.  For more information about the board, access the following NXP page.      2) Temperature and humidity sensor HTU21D  The HTU21D is an easy-to-use, digital sensor for measuring humidity and temperature levels. It utilizes the I2C communication protocol, making it suitable for various applications, such as an Air Quality Monitor.     3) eCO2 and TVOC sensor CCS811  The CCS811 sensor precisely monitors indoor air quality, measuring TVOCs and carbon dioxide levels in real time. Using the I2C communication protocol, it is easily integrated into air quality monitor applications.     4) Pressure sensor BMP280  The BMP280 sensor accurately measures atmospheric pressure using the I2C communication protocol.     5) Dust density sensor GP2Y1010AU0F  The GP2Y1010AU0F sensor is utilized for the measurement of dust density with high precision. Utilizing an analog output mechanism, it delivers reliable data for comprehensive air quality assessments.    4.2. Electrical schematic    Apart from the components described above (HTU21D sensor, CCS811 sensor, BMP280 sensor and GP2Y1010AU0F sensor), a resistor and a capacitor will be needed.   The following electrical schematic is an example of how the sensors can be connected:                                                             Figure 2: Electrical schematic    5. SOFTWARE DESIGN    5.1. Prerequisite software  To be able to follow the next steps presented in this article, the following software will be necessary:  Matlab® and Simulink® (2021a or newer), including Stateflow ®, MATLAB® CoderTM, Simulink® CoderTM, Embedded Coder®  NXP Support Package S32K1xx    5.2. Model overview   The application uses the Simulink environment to implement the algorithms for computing the data read from the sensors connected to the S32K144 EVB. The model is organized into two big sections: initialization and sensors’ algorithms. For the sensors part, each sensor has its subsystem where the algorithm is implemented.                                                     Figure 3: Application’s model    5.3. INITIALIZATION  The initialization holds the blocks required for our model to work. On the first line, from left to right, the following can be found:        1) The Configuration block for S32K1xx processor family. The required settings of the processor configuration block are the default ones, except for the processor family and the download interface.                           Figure 4: Configuration block for S32K1xx family of processors        2) The LP2IC Configuration block. Here the functioning mode (master or slave) can be changed, and the pins used for communication can be chosen. This application has three sensors that use this communication protocol:  BMP280, whose address is 0x76  CCS811, whose address is 0x5A HTU21D, whose address is 0x40                                            Figure 5: Configuration block for LPI2C        3) The FreeMASTER configuration block. Here the communication interface, the baud rate, and long interrupt serial communication can be set. This component facilitates communication between the S32K144 EVB LPUART1 instance and the FreeMaster tool, via the microUSB serial port.                                Figure 6: Configuration block for FreeMASTER        4) The configuration block for ADC. The ADC converter number and the resolution mode can be selected from here.     Figure 7: Configuration block for ADC    On the second line, the data stores for the variables used in this project can be found. The data type and size for the data stores can be found in the following table:     VARIABLE NAMES  DATA TYPE  SIZE / DIMENSION  SENSOR  aux_temp  uint8  3  BMP280  aux_press  uint8  3  BMP280  BMP280_Temp  uint8  6  BMP280  BMP280_Press  uint8  18  BMP280  BMP280_T  uint16  1  BMP280  BMP280_T2  int16  2  BMP280  BMP280_P  uint16  1  BMP280  BMP280_P2  int16  8  BMP280  raw_press  int32  1  BMP280  raw_temp  int32  1  BMP280  Pressure  double  1  BMP280  buf  uint8  8  CCS811  TVOC  uint16  1  CCS811  eCO2  uint16  1  CCS811  temperature  double  1  HTU21D  humidity  double  1  HTU21D  hum_raw  uint16  1  HTU21D  temp_raw  uint16  1  HTU21D  humcomp  default  default  HTU21D  dustDensity  default  default  GP2Y1010AU0F    Figure 8: Variables    Note! It is important, for the variables to be visible in FreeMASTER, to go to Apps -> Embedded Coder -> Code Interface -> Default Code Mappings -> Data Stores and set all the variables to Volatile.    Figure 9: Embedded Coder selection    Figure 10: Default Code Mappings    5.4. ALGORITHM   The second part of the model consists of every sensor’s subsystem. In each subsystem, the necessary algorithm for computing the data is implemented.   Let’s look at every subsystem and algorithm.       5.4.1. BMP 280 Pressure sensor   For this sensor’s initialization, BMP280_Temp and BMP280_Press will  be used. Top down, five subsystems can be found: Global Initialization Sensor, Temp Calib, read16LE – temp, Press Calib, read16LE – press.     Figure 11: BMP280 subsystems    The purpose of the Global Initialization Sensor is to prepare the sensor for subsequent data reading. This involves transmitting specific data to the sensor using the LPI2C Master Transmit block. These data include values such as 0xF5 and 108, as well as 0xF4 and 111, which serve to configure and calibrate the sensor for upcoming tasks. Having multiple sensors connected using I2C communication protocol, the way the sensor can differentiate between them is by their address. Therefore, the data will be sent to the 0x76 address, which corresponds to the address of the pressure sensor.  Figure 12: Pressure sensor initialization    In Temp Calib subsystem, data is read from the temperature's memory location and placed into the BMP280_Temp data store mentioned earlier. The addresses from which data needs to be read are sequential, so reading begins from the 0x88 address and 6 bits of data are requested, resulting in reading from address 0x88 to address 0x8C inclusively.  Figure 13: I2C Master Multi Transfer    In read16LE – temp subsystem, the add operation is utilized to perform an OR bit operation for calibrating the data and placing it into the BMP280_T data store and the BMP280_T2. LE stands for Little Endian.    Figure 14: Temperature data calibration    For the Press Calib and read16LE – press subsystems, the same operations described previously are performed, but for a greater number of bits. After the initialization is completed, the Else subsystem is entered, where the computing takes place. An auxiliary temperature is computed, which is required for the pressure's formula. For this purpose, the data store named aux_temp will be used. Within this subsystem, there are 2 further subsystems: READ TEMP REGISTER and RAW TEMP.  In READ TEMP REGISTER, data is read from the 0xFA address using an LPI2C Master Multi Transfer, and 3 bits of data are transferred into the aforementioned aux_temp data store.  In RAW TEMP, the raw_temp necessary for the pressure calculation formula is computed.  Similar to the temperature calculation, the pressure calculation data is read from the 0xF7 address into the data store named aux_press, and then the raw_press required for the formula is computed.  For the actual computation of the pressure, an S-Function block with C code inside is utilized, where the algorithm found in the Adafruit Library for BMP280 is included. [1] [functions float Adafruit_BMP280::readTemperature() and float Adafruit_BMP280::readPressure()].  Figure 15: convertPressure S-Function       5.4.2. CCS811 TVOC & eCO2 sensor  For this sensor, during initialization, the same procedure as before is followed: specific data is sent to the sensor using the LPI2C Master Transmit to notify it of the upcoming data reading. Specifically, the predefined data 0xF4 and 0x01, 16 is now transmitted.   Figure 16: Initialization for eCO2 and TVOC sensor    In the Else subsystem, 8 bits of data are read and placed into the buf variable using the LPI2C Master Multi Transfer block. Subsequently, after the necessary data is retrieved from the sensor, the required values are computed, with their formulas sourced from the Adafruit Library for the CCS811 sensor [2]:  _eCO2 = ((uint16_t)buf[0] << 😎 | ((uint16_t)buf[1]);  _TVOC = ((uint16_t)buf[2] << 😎 | ((uint16_t)buf[3]);    Figure 17: Compute data for eCO2 and TVOC values       5.4.3. Humidity & Temperature subsystem  For this sensor, another library [3] will be utilized to obtain the necessary formulas and the algorithm. Initially, for both temperature and humidity readings, the LPI2C Master Multi Transfer block will be employed to retrieve the required values. Specifically, the command to trigger temperature readings is 227, and for humidity, it is 229. Each reading will consist of 3 bits, from which only the most significant bit and the least significant bit will be utilized for temperature and humidity, respectively.  For both of them, the raw values need to be computed. The formulas needed are:  For temperature:  uint16_t rawValue = ((uint16_t) msb << 😎 | (uint16_t) lsb;  temp_raw = rawValue & 0xFFFC;       2. For humidity:  uint16_t rawValue = ((uint16_t) msb << 😎 | (uint16_t) lsb;  hum_raw = rawValue & 0xFFFC;    The temperature is computed using the following formula:  Temperature = temp_raw * (175.72 / 65536.0) – 46.85;    Figure 18: Temperature computing    The humidity is computed using the following formula:  Humidity = (-6) + 125 * (hum_raw / 65536.0) + (25 – Temperature) * (-0.15);    Figure 19: Humidity computing    Figure 20: Temperature and humidity subsystem       5.4.4. Dust Pm2.5 subsystem  For this final sensor, an additional library [4] will be employed to implement our model-based design algorithm for measuring and computing the PM2.5 levels in our surroundings.   In this scenario, the GPIO Write block will be utilized to activate and deactivate the infrared LED on the sensor. Following activation, a 0.28ms delay will be introduced before employing the ADC to read the data, which will then be computed using the provided formula:  dustDensity = (170 * 5 / 1024 – 0.1) * Voltage      Figure 21: Formula applied for dust density    After applying the above-mentioned formula, another delay of 0.04ms will be used and then the LED will be turned off.      Figure 22: Dust Pm2.5 subsystem    5.5. FREEMASTER  To visualize the results from the application, a FreeMASTER project can be created. Once created, the .elf file of the built application can be added by navigating to Project -> Resource files -> "pack" directory setup -> MAP Files -> Default symbol file.  Variables can be added to the Variable Watch section. For this project, the most important ones are Pressure, eCO2, TVOC, humidity, temperature, and dustDensity.    Figure 23: Variable watch section    5.6. HARDWARE SETUP  A possible example for hardware setup is represented in the below picture:  Figure 24: Hardware setup    6. CONCLUSION    The application covers the steps of developing an air quality monitor that monitors how the pressure, TVOC, eCO2, humidity, temperature, and dust density evolve in a room, using the Model-Based Design Toolbox for S32K1 MCUs. It can be a good academic study for how to use the S32K1XX EVB and sensors using the MBDT and for how to adapt C code and use it in a graphic programming environment such as Simulink to simplify your work.      Bibliography:   [1] https://github.com/adafruit/Adafruit_BMP280_Library  [2] https://github.com/adafruit/Adafruit_CCS811  [3] https://github.com/sparkfun/SparkFun_HTU21D_Breakout_Arduino_Library  [4] https://github.com/mickey9801/GP2Y1010AU0F       NXP is a trademark of NXP B.V. All other product or service names are the property of their respective owners. © 2024 NXP B.V. MATLAB, Simulink, and Embedded Coder are registered trademarks of The MathWorks, Inc. See mathworks.com/trademarks for a list of additional trademarks.   
記事全体を表示
General Installer and Setup Installation Troubleshooting  TPL Communication TPL communication troubleshooting TPL Communication with multiple BCCs FreeMASTER Configuration FreeMASTER not detected on the HVBMU Board  TD Handler TD Handler indexing 
記事全体を表示
  Product Release Announcement Automotive Embedded Systems NXP Model-Based Design Toolbox for LAX – version 1.2.0 RTM   The Automotive Embedded Systems, Model-Based Design Tools Team at NXP Semiconductors, is pleased to announce the release of the Model-Based Design Toolbox for LAX version 1.2.0 RTM. This release supports automatic code generation for ARM Cortex-A53 and NXP LAX Accelerator cores from MATLAB for NXP S32R45 Automotive Microprocessors. This release adds support for RSDK 1.2.0, improves to code generation and Radar processing demo, and adds support for new trigonometric LAX kernels. The product comes with 60 examples, covering the supported RSDK LAX Kernels by MATLAB API and demonstrating the programming of the LAX accelerator from MATLAB environment.   Target audience: This product is part of the Automotive SW – Model-Based Design Toolbox.   FlexNet Location: https://nxp.flexnetoperations.com/control/frse/download?element=3983168   Technical Support: NXP Model-Based Design Toolbox for LAX 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 S32R45: ARM Cortex-A53 NXP LAX Accelerator Support Linux application build and run NXP Auto Linux BSP 37.0 for S32R45 Includes MATLAB API for additional RSDK LAX Kernels highly optimized for LAX accelerator add, sub, mul, div, times, cT, inv abs, abs2, sqrtAbs ¸conj, norm, norm2 diag, eye, zeros, ones, find, sort cospi, sinpi, tanpi, cispi, sincpi acospi, asinpi, atanpi, atan2pi Improved code generation and reduced memory usage Support for Radar SDK version 1.2.0 Support for MATLAB versions: R2021a R2021b R2022a R2022b R2023a R2023b R2024a More than 60 examples showcasing the supported functionalities: Cholesky Gauss-Newton Eigen (new) Kalman Filter Linear Regression Navier-Stokes QR Factorization (updated) MUSIC DoA (updated) Radar processing demo (updated) Range FFT, Doppler FFT, and Non-Coherent Combining offloaded to NXP SPT accelerator MUSIC DoA offloaded to NXP LAX accelerator     For more details, features, and how to use the new functionalities, please refer to the Release Notes and Quick Start Guides documents attached.   MATLAB® Integration: The NXP Model-Based Design Toolbox extends the MATLAB® experience by allowing customers to evaluate and use NXP LAX Accelerator from NXP’s S32R45 MPU and evaluation board solutions out-of-the-box. NXP Model-Based Design Toolbox for LAX version 1.2.0 is fully integrated with MATLAB® environment.       Target Audience: This release (1.2.0 RTM) is intended for technology demonstration, evaluation purposes, and prototyping on NXP S32R45 MCUs and Evaluation Boards.   Useful Resources: Examples, Trainings, and Support: https://community.nxp.com/community/mbdt    
記事全体を表示
PMSM Motor Control Application for S32K396 with MBDT and Custom Code Examples were designed on XS32K396-BGA-DC EVB and 3-phase PMSM pre-driver board(with connection cable) MATLAB Simulink-based project (s32k396_pmsm_mc_mbdt) is build using Model-Based Design Toolbox (MBDT) and can be downloaded from NXP Model-Based Design Toolbox for S32K3xx - version 1.5.0 or newer releases. For all models file and document, please find the attachment. 1. Introduction This article aims to introduce and demonstrate how a PMSM control algorithm targeting the S32K396 MCU can be designed inside the Simulink ® environment. The demo introduced by this article is built using (but is not part of) the NXP ® Model-Based Design Toolbox (MBDT) for S32K3xx, hence it has not been fully tested inside the MBDT development environment, neither been passed through the verification and validation processes imposed for the applications delivered within the toolbox. The demo presented in the following article is just an example of how NXP's software and hardware products can be used for developing motor control algorithms, using the MATLAB ® and Simulink ecosystem capabilities. The S32K39 is an Arm ® Cortex ® -M7 based Microcontroller series which runs up to 320 MHz, which contains an advanced motor control co-processor (eTPU) designed with the purpose of offloading the main CPU from motor control tasks, and a high-resolution PWM. It is developed to meet the next generation SiC traction inverter requirements and to enable high efficiency and low latency features. Also, S32K39 is suitable for applications like Automotive Inverter, On-board Charger (OBC), and High-performance Battery Management System (BMS). The NXP Model-Based Design Toolbox (MBDT) is a comprehensive collection of tools that plug into the MATLAB and Simulink model-based design environment to support verification, validation, and rapid prototyping of complex algorithms for real targets based on NXP microcontrollers and processors. For enabling hardware access from the Simulink applications development environment, MBDT offers integration with Real-Time Drivers (RTD) for controlling the system and peripheral devices. The configuration of the on-board peripherals, pins, and clocks, is realized by enabling the integration with dedicated configuration tools, like NXP’s S32 Configuration Tools delivered inside the toolbox, and EB Tresos. MBDT delivers a library of Simulink blocks, which implement functionalities of MCU peripherals and generate code on top of specific drivers' functions. Together with these, the toolbox integrates the AMMCLIB library, for facilitating the development of motor control algorithms. The toolbox offers support for software-in-the-loop and processor-in-the-loop (SIL and PIL) development workflows, allowing the design, verification and validation at each development step. It also generates and deploys code automatically, from Simulink models, to start up the MCU and run complex applications, which enables control engineers and embedded developers to shorten project life cycles. Hence, by using NXP's Model-Based Design Toolbox, complex algorithms, which can be modelled, simulated and verified hardware independently, using the rich ecosystem of solutions the MathWorks ® environment provides, can be tailored to become hardware aware for targeting specific NXP platforms. The S32K39 is an Arm Cortex-M7-based Microcontroller series, which contains an advanced motor control co-processor (eTPU), a high-resolution PWM, and runs up to 320 MHz. It is developed to meet the next-generation SiC traction inverter requirements and to enable high efficiency and low latency features. Also, S32K39 is suitable for applications like Automotive Inverter, On-board Charger (OBC), and High-performance Battery Management System (BMS). This demo aims to give a quick start guide on building up a motor control system with NXP MBDT on S32K396. It contains the environment setup, module configuration, system initialization, and interruption structure, Permanent Magnet Synchronous Motor (PMSM) control algorithm, and FreeMASTER configuration. 2. Hardware and Software Setup For more details on how this can be achieved, the following diagram is introduced, mapping the PMSM algorithm on top of the existing hardware for the S32K396 MCU. The App, Algorithm, Data processing section can be implemented using Simulink libraries blocks, AMMCLib blocks and Simulink custom code functionalities to include eTPU drivers that address this co-processor access and control. The MBDT section is covered by the blocks provided by the toolbox, ensuring hardware access to the peripherals implied in such applications, while the MCU, Motor, circuits refers to the hardware elements used for the design.  The following picture presents the application mapping of the software and hardware used to develop PMSM Motor Control on S32K396: Figure 2.1 Application mapping of software and hardware used to develop PMSM Motor Control on S32K396 For an overview of the elements necessary for modeling such a diagram inside a Simulink model, the following picture is introduced, showcasing the software components and functionalities that can be used inside this scenario, which will be furtherly detailed in the following sections. Figure 2.2 Software Components for modeling the PMSM Motor Control on S32K396 This demo aims to give a quick start guide on building up a motor control system with NXP MBDT on S32K396. It contains the environment setup, module configuration, system initialization, and interrupts structure, Permanent Magnet Synchronous Motor (PMSM) control algorithm, and FreeMASTER configuration, demonstrating the following features: 3-phase PMSM speed Field Oriented Control. Integrated eTPU software resolver functions for position and speed measurement. Develop PIL models for hardware simulation and PIL test. Application control user interface using FreeMASTER debugging tool. (Please get more details on FreeMASTER from section 9 and the references part) 2.1 Required software S32 Design Studio for S32 Platform 3.5 EB tresos Studio 29.0 FreeMASTER 3.2 MATLAB R2023b with “Embedded Coder ® for ARM Cortex-M Processors” NXP Model-Based Design Toolbox for S32K3xx version 1.5.0 SW32K3_S32M27x_RTD_R21-11_4.0.0_P19(contained in the toolbox) 2.2 Required hardware The following is a list of required hardware: Boards: XS32K396-BGA-DC EVB and MC33937 MOSFETs pre-driver (with connection cable). Motor: 3-phase PMSM TGT2-0032-30-24. Debugger: Lauterbach for Cortex-M7 or Multilink PE micro debugger. Power: 12V power supply for EVB and 24V power supply for pre-driver board. PCIE Cable. Micro USB Cable. Note: The debugger Lauterbach is not integrated in the MBTD tool, it is only a method to debug the code. 2.3 Prepare the demo The central controller EVB board runs the control algorithm, and the pre-driver drives the motor. Connect the hardware devices with the following steps: Figure 2.3.1 Hardware Setup Connect the PMSM’s three-phase winding to J4 on the pre-driver and connect the resolver signal to J8 on the pre-driver. Connect motor control signals from J14 on the pre-driver to J44 on the EVB board. Connect the debugger between JTAG J20 and the computer. Connect the USB cable between J15 and the computer, then the EVB LED D30 will be solid green. Plug in the 12V power supply port J1 on the EVB board, then the EVB LED D4 will be solid green. Plug in the 24V driver power on port J13 of the pre-driver, and then the pre-driver LED D14 will be solid yellow. 2.4 Running the demo Please refer to the  S32K396_MBDT_BASED_MOTOR_CONTROL_Quick_Start_Guide_0_9_0.pdf  in the project doc folder. 3. Demo blocks introduction In the following figure, an overview of the main Simulink model is presented. The motor control application model has the following structure: Initialization and Interrupt. Figure 3.1 Simulink Application Top Model  Var Init contains the variables used by the model and can be visualized in FreeMASTER. Initialize subsystem contains the FreeMASTER configuration, state machine and control mode initialization, and BCTU hardware trigger enablement. This subsystem is executed only once, at the beginning of the application. Hardware Interrupt Callback calls the motor control block to run. This block delivered by the MBDT, allows the implementation of specific actions inside a callback function which is executed when an interrupt occurs on the configured peripheral instance, at a specific event. Callbacks are associated with specific events inside the configuration project used with the model, which ensures the on-board configuration of the peripherals, pins, and clocks. Motor Control function-call subsystem runs every time an ADC interrupt occurs. Inside the Motor Control subsystem, as illustrated below, the ADC hardware trigger is disabled (Step 1) until the PMSM control algorithm calculation is finished (Step 2), and reenabled at the end of this computation (Step 3). The priority order of the generated code is achieved by setting the “Priority” value, accessible inside the Properties of each Simulink block. Figure 3.2 Motor Control Subsystem The pmsm_mc_algo algorithm is a subsystem reference model. It collects the input sensor signals, calculates the PMSM control algorithm, and drives PWMs to generate the output voltage. Following figure shows the main blocks: Current Voltage Measurement reads BCTU FIFO data and calls the following blocks. Board Buttons control the motor with hardware pins on board. State Machine subsystem contains the Stateflow® of the motor control application and each state will call a dedicated function block. Enable Outputs enables the PWM output function. Disable Outputs disables the PWM output function. Green LED Toggle controls a green LED to blink. Update PWM calls the MBDT PWM block to update the duty cycle value. Figure 3.3 PMSM Motor Control Algorithm 4. Startup initialization The startup initialization is a subsystem of the initialize function block. It’s used to configure some basic functionality at the start of the application: FreeMASTER Config which configures the UART to communicate with FreeMASTER GUI. FreeMASTER Config block allows the users 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. Gpt_StartTimer enables one GPT channel for pre-driver MC33937 dead time configuration. Adc_CtuEnableHwTrigger enables the BCTU hardware trigger feature. Set the event and state to reset values and set the default control mode as speed control. Figure 4.1 Initialize Subsystem 5. Interrupt and measurements This part describes the configuration and usage of BCTU and ADC modules for analog data capturing. BCTU is triggering parallel ADC conversions for 3-phase current measurements. After all measurements are fulfilled, the BCTU FIFO notification is used to read the stored ADC data and to call the main control loop of the application for further processing.  5.1 Interrupt configuration and service The following picture shows the configuration for the BCTU FIFO notification callback feature. The BCTU FIFO 1 is used to store the ADC results, the watermark value decides when to call the function configured in the notification. Also, enabling the BCTU IRQ in configuration is required. Figure 5.1.1 BCTU Watermark Notification Configuration  Figure 5.1.2 BCTU Interrupt Enablement In the Simulink model, the configured notification for BCTU is selected inside the Hardware Interrupt Callback block. This will execute the connected function-call subsystem when the End-of-Conversion interrupt occurs. Figure 5.1.3 Interrupt Callback Subsystem 5.2 Measurements of currents and voltage This section describes the measurement of analog quantities: 3-phase currents and DC bus voltage. BCTU receives the hardware trigger to start the ADC measurements (parallel conversions). Once all results have been stored into the FIFO, the interrupt will call the main control loop. BCTU FIFO notification is used to call the main loop of the motor control, which ensures the sampling is finished before using them. How to get sampled values for processing is presented in this section. The following picture shows the steps and operations to transfer the current and voltage to their real physical values. To acquire the currents and voltage from BCTU FIFO for further processing, the Adc block from MBDT library is used and the Adc_CtuReadFifoData is selected.  Figure 5.2.1 Process converted data to physical values 6. eTPU resolver Software resolver is now widely used in the Inverter application, which can help to save the BOM (Bill of Materials) cost. The eTPU on S32K39 supplies a function to the customer to implement a software resolver via a software package. It uses one eTPU channel to generate a 50% duty-cycle PWM output signal to be passed through an external low-pass filter and used as a resolver excitation signal. In the resolver position sensor, this excitation signal is modulated by the sine and cosine of the actual motor angle. The feedback Sine and Cosine signals are sampled by an SDADC and processed by a followed DSP. The conversion results can be transferred to eTPU DATA RAM by DMA. Then, the eTPU can process the digital samples of resolver output signals and output the position and speed for the FOC. For more details about the eTPU resolver, please refer to AN13038. Figure 6.1 eTPU Resolver Diagram 6.1 Resolver functions call in MATLAB The eTPU Resolver Block is not yet available in MBDT. The System Output block is used to insert custom code for getting resolver data. The getMotorControlResolver(&mbd_ebt_DW_FOC_one.Resolver_SW) function is used to get resolver data. Figure 6.1.1 Simulink custom code for eTPU access The speed and angle are estimated from the Resolver Angle subsystem and are provided to the slow & fast control loops. Finally, the sine and cosine values from the estimated electrical angle are computed. Figure 6.1.2 Computation of the speed and angle 7. State machine This is a critical part of the motor control application model, each state has a dedicated block to handle the related functions. Figure 7.1 Motor Control States Implementation The state machine block controls the workflow of the motor control application, it has been designed using Stateflow. Figure 7.2 Finite State Machine 8. PWM control and update Subsystems Enable Outputs and Disable Outputs control the output of PWM. They are called by the state functions. In the subsystems, the flag PWM_enabled and gate driver output status are changed via the pwm_enable_output or the pwm_disable_output function. Figure 8.1 Enable Outputs Subsystem Figure 8.2 Disable Outputs Subsystem Update PWM subsystem is used to generate the PWM duty cycle value according to the output from the control loop. This value is eventually set for the FlexPWM peripheral to generate PWM voltages to drive the motor. The FlexPWM is configured to generate complementary signals for bridges and is updated synchronously according to a reload signal in the EB project. Here it is only needed to pass the duty cycle values to the Pwm function in the model. Figure 8.3 PWM Duty Cycle Values Computation Figure 8.4 PWM Duty Cycle Values Update 9. Buttons Buttons are used to control the running of the motor. The algorithm reads the value of the button from the board to change the running state or speed. The Dio block in the MBDT library is used to read the value of I/O. The I/O port of buttons has been configured in the EB project. Two buttons on the board are used to increase or decrease the running speed of the motor. Also, they are used to clear the fault information when pressed together. One button is used to control the start or stop of the motor. The following picture shows the subsystem for the button control logic. Figure 9.1 Buttons Control Logic 10. FreeMASTER GUI FreeMASTER is a user-friendly real-time debug monitor and data visualization tool that enables runtime configuration and tuning of embedded software applications. To enable FreeMASTER in this project, the interface needs to be configured first. MBDT supplies blocks to support FreeMASTER’s configuration. In this project, LPUART_0 is used to transmit data between the GUI and the board. The following figure shows the MCAT GUI, which can be used to observer parameters/variables and also used to control the status of the motor. It can be found in the project folder, under “./mbd/FreeMASTER_control”. Figure 10.1 MCAT GUI 11. PIL model PIL represents a verification and validation step where the code generated for the developed control algorithm is cross-compiled and deployed on the target hardware, then stimulated with test inputs from the Simulink application executed on the host PC, containing the plant model. The test inputs are sent to the target via Serial Communication. By enabling this simulation mode, users could test the performance of the processor long before having the final hardware design, testing whether the model and the generated code are numerically equivalent, and being able to perform code execution profiling. Hence, for this motor control design, we have also developed a PIL model (pil_model_ebt) used to verify the model-generated code on the S32K396 microcontroller. The PIL top model contains two parts: Simulation Model and Hardware Model. The Simulation Model contains the model of the real system (pre-driver and PMSM), as depicted inside Section 11.1. The Hardware Model contains the control algorithm which is the same as in the application previously introduced (mbd_ebt.slx). For the hardware Model part, the code will be generated, built and an executable file will be deployed on hardware. Input and output signals processing blocks will generate the necessary test inputs for the code that runs on the hardware controller, as depicted in the screenshot below. Figure 11.1 PIL Top Model 11.1 PIL Model introduction The PIL top model runs the simulation model part inside the Simulink environment and exchanges signal data with the hardware controller through Serial Communication. 11.2 Simulation model The simulation model simulates the hardware of the pre-driver and PMSM using Simscape™ Electrical™ blocks. Duty to PWM simulates the function of a central aligned FlexPWM with the frequency of 20kHz. Inverter simulates three-phase full-bridge circuit with the same parameters as in MC33937 MOSFETs pre-driver. PMSM is defined with the same parameters as the real motor. Resolver is simplified as an ideal rotational motion sensor. Phase Current Sensing, Bus Current Sensing and Bus Voltage Sensing are built up regarding MC33937 MOSFETs pre-driver. SARADC block samples signal simultaneously with the PWM module and generates a function call after data conversion is completed. Figure 11.2.1 PIL Host Model 11.3 Hardware model The hardware model is a referenced model that generates code and deploys it into the microcontroller. It’s called by ADC conversion completion signal. In the initialization process, it initializes the global variables and drivers. In the normal running process, when a function call comes, the model will calculate the input signal, run the state machine, and generate the output signal in the order defined in subsystem “pmsm_mc_algo”. Figure 11.3.1 PIL Target Model 12. Conclusions NXP's MBDT enables the usage of hardware optimized tools: Real-Time Drivers (RTD), Automotive Math and Motor Control Library (AMMCLib), Configuration (S32 Configuration Tools and EB Tresos), and Build Tools in the Simulink environment. This article gives examples on the construction and environment setup process for designing motor control models, and how they can be verified and validated through PIL simulation before being deployed on the target hardware. It focuses on how NXP’s Model-Based Design Toolbox and the software NXP provides could be used together with MathWorks tools and functionalities for rapid prototyping complex embedded designs on NXP targets. Together with the rich MathWorks ecosystem, it allows users to model complex algorithms, and generate optimized code for the NXP’s microcontrollers and processors, ensuring thus a fast and reliable programming environment. Please note that the demo was not fully tested inside MBDT ecosystem and application development workflow it proposes, as the depicted example uses custom code functionalities for addressing the eTPU co-processor access, currently not supported by MBDT, and a specific version of the RTD, different than the one the toolbox was released and tested with. For more information about MBDT, tutorials, webinars and other resources, please visit the MBDT Community Page. You might also visit NXP.com for additional information on the development ecosystem that NXP offers. 13. References 3-phase Motor Control Kit with S32K396 The workshop “3-Phase PMSM Control Workshop with NXP's Model-Based Design Toolbox” from NXP Community Module 4: Space Vector Modulation from NXP Community MC33937: 3-Phase Field Effect Transistor Pre-driver. Automotive Math and Motor Control Library Set for NXP S32K3xx devices. FreeMASTER Run-Time Debugging Tool. Application Note: AN13902: 3-Phase Sensorless PMSM Motor Control Kit with S32K344 using MBDT Blocks
記事全体を表示
1. Introduction   This article demonstrates how to control a 4-wire server fan based on temperature or user input, using the Model-Based Design Toolbox for S32K1 MCUs. The Model-Based Design Toolbox represents a solution which allows the complex applications deployment on NXP hardware directly from Simulink. By incorporating hardware optimized software, such as drivers, libraries, and tools, the Model-Based Design Toolbox allows the users to focus only on the algorithm development, while making such applications hardware-aware is handled by the toolbox. By the integration with the MathWorks ecosystem, the MBDT leverages the model-based design paradigm, thus enabling a programming process based on models - users to not need to write C code for implementing their designs, but create logical diagrams using Simulink blocks performing dedicated functions. In this article, we will demonstrate how this tool can be used for designing and deploying on an S32K146 Evaluation board a fan speed control application. Thus, the steps proposed for achieving this are described thorughout the article, in the following sections: II. Application overview – how the application works and the links between the components; III. Hardware design – the description of the components used and the electrical diagram; IV. Software design – the application execution flow and the model implementation explained in more detail; V. Conclusion – the results of the application.   2. Application overview   The application has 2 operating modes: automatic and manual. To switch between operating modes, we need to press the SW2 button on the S32K146 board. When starting, the application is in automatic operating mode (the RGB LED of the board lights up green): this means the fan adjusts its speed according to temperature. In manual mode (the RGB LED of the board lights up blue), the fan changes its speed depending on the value supplied by the potentiometer. The graphs and values of fan speed, acceleration, ambient temperature will be displayed in FreeMASTER. Block diagram   Figure 1: Block diagram   3. Hardware design   A. Hardware components The required hardware components are:  S32K146 Evaluation board  Thermistor NTC100K  4-wire PC fan   12V power supply AC-DC.   1) S32K146 Evaluation board The S32K146EVB serves as an affordable evaluation and development board designed for a wide range of industrial and automotive uses. The board is the “brain” of the application, as it collects data from various sensors (e.g.: temperature sensor) and uses the algorithm to regulate the actuators (e.g.: the BLDC motors found in fans).  For more information about the board, please read from here.   2) Thermistor NTC100K A thermistor is a resistor whose resistance is dependent on temperature. The temperature value is calculated using the Steinhart-Hart equation. The Steinhart-Hart coefficients A, B, C vary depending on the type and model of thermistor and the temperature range of interest. To find these coefficients, we use three values of resistance data for three known temperatures. For example, from NTC100K Thermistor Datasheet we get for the temperatures of 15℃, 25℃ and 45℃, corresponding resistance values of 156407 Ω, 100000 Ω and 43659 Ω. It results, according to the equation (2), that the coefficients have the following values:  So, the steps to determine the temperature are to get the thermistor resistance using a voltage divider converter along with an analog-to-digital converter (ADC) and calculate the temperature from the resistance.    3) 4-wire PC fan The fan has 4 pins, being used especially for processors with high power consumption. The simplest fan has 2 pins, one for power and one for ground. The 3-wire fan has an extra pin called “tachometer”, which indicates the speed of the fan (one/two impulses are received for each rotation). With 2-wire and 3-wire fans, the speed is controlled by increasing/decreasing the voltage on the power pin. Instead, the 4-wire fan has a control pin and uses PWM (Pulse Width Modulation) to control the speed.  Before using the fan, we must find out information such as the maximum speed, the number of impulses per rotation given by tachometer and the minimum operating speed if necessary. These things can be looked up in the fan’s datasheet or can be determined experimentally if we have an unknown fan, and we cannot find its datasheet.  The values of the fan used as an example in this article were determined experimentally and we got an approximate maximum speed of 300 rotations per second (18000 rpm), two impulses per rotation and a minimum operating speed of 80 rotations per second (4800 rpm).    4) 12V power supply AC-DC The power supply converts alternating current (AC) electrical energy into direct current (DC) electrical energy with an output voltage of 12 volts. In our application, it will supply the power for the fan.   B. Electrical schematic There are multiple hardware configurations for the fan speed control application. We will use, in addition to the hardware components mentioned above (fan, 12V power supply, thermistor), the potentiometer, the SW2 button and the RGB LED of the S32K146EVB.  We propose the following electrical schematic:  Figure 2: Electrical schematic Note! It is important that all components are connected to the same ground.   C. Hardware setup A possible hardware setup may look like in the following picture:  Figure 3: Hardware setup example   4. Software design   A. Prerequisite software To be able to follow the next steps in this article, the following software is necessary: MATLAB ®  and Simulink ®  (2021a or newer), including Stateflow ® , MATLAB ®  Coder TM , Simulink ®  Coder TM , Embedded Coder ® Model-Based Design Toolbox for S32K1xx 4.3.0   B. Flow chart The application execution flow is based on a state machine, according to the following diagram. Figure 4: State machine The architecture of the application is a closed-loop system, which uses a feedback signal to adjust the fan speed. The current fan speed and the fan acceleration update their values with each tachometer pulse. The difference between the reference speed (set using temperature or potentiometer) and the current speed, alias error signal, is the input to the closed-loop control system, such as a proportional-integral-derivative (PID) controller. The PID controller applies a correction based on proportional, integral, and derivative coefficients to a control function, in our case, it determines the PWM duty cycle to control the fan speed.  Figure 5: Application's model   C. Model Overview From top to bottom (Figure 5), we have 4 big sections:  Initialization Switching between operating modes The operating modes which set the reference speed The control algorithm. Let’s take each section to dive further into the details.    1) Initialization  Figure 6: Initialization section We have on the first line, from left to right, the Configuration block for S32K1xx processor family, the FreeMASTER Configuration Block and two ADC Configuration Blocks. On the second line, we have the pull-up resistance on the tachometer pin and two mapping functions from the temperature value and the ADC potentiometer value to the reference speed. Also, there are variables for current operating mode, temperature value, reference speed, current speed, duty cycle and some other auxiliary variables.  The required configurations of the processor configuration block are the default ones, except for the processor model and the download interface (Figure 7).  For the FreeMASTER configuration block, we set the communication interface (e.g.: LPUART1), the baud rate (e.g.: 19200) and long interrupt serial communication. This component provides an interface where relevant data such as current speed, ambient temperature and many others are displayed. In the ADC configurations blocks, used for reading temperature and potentiometer value, we select the ADC converter number and the resolution mode (e.g.: 10-bit conversion).   Figure 7: Configuration block for S32K1xx family of processors   2) Switching between operating modes We configure the pin PTC12 (SW2) to generate a falling edge interrupt on each button press, using the GPI ISR block. Figure 8: Switching mode section When an interrupt is generated, the value of the operation mode variable is toggled and the color of the LED corresponding to the operating mode lights up (automatic mode – green, manual mode – blue). It also enables/disables the PIT (Periodic Interrupt Timer) interrupt which triggers the ADC reading of the temperature sensor at each one second (Figure 10).  Figure 9: The function called when the interrupt is generated.  Figure 10: Enable/disable PIT interrupt for ADC temperature reading; RGB LED in Automatic & Manual mode   3) Operation modes  Figure 11: Operation modes section Depending on the operating mode, the reference speed is set by the temperature value or the ADC value of the potentiometer. a) Automatic mode In this mode, the PIT block is enabled, and the ADC value of the thermistor is read once per second. The resolution of the ADC is 10 bits. So, it can take values between 0 and 1023, which corresponds to voltage values between 0V and 5V. Let’s assume Vout is the output voltage on the pin PTB13. Also, according to the electrical schematic from Figure 2, we have a voltage divider: We can find out the value of thermistor resistance: And then, we can get the temperature value using the Steinhart-Hart equation (1).  Based on the temperature, we can map a value for reference speed. We can define for this mapping a linear function or whatever we need.  Figure 12: Automatic mode   b) Manual mode In manual mode, the ADC value of the potentiometer is read and mapped to reference speed.  Figure 13: Manual mode   4) The control algorithm  Figure 14: The control algorithm section In this section, the closed loop of the system is implemented using the PID (Proportional-Integral-Derivative) controller. We must tune the coefficients of the PID controller (Kp, Ki, Kd) to produce the optimal control function. There are several methods for tuning: manual, Ziegler-Nichols or using software specialized tools. For this application, the Ziegler-Nichols method was used, and, for fine adjustment, manual tunning was applied. After applying this method, we get the following values: KP = 0.003, KI = 0.003, KD = 0.001.  Figure 15: PID controller configuration With the PWM signal from the PID controller, we control the fan speed via the PWM pin, using the FTM PWM Config block. We configure the block as follows:  Figure 16: Parameters of FTM PWM Config block According to the electrical schematic (Figure 2), the pin used to control the fan speed is PTC1, which corresponds to FTM0_CH1. This means we need to configure the channel 1 from the module 0 of FTM (FlexTimer Module). To get the fan current speed, we need to know the period between two pulses from the tachometer. This can be determined using the FTM Input Capture block, which returns the timestamp in microseconds. Remember that there are two pulses per rotation. We measure the speed once every 10 milliseconds. So, the acceleration has the following value:  Figure 17: Calculation of fan speed and acceleration   D. FreeMASTER To visualize the results of the application, you can create a FreeMASTER project. Add the .elf file of the built application to Project – Resource files – “pack” directory setup – MAP Files – Default symbol file. You can add variables to the Variable Watch section, such as operation mode, current speed, reference speed, temperature (Figure 19). Also, you can create a graph, as in Figure 18, using the FreeMASTER oscilloscope with the current speed and reference speed. In the following figure, we can observe that the system is initially in automatic mode: temperature is about 28 Celsius degrees, which corresponds to an approximate reference speed of 110 rotations per seconds. Then, when SW2 button is pressed (at second 685 on the graph), the system goes into manual mode and the reference speed is set about 236 rotations per second, which is mapped according to the value read from the potentiometer. The current speed (red line) is tracking the reference speed imposed (green line).  Figure 18: Graphic with reference speed and current speed Also, we can track values such as operation mode - boolean value (0 for automatic mode and 1 for manual mode), temperature in Celsius degrees, reference speed and current speed measured in rotations per second, acceleration or the PWM duty cycle used for controlling the fan speed.  Figure 19: Variable watch section   5. Conclusion   In conclusion, the application consists in controlling the fan speed depending on the temperature or the potentiometer value, using the Model-Based Design Toolbox for S32K1 MCUs. It combines notions from systems theory, electronics, and embedded systems, representing an academic study on the use of fans for temperature control in different applications like servers, routers, switches, etc.   Useful links:   1. S32K146EVB:   https://www.nxp.com/document/guide/getting-started-with-the-s32k146-evaluation-board-for-general-purpose:NGS-S32K146EVB  2. NTC100K Thermistor: https://www.tme.eu/Document/f9d2f5e38227fc1c7d979e546ff51768/NTCM-100K-B3950.pdf  https://en.wikipedia.org/wiki/Steinhart%E2%80%93Hart_equation#Steinhart%E2%80%93Hart_coefficients  3. 4-wire fan:  https://www.electroschematics.com/4-wire-pc-fan/  https://www.nidec.com/en/product/search/category/B101/M111/S100/NCJ-V40S-E5-57/  4. PID coefficients:  https://control.com/textbook/closed-loop-control/p-i-and-d-responses-graphed/  https://en.wikipedia.org/wiki/Proportional%E2%80%93integral%E2%80%93derivative_controller    NXP is a trademark of NXP B.V. All other product or service names are the property of their respective owners. © 2024 NXP B.V. MATLAB, Simulink, and Embedded Coder are registered trademarks of The MathWorks, Inc. See mathworks.com/trademarks for a list of additional trademarks.  
記事全体を表示
    Product Release Announcement Automotive Processing NXP Model-Based Design Toolbox for BMS – 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 BMS version 1.0.0 EAR. This release is an Add-On for the NXP Model-Based Design Toolbox for S32K3xx 1.4.0, which supports automatic code generation for battery cell controllers and applications prototyping from MATLAB/Simulink. This new product adds support for MC33775A, MC33772C, MC33665A BCCs and part of their peripherals, based on BMS SDK components (Bcc_772c, Bcc_772c_SL Bcc_775a, Bms_TPL3_SL_E2E, Bms_common, Phy_665a). In this release, we have added the integration with the Model-Based Design Toolbox for S32K3xx version 1.4.0, added support for the BMS SDK 1.0.1, and MATLAB support for the latest versions. The product comes with battery cell controller examples, targeting the NXP HVBMS Reference Design boards.   Target audience: This product is part of the Automotive SW – Model-Based Design Toolbox.   FlexNet Location: https://nxp.flexnetoperations.com/control/frse/download?element=3720278   Technical Support: NXP Model-Based Design Toolbox for BMS 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 Battery Cell Controllers derivatives: MC33775A MC33772C MC33665A   Support for the following peripherals (BMS SDK components): Bcc_775a Bcc_772c Bms_Common Bms_TD_handler Bcc_772c_SL Bcc_TPL3_SL_E2E   Support for MC33775A and MC33772C battery cell controllers & MC33665PHY The toolbox provides support for the MC33775A, MC33772C, and MC33665. The MC33775A and MC33772C are lithium-ion battery cell controller ICs designed for automotive applications that perform ADC conversions of the differential cell voltages and battery temperatures, while the MC33665 is a transceiver physical layer transformer driver, designed to interface the microcontroller with the battery cell controllers through a high-speed isolated communication network. The ready-to-run examples provided with the MBDT for S32K3 show how to communicate between the S32K344, the MC33775A and MC33772C via the MC33665 transceiver. For the MC33775A, the examples show how to configure the battery cell controller to perform Primary and Secondary chains conversion, and read the cell voltages conversion results from the MC33775A, while for the MC33772C the examples show how to configure the Battery cell controller to read current. All the converted values are displayed to the user over the FreeMaster application.             BMS SDK version supported (1.0.1) Support for MATLAB versions We added support for the following MATLAB versions: R2021a R2021b R2022a R2022b R2023a   Examples of the functions supported: MC33775A Configuration and data acquisition example MC33772C Configuration and data acquisition example RD-HVBMSCTBUN Configuration and data acquisition example   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 Battery Cell Controllers together with S32K3xx MCUs and evaluation board solutions out-of-the-box with: NXP Model-Based Design Toolbox for BMS version 1.0.0 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 battery management systems prototyping using NXP Battery Cell Controllers and S32K3xx MCUs and Evaluation Boards.   Useful Resources: Examples, Trainings, and Support: https://community.nxp.com/community/mbdt      
記事全体を表示
1. Introduction This is the fourth article in the Beginner’s Guide series and it aims to showcase how to configure the CAN peripheral to be able to send and receive CAN messages over the CAN Bus using the MR-CANHUBK344 Evaluation Board. For more details about the MR-CANHUBK344 board or step-by-step instructions on how to run a Simulink ® model on it using MBDT, please check out the first article in the series: Interacting with Digital Inputs/Outputs on MR-CANHUBK344. This article’s application consists of reading digital and analog inputs, processing them before they are sent across the CAN Bus from one CAN instance to another, and then controlling digital and analog outputs based on the received message. 1.1. Extra Prerequisite Software On top of the requirements from the first article, the application that we are developing in this article requires the Vehicle Network Toolbox TM from MathWorks. 1.2. Optional Hardware In this article we are going to show the messages that are sent across the CAN Bus using a device that can interact with the CAN Bus. The specific model we are using is the PCAN-USB Pro FD. 2. CAN Configuration This chapter will focus on the changes that have to be made in the configuration project in order for the board’s components to communicate properly with each other. It will focus mainly on the CAN-related settings, as the settings for the DIO, ADC and PWM have been explained in the previous articles. 2.1. Hardware Connections The MR-CANHUBK344 board has 6 CAN instances, with 3 different transceivers among them. CAN0 and CAN1 use TJA1443ATK, CAN2 and CAN3 use TJA1463ATK and CAN4 and CAN5 use TJA1153. Each of the CAN instances has 2 identical connectors, wired to each other, labelled A and B, to allow for daisy chain wiring. In this article we will focus on communicating between the CAN0 and CAN1 instances. Note: A CAN bus usually requires 60 Ohm termination at both ends of a CAN bus. This may be accomplished using one of the included CAN Term boards. For a CAN instance to work properly, the unused connector (if there is one) has to be connected to a CAN Term board, which is included in the MR-CANHUBK344 package. Below you can find a schematic that shows how the CAN0 instance is connected to its transceiver and how the signals are routed between them: 2.2. Pins Configuration The pins for the CAN instances can be found by searching for the component name inside the schematic. For this article’s purpose, I have extracted the necessary pins below. The _RX and _TX pins are linked directly to the CAN instance, while the _ERRN, _STB and _EN pins correspond to the transceiver associated to the CAN instance, like illustrated in the schematic above. To start configuring the pins, we have to open the Pins Tool, inside the S32 Configuration Tools. To quickly open the configuration project for a model, you can click on the Configure button from the window that appears when double-clicking a MBDT Block. Once the software has opened, clicking the Pins button will open the  Pins Tool. Inside the Pins Tool, we will focus on the top-left window, called the Pins tab. First, we check if the pin we are trying to add already exists in the configuration by typing the name in the search bar. Here we can see that no other pin is configured for this purpose (by the lack of green checkmarks in the box to the left). This has to be done for every of the 12 pins that we are configuring. This process has been showcased in detail in the first article, Interacting with Digital Inputs/Outputs on MR-CANHUBK344. Here is a case where the pin already exists. The steps that have to be taken in order to remove the old configuration consist of clicking the green checkmark, and then unchecking the currently selected option in the window that pops up. After checking every pin, we can start adding the ones we want to configure. Note: CAN_RX, CAN_ERRN are inputs, while CAN_TX, CAN_STB and CAN_EN are outputs. The CAN_STB and CAN_EN are outputs because we will set appropriate values to them to initialize the transceiver by switching it into the normal operating mode, while the CAN_ERRN is an input because it is used to inform the MCU about possible problems that can take place when initializing the transceiver. To do that, we type the pin’s value in the search bar. As an example, let’s look at some of the pins that we are configuring: The LED_CAN0 pin is connected to a red LED placed near the CAN connector which is used separately from the CAN, similarly to any other LED on the board. It also shares the same inverted logic as the other LEDs. It has the corresponding value PTC18, which we type in the filter. Afterwards, we populate the Identifier and Label fields with the pin’s name. Then we click the checkmark to the left and select the appropriate option in the window that shows up. Here, the for the LED we select the SIUL2:gpio,82 option. Since we are configuring an LED, which is an output, we also select the Output option in the window that asks for the pin’s direction. The process is similar for the other pins, but keep in mind that when configuring the CAN_RX and CAN_TX pins, you have to choose another signal from the list of available signals. Given the difference between the pins we are configuring, the CAN_ERRN, CAN_EN and CAN_STB are connected to the SIUL2 peripheral as inputs/outputs, while the CAN_RX and CAN_TX are connected to their respective CAN peripheral. Here is how that looks for the CAN0_RX pin: This is how the signals for the CAN0 and CAN1 instances look after being configured: To be able to see the signals in a similar manner, you can type “CAN” in the search bar of the bottom window, called Routing Details. Next, we have to return to the Peripherals Tool by clicking the highlighted button.   2.3. Component Configuration 2.3.1. CanController To start configuring the CAN instances, the first step is to open the Can_43_FlexCAN component and navigate to the CanController tab, inside the CanConfigSet panel. Here we are going to configure the two CAN controllers that correspond to the CAN0 and CAN1 instances. The CanController section provides all the necessary settings to configure a CAN controller instance, as required by the application.  You can expect to interact with some of them more frequently than the rest, so we are focusing on explaining what these do. The Name field controls the name that is associated to the controller and it is used to reference the controller in other menus. Can Hardware Channel controls which physical CAN instance is connected to the current controller. The Can Controller Activation checkbox enables the Can Controller. Without it, the controller does not function. CAN Rx/Tx Processing Type enables/disables read and write operations through Can_MainFunction_Read(), respectively Can_MainFunction_Write(), for handling PDU (Protocol Data Unit) events while set to polling. If the parameter is set to POLLING or MIXED, then the functions mentioned will be polling for RX Indication or TX Confirmation. If the parameter is set to MIXED, then only the hardware objects which have the attribute CanHardwareObjectUsesPolling set to true will be affected. Alternatively, if the parameter is set to INTERRUPT, Can FD ISO controls whether the Flexible Data-Rate feature is enabled on the Controller. In this example, we use the Can FD protocol for communicating between CAN instances so it will be checked. The Can Controller Default Baudrate field is responsible for choosing which Baudrate configuration to assign to the controller. The Baudrate configuration will be presented in the following screen. CanCpuClockRef allows you to select the reference clock. For the CAN peripheral, there are 2 clocks available, FLEXCAN_PE_CLK0_2 and FLEXCAN_PE_CLK3_5, covering the CAN0, CAN1, CAN2 and CAN3, CAN4, CAN5 respectively. These clocks can be configured inside the Mcu component, which will be shown in the following chapters. The Name field is used to select it in the Can Controller Default Baudrate field from the previous screen. Can Automatic Time Segments Calculation can be used to automatically set the Can Propagation Segment, Can Phase Segment 1 and Can Phase Segment 2 according to the Bitrate and the Can Controller Prescaler. Can Controller Prescaler sets the prescaler for the controller, based on the Clock selected. Can Controller BaudRate (Kbps) controls the speed that the data is transferred at. In the following section, containing Can Propagation Segment, Can Phase Segment 1 and Can Phase Segment 2 you can configure the timings of the CAN transfer. And finally, in the bottom section you can configure the timings for the Flexible Data-Rate protocol, by changing the Can FD Controller Baudrate, Can FD Propagation Segment, Can FD Phase Segment 1, Can FD phase Segment 2, Can FD Resynch Jump Width and Can FD Prescaler. These can be seen as FD equivalents for the previous settings. The first section allows you to configure the CanRamBlock associated with the current Can Controller. A CAN controller’s CAN RAM contains CAN hardware objects defined as a PDU buffer. The CAN RAM block can store message buffers in different configurations of sizes. According to the S32K3XX reference manual, the RAM block can store 32 messages of 8 bytes, 21 messages of 16 bytes, 12 messages of 32 bytes or 7 messages of 64 bytes. In the second section, CanRxFifo, the RX Fifo can be added or removed. According to the S32K3XX Reference manual, only the CAN0 allows the use of Enhanced RX FIFO. So if you are using another CAN instance and the FD protocol, the CanRxFifo should be disabled duo to the incompatibility between CanLegacyFifo and the FD protocol. Since this article’s application involves 2 CAN instances communicating with each other, it means that another Can Controller has to be set up besides the one that is already here. To have a solid starting point for the second Can Controller’s configuration, you can copy the current controller’s configuration and paste it into a new one. After completing the steps above, you will end up with 2 identical Can Controllers, which will cause conflicts due to duplicate items. To solve this, fill in the details for the second Can Controller. In this case, that only involves changing the Name, the Can Hardware Channel, the Can Controller ID (which should simply increment) and Can Controller Default Baudrate (the correct one becomes available in the dropdown list after changing the Name field). The last setting that needs to be changed on this newly created Can Controller is deleting the CanRxFifo, since the CAN1 does not have the Enhanced Fifo feature and we are using the FD protocol at the same time. 2.3.2. CanHardwareObject The next step is configuring the Can Hardware Objects inside the CanHardwareObect tab, still under the CanConfigSet menu. Working in a similar manner to the previous subchapter, we will focus on the explaining the options that you can expect to use. First of all, as a general rule, the RX objects should be placed before the TX objects in the list of objects. So there shouldn’t be any RX object with an ID that is higher or equal to the lowest TX object’s ID. The Name field controls the name associated to the hardware object that is displayed inside MBDT blocks. The Can ID Message Type controls whether the can message’s ID type is Extended, Mixed or Standard. Can Object ID acts as an identifier for the hardware objects. It starts with 0 and should continue without any gaps. Can Object Type controls whether the hardware object will be used to receive or transmit CAN messages. Can Controller Reference selects which Can Controller this object is configured for. Can Hw Object Count defines the number of elements in the hardware FIFO. The CanHwFilter is used for filtering messages. The Can Hw Filter Mask determines which part of the filter is active. The decimal number 536870911 converted to binary is 11111111111111111111111111111 (29 digits). This means that the mask enables the entire filter, since the extended ID format has 29 bits. The Can Hw Filter Code is the ID that the message would be compared to, based on the filter mask. Let’s look at the example in the image: Filter Code:  00000000000000000001111110000 (1008 in decimal) Filter Mask:  11111111111111111111111111111 Allowed IDs: 00000000000000000001111110000 (1008 in decimal) This means that the filter only allows messages coming from the extended ID 1008. If you want the filter to allow more than one value, you have to modify the filter mask in such a way that the filter does not check if every bit is equal to the filter code. Another example: Filter Code:  00000000000000000001111110000 (1008 in decimal) Filter Mask:  11111111111111111111111111110 Allowed IDs: 00000000000000000001111110000,                      00000000000000000001111110001 (1008 and 1009 in decimal) In this case, the filter mask allows the last bit to be different from the filter code. Since the Can Hardware Objects that already exist are properly configured for the CanController_0, we do not have to perform any changes. But, for the CAN1 to be able to communicate with the CAN0 instance, we have to add a TX (Transmit) hardware object for it. To do that, click on the highlighted + Button and then configure the object accordingly. As an alternative, you could copy the configuration from CanHardwareObject_Can0_Tx_Interrupt and simply change the fields that are relevant to the CAN1. This means changing the Name to reflect the correct controller, updating the Can Object ID, making sure that the Can Object Type is set to TRANSMIT, and changing the Can Controller Reference to point towards the CanController1. After finishing these configuration steps, the CAN0 would be set up to both receive and send messages, while the CAN1 is configured to only send messages. 2.4. CanIf Configuration The CAN Interface is found between the low-level CAN drivers and the upper communication service layers from the AUTOSAR stack. It provides a way to interact with different CAN Hardware device types like CAN Transceivers and CAN Controllers. Next, the newly created Can Controller (for the CAN1) has to be added to the CanInterface, in the CanIfCtrlCfg section, inside the CanIfCtrlDrvCfg menu. To add a new CanIfCtrlCfg element, press the + button, and then you have to update the CanIfCtrlId field and choose the right Can Controller for the CanIfCtrlCanCtrlRef.   2.5. Clocks Configuration (MCU) In order for the CAN instances to work properly, their clock has to be enabled in the McuModeSettingsConf tab, under McuModuleConfiguration, in the Mcu component. Once on this page, you have to scroll down and verify that the Clocks corresponding to your FlexCAN instances are enabled. By default, they are enabled in this current configuration, but it is important to remember that the CAN peripherals require to have their clocks. To change the reference clock, CanCpuClockRef, for a set of Can Controllers, you can find them in the McuClockSettingsConfig > McuClockReferencePoint.   2.6. Interrupts Configuration (Platform) The last step in the Configuration Tool is to set up the Interrupts for the CAN instances that we are using in this model so that we can use Interrupt-based blocks. To do that, head to the Platform component, by clicking the Platform button on the left of the Peripherals Tool. Afterwards, we have to navigate to the Interrupt Controller tab, where we can see all the interrupts that are currently configured. To configure the CAN instances, scroll down until you see the FlexCAN instances that you are configuring. In this article we use the CAN0 and CAN1 instances, so we are configuring these two instances. When it comes to FlexCAN interrupts, the FlexCAN0_0 contains 9 general interrupt requests, while the FlexCAN0_1 – FlexCAN0_3 instances contain 96 message buffer interrupts. More details about the interrupt mappings can be found inside the reference manual, S32K3XXRM, by consulting the attached file called S32K3xx_interrupt_map.xlsx. As you can see, one of them is already configured, so we only have to configure the FlexCAN1 instance as follows:   2.7. Dio Configuration The Input/Output pins configured previously also have to be configured in the Dio component, similarly to chapter 2.3. from the first article, Interacting with Digital Inputs/Outputs on MR-CANHUBK344. Now, inside the Dio component, we are configuring the input/output pins that will be used later in the model to enable the transceivers. Briefly going over the process, we have to remove the default pins that do not match the configuration we are working on. In this situation, it means removing the CanController_0_EN, CanController_0_STB and CanController_0_ERRN channels from the DioPort PTC_H. Afterwards, we add the Input/Output pins configured previously.   2.8. Uart, FreeMASTER, Adc and Pwm Configuration This article’s application involves using the Adc and Pwm components, as well as the FreeMASTER functionality, the way they were configured in the previous articles. For details on how to configure Uart and FreeMASTER, please refer to the second article, Sending data via UART and monitoring signals with FreeMASTER. As for the Adc and Pwm configurations, you can find step-by-step instructions in the third article of this series, Controlling LED intensity with ADC and PWM. For these components, there is no difference from the setups described in the referenced articles.   3. CAN Model Overview This article’s application aims to incorporate the previous components into a single example. This application consists of gathering data from two inputs, the ADC potentiometer and the USER_SW2 button, processing it, packaging it and sending it across the CAN Bus, so that it can be received by the other CAN instance and then control two outputs. The two outputs are a Blue LED that turns on according to the USER_SW2 button presses, and a Red LED whose intensity varies based on the rotation from the potentiometer. The following diagram aims to provide a better understanding for the flow of this application: Now, let’s break down the model into smaller pieces. Starting from the top left, the model uses a few variables. These have been grouped based on their purpose. For example, the Channel1 variable from the ADC is responsible for holding the value read from the ADC. Similarly, in the case of the CAN instances, the variables Data and Length represent the message that has been received across the CAN Bus. The last panel is the most important one, representing the values of the Dio and Aio peripherals right after the CAN message has been unpacked. Moving on to the Initializations section, this is where we perform the operations needed to prepare the components. In this specific case, we initialize the 2 CAN transceivers by setting 2 of their inputs to HIGH. In the initialization subsystem, a result buffer is set for the ADC conversion and the group notifications are enabled, so the configured ADC callback would be executed when the conversion on the group finishes. Finally, we turn the LEDs of the board off since this board uses inverted logic for the LEDs, which means they would normally turn on along with the board. The FreeMASTER Config block is used for enabling FreeMASTER functionality for this project. Moving on, there’s one more block to talk about before explaining the active parts of the model, which executes each step and which starts the group conversion for the ADC. Once the conversion is done, the hardware interrupt for the ADC will be triggered and the subsystem linked to the hardware interrupt callback block will output the ADC signal. The conversion to single data type takes place because the CAN Pack block is configured to accept a floating-point number which represents a voltage between 0V and 3.3V, corresponding to how much the potentiometer is turned. As specified, we start by collecting data from the inputs, the Aio and Dio. In the case of the Aio, we scale the value to represent the voltage read by the ADC. To be able to package the data and interpret it after the transfer, we are using a DBC file. DBC is a CAN Database file, which describes what kind of signals will be stored and sent through the CAN message. Afterwards, the data is then sent to a VNT packing block (VNT stands for Vehicle Network Toolbox TM ). By opening the CAN PACK block, we can see that the signals configured in the DBC file have been parsed properly and the block now expects them as an input. The ADC value will be a 32-bit variable, representing a voltage between 0V-3.3V, while the Dio variable will only have 1 bit, representing whether or not the button is pressed. In total, the variables take up 5 bytes, which becomes the length of the message. The next block, CAN Unpack, is used to extract the raw data from the CAN Frame, since that’s what will be sent by the CAN Transmission block. Can_Write is one of the available functions for the Can block and as the name suggests, it’s responsible for sending the CAN Message across the CAN Bus. The second dropdown item allows the user to select which CanHardwareObject will be sending the data. The items that appear here are the items configured as TRANSMIT in the menu seen in section 2.3.2. In this application, the data is being sent using an interrupt-based hardware object. The CAN FD Message checkbox selects whether the message being sent is using the CAN FD protocol and the Extended ID CAN Message selects the format for the ID. These should reflect the settings done in the configuration software. The second half of the application start with the CAN0 receiving the message sent by the CAN1. One important thing to note about how this works is that receiving the message is based on the CanIf_RxIndication, which triggers the Hardware Interrupt Callback. Afterwards, we can access the data. In the Hardware_Interrupt_Handler block, after selecting Can as the Interrupt Group, the following list of Can-related callbacks is made available. This application requires the ability to read incoming CAN Messages, so the CanIf_RxIndication is used for that purpose. CanIf_RxIndication is a callback which has an interrupt-based execution, being called whenever a CAN frame is received. Before obtaining the actual values from inside the CAN Message, we have to, once again, use the CAN Pack and Unpack blocks to extract the data and decode it according to the DBC file. Now that we have the values, we use the ADC value to proportionally change the brightness of the Red LED, and we use the value of the DIO to turn on or off the Blue LED. To validate the model, we can use the FreeMASTER tool to read and graph the values. As we can see, the received message is made up of 5 bytes of data, which represent the Adc Value and the Dio Value. Below you can see the variables' representaton on a graph made in real time in the FreeMASTER software. The red signal represents the value read from the potentiometer, situated between 0V and 3.3V. The blue signal corresponds to the state of the button: if the button is pressed, the blue signal will be equal to 1; otherwise the signal will be 0. On the bottom of the window, you can see the values of the signals at the time the screen capture happened. Apart from the ADC_Received and Dio_Received variables, which correspond to the red and blue signals from the graph, the other variables provide details about the last CAN message received.  By connecting the device capable of reading CAN messages, we can also see  them being transmitted through the CAN Bus. Here we use the PCAN-View software application to show the messages captured by the PCAN-USB Pro FD.     4. Conclusion After following the steps in the tutorial, you should now be able to include the MR-CANHUBK344 board into applications that require CAN Communications, either between the MR-CANHUBK344 board and a third party, or even between different CAN instances  from the same board. This article’s application also serves as an example on how to manage the workflow of adding multiple MBDT components into a single model.     Instructions on how to run the attached model: Download and extract the archive’s contents; Copy both the .mdl and .mex file to the location where you wish to set up the project; Note: for the model to work properly, please place the .mex and .dbc files next to the model. Open the .mdl file and make sure that MATLAB’s Current Folder points to the folder that contains the model; Click on the Hardware tab and then press the “Build, Deploy & Start” button.   Simulink is a registered trademark and Vehicle Network Toolbox is a trademark of The MathWorks, Inc. See mathworks.com/trademarks for a list of additional trademarks.
記事全体を表示
1. Introduction 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.
記事全体を表示
  Product Release Announcement Automotive Processing NXP Model-Based Design Toolbox for S32K3xx – version 1.4.0 RFP   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.4.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 S32K310, S32K311, S32K312, S32K314, S32K322, S32K324, S32K328, S32K338, S32K341, S32K342, S32K344, S32K348, S32K358 and S32K396 MCUs and part of their peripherals, based on RTD MCAL components (ADC, PWM, MCL, DIO, CAN, SPI, UART, LIN, GPT). To enable BMS applications development, the toolbox offers support for MC33775A and MC33772C battery cell controllers (& MC33665PHY). In this release, we have also updated RTD, AMMCLib, and MATLAB support for the latest versions. The product comes with over 120 examples, covering everything that is supported, including demos for battery cell controllers (BCC) and motor control.   Target audience: This product is part of the Automotive SW – S32K3 Standard Software Package.   FlexNet Location: https://nxp.flexnetoperations.com/control/frse/download?element=14146527   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: S32K310 S32K311 S32K312 S32K314 S32K322 S32K324 S32K328 S32K338 S32K341 S32K342 S32K344 S32K348 S32K358 S32K396   Support for the following peripherals (MCAL components): ADC PWM MCL LIN CAN SPI UART GPT DIO   Board initialization: The Model-Based Design Toolbox for S32K3xx generates the component’s peripherals initialization function calls as configured in the Board Initialization window. The toolbox provides a default configuration including function calls for initializing the clocks, followed by pins and a custom order for the rest of the peripherals which have been configured in the project associated to the model. Moreover, the toolbox provides the option to save and export the initialization sequence to a file which can be later used for other models as well – in this way, the customization of the board initialization sequence can be done only once, even if applicable for other models as well. Such a file can be then imported as an external Board Initialization Template.   Custom Linker Files and Startup Code: The toolbox allows the selection of custom linker files and startup code to be used during the build process. By enabling the Use Custom Linker or/and Use Custom Startup Code checkboxes, this feature is activated, allowing the users to Browse for specific files.   Support for Referenced Configurations The Model-Based Design Toolbox for S32K3xx enables the usage of Referenced Configurations, a Simulink feature which allows users to share the configuration of an application with multiple models.   Support for MC33775A and MC33772C battery cell controllers & MC33665PHY The toolbox provides support for the MC33775A, MC33772C, and MC33665. The MC33775A and MC33772C are lithium-ion battery cell controller ICs designed for automotive applications which perform ADC conversions of the differential cell voltages and battery temperatures, while the MC33665 is a transceiver physical layer transformer driver, designed to interface the microcontroller with the battery cell controllers through a high-speed isolated communication network. The ready-to-run examples provided with the MBDT for S32K3 show how to communicate between the S32K344 and the MC33775A and MC33772C via the MC33665 transceiver. For the MC33775A, the examples show how to configure the battery cell controller to perform Primary and Secondary chains conversion, and read the cell voltages conversion results from the MC33775A, while for the MC33772C the examples show how to configure the Battery cell controller to read current. All the converted values are displayed to the user over the FreeMaster application.       Support for AUTOSAR blockset (SW-C deployment) New RTD version supported  (3.0.0) Provides 2 modes of operation: Basic – using pre-configured configurations for peripherals; useful for quick hardware evaluation and testing Advanced – using S32 Configuration Tools or EB Tresos to configure peripherals/pins/clocks Integrates the Automotive Math and Motor Control Library release 1.1.32: All functions in the Automotive Math and Motor Control Functions Library v1.1.32 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: R2021a R2021b R2022a R2022b R2023a   S32Design Studio Integration We provide a simple mechanism for the users to export the code generated 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 or for debugging purposes.   Support for custom default project configuration The toolbox provides support for users to create their custom default project configurations. This could be very useful when having a custom board design – only needing to create the configuration for it once. After it is saved as a custom default project, it can be used for every model that is being developed.   Support for component restore to default settings The toolbox allows users to restore the configuration of a component (for models which use the EB Tresos configuration tool) to the settings corresponding to the Default Configuration Template the model uses. This allows reverting changes (if made) to the default values.   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 120 examples, including: Battery Management Systems examples Motor control applications (including eTPU example on S32K396) Communication (LIN, SPI, CAN, UART) AMMCLib Timer control (GPT) DIO FreeMASTER SIL / PIL / External mode For more details, features, and how to use the new functionalities, please refer to the Release Notes document attached. MATLAB® Integration The NXP Model-Based Design Toolbox extends the MATLAB® and Simulink® experience by allowing customers to evaluate and use NXP’s S32K3xx MCUs and evaluation board solutions out-of-the-box with: NXP Model-Based Design Toolbox for S32K3xx 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 S32K3xx MCUs and Evaluation Boards.   Useful Resources Examples, Trainings, and Support: https://community.nxp.com/community/mbdt          
記事全体を表示