S12 / MagniV Microcontrollers Knowledge Base

cancel
Showing results for 
Search instead for 
Did you mean: 

S12 / MagniV Microcontrollers Knowledge Base

Labels

Discussions

Sort by:
S12(X) MCU Secure: There’s a security byte in the flash memory at address 0xFF0F that should be programmed appropriately. Datasheet says: “The contents of the Flash Protection/Options byte at $FF0F in the Flash Protection/Options Field must be changed directly by programming $FF0F when the device is unsecured and the higher address sector is unprotected. If the Flash Protection/Options byte is left in the secure state, any reset will cause the MCU to return to the secure operating mode.”   If you use CodeWarrior then you can use the syntax as follows: const unsigned char secure @0xFF0F = 0xFC;   If the security is enabled then: - internal flash memory cannot be read via BDM device. - debug features are disabled. For more information see the description of FSEC register in datasheet.   I would like also recommend our application note AN2400 HCS12 NVM Guidelines: http://www.freescale.com/files/microcontrollers/doc/app_note/AN2400.pdf AN2880 Using the Backdoor Access Capability to Unsecure HCS12 MCUs: http://www.freescale.com/files/microcontrollers/doc/app_note/AN2880.pdf http://www.freescale.com/webapp/sps/download/license.jsp?colCode=AN2880SW     Security at S12(X) MCUs with 180nm Flash: This is related to all S12(X) MCUs with 180nm Flash with ECC (S12G, S12HY, S12P, S12XE, S12XF, S12XHY,  S12XS, MM912G634, MM912H634, MM912J637 and S12VR):   If we load the flash security byte together with other code, ****************** c code example: //set backdoor key and secure the flash (set flash security byte to 0xBD): const unsigned char flash_array[] @0xFF00 = {0xAA,0xAA,0xAA,0xAA,0xAA,0xAA,0xAA,0xAA,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xBD}; ****************** then we have to add following command to preload command file (P&E_Multilink_USB_Preload.cmd if you use PE Multilink):   FLASH NOUNSECURE   This command will ensure that the burner will not change security byte to unsecured state prior to programming. That's normal way: the MCU is erased, flash security byte is programmed to default unsecure state (0xFE) and then the code is loaded. We just have to turn off the programming of security byte.   Why: The cumulative bits within the phrase is not allowed. If the flash security byte at address 0xFF0F is not erased prior to programming of the new value then the ECC checksum of this phrase is corrupted and the MCU will be left in secured state and the flash will be fully protected after next reset.   Datasheet says: "If a double bit fault is detected while reading the P-Flash phrase containing the P-Flash protection byte during the reset sequence, the FPOPEN bit will be cleared and remaining bits in the FPROT register will be set to leave the P-Flash memory fully protected."   "If a double bit fault is detected while reading the P-Flash phrase containing the Flash security byte during the reset sequence, all bits in the FSEC register will be set to leave the Flash module in a secured state with backdoor key access disabled."   The same for D-Flash...   S12(X) unsecure: Unsecure is possible by three ways: 1. Backdoor key access(temporary) 2. Reprogramming the security bits 3. Complete memory erase (special modes) Ad1) For secure and backdoor key you set 16bytes on address 0xFF00. The backdoor key access method allows debugging of a secured microcontroller without having to erase the Flash. This is particularly useful for failure analysis. For unsecure by backdoor key you use special flash command 0C (caption Verify Backdoor Access Key Command in reference manual). No word of the backdoor key is allowed to have the value 0x0000 or 0xFFFF. Unsecure is valid only till reset. If an invalid attempt is made to verify the Backdoor Keys the command will be locked out until a power down occurs.  Ad2) In normal single chip mode (NS), security can also be disabled by erasing and reprogramming the security bits within Flash options/security byte to the unsecured value. Because the erase operation will erase the entire sector from 0xFE00–0xFFFF, the backdoor key and the interrupt vectors will also be erased; this method is not recommended for normal single chip mode. Ad3) Complete mass erase by BDM device(in special mode). In Code Warior debugger menu ->MultilinkCyclonePro->Unsecure… If not work you can use unsecure12 from P&E: http://www.pemicro.com/downloads/download_file.cfm?download_id=16 Unsecure_12 Help Files: http://www.pemicro.com/downloads/download_file.cfm?download_id=14 Note: For downloading is necessary registration.
View full article
I've just went through my PC and put some examples here. ( I made them "a few" days ago.) The files are presented with extension BMP because of some firewals.   AN3490.pdf DOC-XEP100-MMC-Memory_Map-Common_Map-V5_0-MSExcel.xls EEE.xls TN263-CodeWarrior IDE.pdf XEP100 - EEPROM Direct Access - CW45.zip XEP100 - Initial data in Emulated EEPROM - CW47.zip XEP100 - MPU - CW47.ZIP XEP100 - RAM addressing - CW45.zip XEP100 - SCI - XonXoff_poll - CW47.zip XEP100 - Security + Backdoor Key Access - CW47.zip XEP100-ATD wakes up from STOP - CW47.zip XEP100-ATD-ATDandXGATEandSharedRAM-CW50.zip XEP100-ATD-CH1toCH4-CW47.ZIP XEP100-ATD-CH1toCH8-CW47.ZIP XEP100-ATD-Cntnuos_SingleCh-v1_0-CW47_Data.zip XEP100-ATD-Tmprture_bandgapV-v1_0-CW47_Data.zip XEP100-BDM-BDMcommExample-CW50.zip XEP100-BufferRAMasOneArray-CW51.zip XEP100-BufferRAMasRAMonly-CW51.zip XEP100-CAN-CAN0-RxTxIsrLoopback-CW47.zip XEP100-CAN-CAN0-TxAtXGATE-CW51.zip XEP100-CAN-CAN0CAN1 - CW45.ZIP XEP100-CAN-CAN2CAN2-Identifiers SandX-loopback-CW51.zip XEP100-CAN-CAN2CAN3-CW47.ZIP XEP100-CAN-CAN2CAN3-FILTER-CW51.ZIP XEP100-CAN-CAN2CAN3-Identifiers SandX-CW51.zip XEP100-CAN-LoopbackInterrupt-CW51.zip XEP100-CAN.ZIP XEP100-CAN0 - CAN1 - CW45.ZIP XEP100-CAN0-RxTxIsrLoopback-CW47.zip XEP100-CAN0-RxTxIsrLoopbackXGATE-CW51.zip XEP100-CAN0-TxAtXGATE-CW51.zip XEP100-CRG-COP-CW47.ZIP XEP100-CRG-PLL-Setup-CW47.zip XEP100-EBI-MRAM256x16-CS0-CW51.zip XEP100-EBI-MRAM256x16-CS2-CW51.zip XEP100-ECT-ECTasPWM-CW47.zip XEP100-ECT-FreqMeasurement-CW51.zip XEP100-ECT-InputCapture-CW51.zip XEP100-ECT-TIM.ZIP XEP100-EEEPROM-Addressing-Lukas-CW46.zip XEP100-EEEPROM-DataPlacement-CW51.zip XEP100-EEEPROM-plusMPU-CW51.zip XEP100-EEPROM-DirectAccess-CW51.zip XEP100-EXBUS-EXRAM256x16-CS1-CW47.zip XEP100-EXBUS-ExRam_MR2A16ACYS35-CS1-CW51.ZIP XEP100-FLASH-PFLASH-CW47.ZIP XEP100-FLASH-PFLASH-CW51.ZIP XEP100-FLASH-PFLASH-PFlashInitData.zip XEP100-FLASH-PFLASH_reading-CW47.zip XEP100-GPIO-PJ2isr-CW47.zip XEP100-GPIO-PortPisrXgate-CW51.zip XEP100-ID-readPartID-CW47.zip XEP100-IIC-Master4Flash24C16-CW51.zip XEP100-INT-INTERRUPTNUMBER-CW51.ZIP XEP100-INT-TRAPPROC-CW51.ZIP XEP100-MDDC-delay generator-v1_0-CW47.zip XEP100-MPU-MPU-CW47.ZIP XEP100-PFLASH-CW47.ZIP XEP100-PFLASH-CW51.ZIP XEP100-PIM-PTPfunctions1-CW47.zip XEP100-PIT-FLOATING PERIOD-CW51.ZIP XEP100-PIT-SERIAL_DATA_OUT-CW45.ZIP XEP100-PIT-XGATE-SEMAPHORES-CW51.ZIP XEP100-PWM-dutyatXGATE-CW47.zip XEP100-RAM-addressing-v1_0-CW51.zip XEP100-RAM-RAMaddressing-CW45.zip XEP100-SCI_PIT-CW47.zip XEP100-SCI-ECHO-isr.zip XEP100-SCI-ECHOatCPU-CW47.zip XEP100-SCI-ECHOatCPUisr-CW47.zip XEP100-SCI-ECHOatXGATEisr-CW47.zip XEP100-SCI-Sci0transmitterOnXGATE-CW45.zip XEP100-SCI-SciTx-CW45.zip XEP100-SCI-SCI_PIT-CW47.zip XEP100-SCI-XonXoff_poll-CW47.zip XEP100-SciTx-CW45.zip XEP100-SECURITY-BackdoorKeyAccess-CW47.zip XEP100-STOP-ATDwakesUp-CW47.zip XEP100-STOP-RTIwakesUp-CW51.zip XEP100-STOP-WakeUp-CW47.zip XEP100-STOP_and_ API_and_PLL-CW47.zip XEP100-STOP_and_XIRQ_and_PLL-CW47.zip XEP100-TIM-10msIsr-CW47.zip XEP100-TIM-FreqMeasurement-CW51.zip XEP100-UnionInPages.zip XEP100-UnionInPagesAndECT.zip XEP100-XGATE-SharedVars-CW51.zip XEP100PWM-PWM8bit-CW45.zip XEP100_SPI_master_w_25AA256.zip XEQ384EXBUS-EXRAM256x16-CS2-4000-7FFF-CW47.zip XEQ512-PWM-10kHz8bit100point-CW51.zip XEQ512-RAM-addressing-v1_0-CW51.zip XEQ512-SWtrigger-CPU_XGATE-CW47.zip XET256-ECT-asPWM-CW47.zip XET256-ECT-OC-CW47.ZIP XET256-EXBUS-ExROM2ExRAM-CW46.zip XET256-RTI-RTIdec and COP-v1_0-CW47.zip XET256-SCI-Tx_Poll-CW51.zip XF256-SCI-ECHOatCPUisr-CW47.zip XF256-SCI-ECHOatXGATEisr-CW47.zip XF256-SCI-ECHOatXGATEisr-CW47.zip
View full article
The DEVKIT platform The NXP released new board platform for automotive products – DEVKIT. The DEVKIT is a low-cost development platform with Arduino UNO/Mega pin compatibility. In my review, I will focus mainly on DEVKIT-ZVL128 board.                                          The DEVKIT boards are similar to FRDM boards, but they are slightly wider (58mm versus 53mm) due to moving MCU specific pins to external rows of Arduino pin compatible connectors. So, we should be able to access MCU specific pins even when we connect any Arduino shield on top of this board.     The other currently or soon available DEVKIT boards are: DEVKIT-S12ZVL DEVKIT-S12ZVC DEVKIT-S12G128 DEVKIT-S12XE DEVKIT-S12VR64 DEVKIT-MPC5748G DEVKIT-MPC5744P FRDM-KEA128 FRDM-KEA64 FRDM-KEA32 DEVKIT-COMM - 6 LIN and 4 CAN transceivers shield DEVKIT-MOTORGD – three-phase motor control shield with GD3000 N-channel MOSFETs driver and power stage Note: The FRDM-KEA boards belongs also into the DEVKIT platform despite on the “FRDM” in the board name.     The Content What you will get for US$35 (current price on NXP web pages): Antistatic paper box DEVKIT-ZVL128 board short micro-USB cable       The sticker on the box points to the NXP web pages for downloading more documents such as the quick start guide, schematic, PCB BOM and design files, code examples or buy the same board again ;-). Unfortunately, the board User Guide is not available yet.   This web page is also offering “Getting Started” tab with the interactive quick start guide – quite useless feature since the page forgets on necessary 12V power supply for MCU powering and it proposes old CW5.1 (Classic IDE) for S12(X) instead of CW10 (Eclipse IDE).   What else you will need: The IDE – for example, the NXP CodeWarrior or Cosmic ZAP 12V DC power supply (3.8V~40V) with barrel connector (6mm outside diameter x 2mm inside diameter) MCU code   The Board DEVKIT-ZVL128 board is assembled by: S12ZVLA128 MCU (Big Knox) in 48-pin LQFP package 8MHz crystal Standard 2mm DC power jack connector for 12V power supply On-board OSBDM debugger trough micro-USB connector Standard BDM connector Arduino UNO pin compatible connectors with extended connectivity (the internal rows of the connectors are arranged to fulfill Arduino™ shields compatibility) RGB LED and 2 x push button switches LIN and CAN connectors CAN transceiver MC33901 5k potentiometer and RESET switch 3V/150mA and 5V/150mA LDO voltage regulators     The great thing is that the board has connector pins named from the bottom side of the PCB = less tracking on schematic.     On another side, some of the MCU pins may be routed to Arduino connectors trough zero Ohm resistors. Since these resistors are very small (size 0402), the potential re-routing will need a solid hand.     It is great that loop type test points arrived finally also on low-cost development boards – now in surface mount version. The small loops may be simply locked by test hooks and measured by laboratory equipment.       The MCU The S12ZVLA128 is one of MagniV family MCUs using the 180nm NVM + UHV technology that offers the capability to integrate 40V analog components. It integrates S12Z core, features from the existing S12 portfolio together with “high-voltage” analog modules, including the voltage regulator (VREG) and a Local Interconnect Network (LIN) physical layer (LIN PHY). The S12ZVL(A)128/96/64 derivatives introduces several unique enhancements in comparison with older S12ZVL32/S12ZVL16 derivatives: Significantly bigger memories (64/96/128kB flash, 1/2kB EEPROM, and 4/8kB RAM) The VDDX voltage regulator is capable of providing 5V or 3.3V MsCAN module The S12ZVLA derivatives additional features/improvements: 2% VDDX regulator tolerance improvements 10/6 channel 12bit ADC 8bit DAC module the rail-to-rail analog comparator (ACMP) the Programmable Gain Amplifier (PGA) I am going to use the PGA for thermocouple measurement in the near future.   Software The Software Integration Guide guides us through CW 10.6.4 installation and creating a new project with Processor Expert (PE) tool. Unfortunately, while following that guide, I discovered that the CW10.6.4 does not offer PE as an option (only project without PE) when I tried to create an S12ZVL128 project. But this option is available in newer CW10.7 version. Note: If S12ZVL(A)128 derivative is missing in your CW10.6.4 IDE, please update your CW IDE via menu-Help-Install New Software-FSL MCU Eclipse Update Site and focus mainly on “S12Z Support” and “MCU 10.6.4 Updates” folders.   The code examples contains three primitive example projects: DEVKIT-ZVL128_Lab1GPIO – configure GPIO pins DEVKIT-ZVL128_Lab2ADC – initialize and measure ADC value DEVKIT-ZVL128_Lab3PWM – configure voltage regulator, initialize CLOCK, initialize and measure ADC value, generate PWM   Note: The zip file contains already built projects. The loading it into MCU does not work due to different paths. We have to clean it and build again in our workspace prior loading into the MCU.   These projects are really simple, but they omit some specific potential issues. For example: I would like to recommend to configure CPMUVREGCTL_VREG5VEN bit also in GPIO example since this bit influences output pin voltage levels. The value of the CPMUVREGCTL_VREG5VEN bit is not influenced by any MCU reset. So, we have to be careful especially when we are starting a new project with new peripherals connected to the S12ZVL128 GPIO pins. The ADC command lists (adc0_cmdlist) and ADC result lists (adc0_results) are not aligned in these example codes. It may be fixed by simple modification: volatile unsigned char adc0_cmdlist[1][4] __attribute__ ((aligned (4))) = {0xC0,0xD0,0xA0,0x00}; volatile unsigned short adc0_results[1] __attribute__ ((aligned (4)));‍‍‍‍ The NXP offers for this MCU also LIN2.x and SAE J2602 Stack and S12Z NVM Standard Software Driver (Flash/EEPROM driver).   There are also well-documented example codes at Community from Technical support team which may be used for an inspiration. For example: S12ZVM clock module and PLL configuration - SW examples S12Z Interrupt catcher for unexpected interrupts S12Z voltage measurement A Library of Functions for HD44780 Based LCD Modules (no R/W) for S12Z devices S12ZVL-TIM-FrequencyMeasurement S12Z Flash example code S12Z EEPROM example code …   The next source of information may be NXP application notes. For example: AN4723 S12Z MagniV Bootloader with SW, AN4731 Understanding Injection Current on Freescale Automotive Microcontrollers, AN4841 S12ZVL LIN Enabled Ultrasonic Distance Measurement with SW, AN4842 S12ZVL LIN Enabled RGB LED Lighting Application with SW, AN5084 Hardware Design Guidelines for S12ZVL Microcontrollers, AN5122 Using Freescale’s LIN Driver with the MagniV Family with SW   Summary One of the best advantages of DEVKIT platform is the price. When we compare DEVKIT board prices with alternative evaluation boards (if any exist), we may save between 40 and 95 % EVB price depending on target MCU family. For example, the older TRK-S12ZVL board (assembled by S12ZVL32) is bigger, additionally offers 9 user switches, buzzer, HVI potentiometer, switchable LIN_OUT connector and header ring with all MCU pins. But the price is also almost three times higher than the price of DEVKIT-ZVL128. Also, the connectors with standard 100mils pitch are definitely plus in comparison with previously used TWRPI/PCI EXPRESS connectors and the board allows using plenty of available Arduino shields without complex hardware interconnections. You may look for it for example at Arduino pages, shieldlist.org, Adafruit, …   From my side - thumbs up :smileycheck:.
View full article
The example code demonstrates MCU low power modes: STOP and WAIT. For detailed description see main.c file of the project. * - tested on X-VLG-S12ZVC board * - BUSCLK = 6.25MHz based on internal oscillator clock IRCCLK = 1MHz.The PLL set by default in PEI mode. * - Reference documentation: MC9S12ZVCRMV1.pdf (REV 1.9) VLG-MC9S12ZVC-SCH.pdf (Document Number SCH-28038, SPF-28038)
View full article
The bold blue links below provide direct download of SW example packs for MagniV devices based on S12Z core.   S12ZVC Getting Started Exercises (REV 1.0) This file contains four hands-on exercise where you can find basic setup code to enable a quick development in different areas. The file includes CodeWarrior projects demonstrating usage of peripheral modules such as: - Digital-to-Analog Converter (DAC), - Controller Area Network (CAN), - Pulse Width Modulation (PWM), - Timer (TIM).   Getting started with S12ZVL32 - S12 MagniV Example Codes (REV 0) The MC9S12ZVC device integrates a battery level (12V) voltage regulator and supply voltage monitoring. This zipped file includes four CodeWarrior examples demonstrating - Overcurrent protection on EVDD pin, - low power STOP mode with API timer and wake-up feature, - Pulse Width Modulation (PWM) - Serial Peripheral Interface (SPI) communication.   Many of these examples can be used on various MCU families across the MagniV product line. Check the appropriate device guide for list of modules and its versions.
View full article
This example shows a few possible configurations of the S12PWM8B8CV2 PWM module. Five PWM channels are configured with different clock source, polarity, alignment, period and duty-cycle.   Four clock sources (A, B, SA, SB) are derived from bus clock using dividers.   Selected polarity of PWM channel determines the duty-cycle whereas the alignment determines the period of the PWM signal.   Four 8-bit channels (4-5, 6-7) are concatenated into two 16-bit channels. Channels 4 and 6 become high-order channels while channels 5 and 7 become low-order channels. These low-order channels (5 and 7) are the output channels routed to a port  and they configure the clock, polarity, alignment and enablement of the PWM signal.  Period and duty-cycle of the signal are configured with both the low-order and high-order channels.   The period registers (PWMPERx) and the duty-cycle registers (PWMDTYx) are double buffered. When they are rewritten while the channel is enabled, the change will not take effect until one of the following occurs: 1. The effective period ends 2. Counter resets 3. The channel is disabled
View full article
In the attached zip file you can find three software examples demonstrating clock module and PLL configuration on MagniV device MC9S12ZVM. The examples are made in CodeWarrior IDE v10.6 (Eclipse). The main.c source file of each project provides detailed description, comments and important notes.   The source code can be used with other devices within MagniV family based on S12Z core such as S12ZVL, S12ZVC, S12ZVH/Y, but the precaution must be considered about the max bus frequency of the device.   p.s. Revision 2: SYNR, REFDIV and POSTDIV values changed in PLL initialization to achieve highest PLL locking time.
View full article
The ADC measurement is always relative – relative to your voltage reference. The most of the applications don't allow to use accurate and expensive voltage reference. In that case, VDDA is used as the reference for ADC measurement. Since the operational VSUP range starts from 3.5V and accuracy of the voltage regulator is limited, we should use internal bandgap reference for compensating ADC voltage results. The bandgap voltage VBG has a narrow variation over temperature and external voltage supply. The example shows how to compensate ADC results by additional bandgap voltage measurement.
View full article
Hello all, sharing the latest version of MagniV Power Dissipation Calculator started by Carlos Vazquez and Anita Maliverney. With this excel sheet is possible estimate the power dissipated for any MCU of S12ZVM, S12ZVL, S12ZC family, considering: supply voltages, digital modules, gate drive unit, charge pump, communication transceivers, etc.   A few features where added, any additional comment or suggestion is appreciated. Regards.
View full article
Have you ever wondered what is the difference between the electric motors included in those two Development Kit with S12 MagniV?     MTRCKTSBNZVM128: 3-phase Sensorless BLDC Development Kit with S12 MagniV S12ZVM MTRCKTSPNZVM128: 3-phase Sensorless PMSM Development Kit with S12 MagniV MC9S12ZVML128 MCU   Well frankly writing none. They include the same motor model 45ZWN24-90       . So the motors are same from physics perspective, only the flux distribution in an air gap is different. It is sinusoidal for PMSM whereas it is trapezoidal for BLDC motor. The powerstage is same for both but what is different however is the control strategy. The Linix motor equipped with the DevKits is in fact somewhere between PMSM and BLDC, The flux is not sinusoidal nor trapezoidal.   Further information and motor parameters can be found at manufacturer product pages:                          http://www.linixmotor.com/3-3-Tool-Motor.html
View full article
The package contains of AN5327_SW ported to S12ZVML-MINIBRD hardware. Just minor changes are introduced, such as removing a button control, moving the LED light to another pin and using internal oscillator. This is just a working version, it is NOT an official release!!! AN5327_SW_CW11_MINIBRD.ZIP CodeWarrior 11.0 and AMMCLib 1.1.13 or higher is required to run this example. If you are not sure about the AMMCLib version, please download the general AN5327_SW from the www.nxp.com/automcdevkits first, install it and then unzip and use the example above.
View full article
The S12Z MCU has linear address space therefore constant, variable, code placement is easier in compare with older S12 or S12X MCUs. But still, there are several ways and potential issues.   The object placement is made by Smart Linker. The linker configuration is defined by settings in project *.prm file and also by linker command line options (menu - Project – Properties – C/C++ Build – Settings – S12Z Linker). The detail information about linker options may be found in MCU_Build_Tools_Utilities.pdf with default path: "c:\Freescale\CW MCU v10.7\MCU\Help\PDF\MCU_Build_Tools_Utilities.pdf"   We may define memory segments in *.prm linker file. The default prm file contains segments for RAM, EEPROM, and ROM (Flash). The sizes of these segments typically reflect our MCU derivative physical memory map, but we may redefine that and use more virtual segments per our needs. The physical/virtual segments definition in prm linker file is located at: SEGMENTS // segments definition END‍‍‍ ‍ ‍ ‍   The general data placement may be divided into two main approaches: Manual – the programmer will specify fix address for some of the data Automatic – the placement will be driven automatically by Smart Linker   Manual placement The first option is an exact specification of specific content at a specific address. This may be managed for a small amount of data by FILL linker command in *.prm linker parameter file. For example: SEGMENTS //… ROM_CONST       = READ_ONLY   0xFE0000 TO 0xFE0000 FILL 0x5A ;   //insert 0x5A value at address 0xFE0000 //… END‍‍‍‍‍ ‍ ‍ ‍ ‍ ‍ Such placement isn’t very comfortable, but it might be simply used for some configuration data out of project code. Note: you may use more than one bytes (e.g. FILL 0x0A 0x34). If segment size is bigger than a number of specified bytes, the bytes will be used as a pattern for filling whole target segment. Note: The potential linker placement will overlap such defined data.   The next option is using address specification by an @ qualifier directly in C code. For example: unsigned const int rom_const @ 0xFE0100 = 0x5AA5 ; ‍ ‍ This may be used also for more complex types than simple byte – typically arrays,...   Since such type of placement is still manual, the linker parameters must be configured for avoiding possible overlapping. Be aware! The default CW project has disabled memory overlapping warnings. So, we must exclude target memory area from linker using. For example, in the *.prm file: SEGMENTS //… ROM_1           = READ_ONLY   0xFE0000 TO 0xFE00FF //ROM_CONST  = READ_ONLY   0xFE0100 TO 0xFE0101;            //we use the 0xFE0100 byte for rom_const ROM_2           = READ_ONLY   0xFE0102 TO 0xFFFDFF //… END‍‍‍‍‍‍‍ ‍ ‍ ‍ ‍ ‍ ‍ ‍ Note: We use qualifiers for define memory access type. READ_ONLY is used for Flash, READ_WRITE for RAM and NO_INIT for RAM where we do not want to initialize data after reset. Sections placed in an NO_INIT segment should not contain any initialized variables (variable defined as int c = 8).   Note: The manual placement may be also implemented by assembler code. For example: XDEF MyVariable MyVariable : equ $ 1100 ‍‍ ‍ ‍ However, also in this case, we must exclude target memory area from linker use like in the case of @ qualifier for avoiding memory overlapping.   Automatic placement by linker The PLACEMENT block allows us to physically place each section from the application in a specific memory area (segment). The sections specified in a PLACEMENT block may be linker-predefined sections (like DEFAULT_ROM, DEFAULT_RAM, COPY, SSTACK,…) or user sections specified in one of the source file building the application (like MY_RAM,…). PLACEMENT // section(s) INTO segment(s); MY_CODE INTO ROM_1 ; END‍‍‍‍ ‍ ‍ ‍ ‍ Note: Since the linker is case sensitive, the name of the section names specified in the PLACEMENT block must be valid predefined or user-defined section names. Note: There is quite mess in ELF/Freescale section/segment terminology. Please take this information as simplified as possible. Please look at MCU_Build_Tools_Utilities.pdf for more details about predefined segments/sections. Note: We may place a various number of sections into a various number of segments. The “,” is used as section/segment delimiter. Note: In general, the placement order is given by simple list order (first specified section will be allocated from first specified segment, after that next section …). But, there are still few limitations for sections list order. The error is generated in the case of wrong list order – for example: ERROR L1122: only checksum section may be behind .copy in the section list.   The default variable/constant/code placement may be changed by #pragma commands. Note: Most of these pragma commands are not limited to the single file. Therefore, we should keep it in complementary pairs. An example of placing code into specific section: #pragma CODE_SEG MY_CODE void f ( void ) { //… } #pragma CODE_SEG DEFAULT‍‍‍‍‍‍ ‍ ‍ ‍ ‍ ‍ ‍ The #pragma DATA_SEG modifies variable placement. For example: #pragma DATA_SEG MY_RAM unsigned int counter ; //… #pragma DATA_SEG DEFAULT‍‍‍‍ ‍ ‍ ‍ ‍   The #pragma CONT_SEG modifies variable placement. For example: #pragma CONT_SEG MY_ROM const unsigned int my_parameter ; //… #pragma CONT_SEG DEFAULT‍‍‍‍ ‍ ‍ ‍ ‍   Note: The shorter option for directly allocating variables in a named segment, rather than using a #pragma may be used. For example: unsigned int counter@ "MY_RAM" ; ‍ ‍ However, even in such case, the #pragma command like #pragma DATA_SEG MY_RAM must be used at least once prior that variable declaration.   Note: The S12Z compiler/linker allows to use also already predefined sections like DEFAULT_ROM, DEFAULT_RAM or ROM_VAR as target sections in #pragma commands (not possible in the case of older S12(X) compiler/linker).     More details about #pragma commands may be found in MCU_S12Z_Compiler.pdf with default path: "c:\Freescale\CW MCU v10.7\MCU\Help\PDF\MCU_S12Z_Compiler.pdf" Data alignment Sometimes we need to keep allocated data aligned. This is for example typical requirement for ADC command and result list where DMA is used for transfer data between ADC module and memory. The simplest method is using alignment attribute. For example: volatile unsigned long adc0_cmdlist [ NR_A_CH ] __attribute__ ( ( aligned ( 4 ) ) ) ; //max 256 bytes = 64 commands per 4-byte entries volatile unsigned int adc0_results [ NR_A_CH ] __attribute__ ( ( aligned ( 4 ) ) ) ;   //max 128 bytes = 64 results per 2-byte entries‍‍ ‍ ‍ I hope it helps you. Best regards Radek
View full article
Example code pack for S12G contains simple code examples how to initialize and how to use MCU module/feature. List of examples: G128-API_wakeup_from_Stop_Mode G128-Clock and COP examples G128-Interrupt_catcher-CW51 G128-LIN-CW51 G128-PLL_PEEmode-CW51 G128-Security-CW51 G240-API+STOP-CW51 G240-API-CW51 G240-ATD+GPIO-CW51 G240-ATD-Continuous_conversion_with_interrupt-CW51 G240-ATD-Multichannel_single_conversion-CW51 G240-ATD-Single_conversion-CW51 G240-Checksum-CW51 G240-Flash-CW51 G240-PLL-PBE_mode-CW51 G240-PLL-PEE_mode-CW51 G240-PLL-PEI_mode-CW51 G240-TIM_50us_interval-CW51 G240-TIM_50us_period-CW51 GN32-EEPROM-EW-CW51 GN32-LIN-CW51 GN32-PWM16b_GPIO GN32-PWM_8bit-CW51 GN32-SCI_SPI_Gateway-CW51 GN32-SCI_wake_up_from_stop-CW51   Oct-22-2013 Update: I added G128-CAN-CW51, G240-SPI-MC33810-CW51, G240-SPI-Slave examples. I added PLL calculator. I fixed error in GN32-EEPROM-EW-CW51 example code.   Aug-21-2015 Update: Updated G240-Flash-CW51 example code. Removed image files and object code from projects (9MB->2MB size)
View full article
How to get device ID and write program once field without programming application to the S12Z device in the CodeWarrior (Eclipse).   Even the datasheet does not present the device ID it can be read at address 0x1FC000. The device ID is size of 8 bytes from 1F_C000 to 1F_C007. The meaning of the field is confidential information. Of course, other "reserved" fields on higher addresses can also be read but their meaning is also confidential. The ID is not presented in the documentation because it has reason for company only. However, some users require unique identification of the device. It is possible to use this number. In order to read the ID, it is enough to create simple project in the CodeWarrior and connect to the device without programming it and run “mem” command in the debug shell window. If you do not want to remember address ranges, then it is better to prepare command file and execute it.   Of course, we can also simply use memory window.   It is a different story if we want also to see program once field. In this case we have to execute a set of commands to get it. As an example of command file which can be executed to get device ID and program the program once field I present two command files. They can be executed in the debugger window – see and test attached project. They are AAA_Read_Device_ID_And_OTPROM.cmd  and AAA_ProgramOnceField.cmd. The project which also presents reading and writing program once field is not relevant but should be created for the device we want to play with. It is not required to be code (simple code, enough to use what is generated by wizard) loaded into the MCU’s memory. However, necessary is the debugger is connected to a memory. Because of this it is enough to set:   …. And press debug   In the debug enable “Debugger Shell”:   Before continuing please modify flash clock setup in both files to value suitable for programming on the basis of the oscclk you use. In the files search for lines    Write into debugger shell command which runs the AAA_Read_Device_ID_And_OTPROM.cmd: source "c:\D\CODING & SW\ECLIPSE\S12ZVMC-FLASH-WRITEONCEFIELD-CW106\AAA_Read_Device_ID_And_OTPROM.cmd" (it is possible you have different path to the file…please change it)   The command will execute and shows: Device ID And Program field phrase 0. If you want to see another phrase you should modify AAA_Read_Device_ID_And_OTPROM.cmd line set PHRASE 1. Change 1 to the phrase you want to see and run the command presented above “source …..” again. It is enough to press arrow up on the keyboard to see and use previous commands.   In order to program selected field use and run command “source” with the file: AAA_ProgramOnceField.cmd source "c:\D\CODING & SW\ECLIPSE\S12ZVMC-FLASH-WRITEONCEFIELD-CW106\AAA_ProgramOnceField.cmd"   The same note as previosly, the path you have could be different so adjust it. The same line as in previous file should be changed to select the phrase you want to program. As a result, you will see programming algorithm and also read back of the field, example of output: %>source "c:\D\CODING & SW\ECLIPSE\S12ZVMC-FLASH-WRITEONC EFIELD-CW106\AAA_ProgramOnceField .cmd" ############################ Programming Field = 2 ############################ cmdwin::mem 0x0386 %x = 0x30 cmdwin::wait 1000 cmdwin::mem 0x0382 %x = 0x05 cmdwin::mem 0x038C %x = 0x07 cmdwin::mem 0x038D %x = 0x00 cmdwin::mem 0x038E %x = 0x00 cmdwin::mem 0x038F %x = 2 cmdwin::mem 0x0390 %x = 0xA2 cmdwin::mem 0x0391 %x = 0xB2 cmdwin::mem 0x0392 %x = 0xC2 cmdwin::mem 0x0393 %x = 0xD2 cmdwin::mem 0x0394 %x = 0xE2 cmdwin::mem 0x0395 %x = 0xF2 cmdwin::mem 0x0396 %x = 0xA3 cmdwin::mem 0x0397 %x = 0xB3 cmdwin::mem 0x0386 %x = 0x80 cmdwin::wait 1000 ############################ Read back Programmed Field = 2 ############################ cmdwin::mem 0x0386 %x = 0x30 cmdwin::wait 1000 cmdwin::mem 0x0382 %x = 0x01 cmdwin::mem 0x038C %x = 0x04 cmdwin::mem 0x038D %x = 0x00 cmdwin::mem 0x038E %x = 0x00 cmdwin::mem 0x038F %x = 2 cmdwin::mem 0x0386 %x = 0x80 cmdwin::wait 1000 cmdwin::mem 0x0390 8      390  $a2 $b2 $c2 $d2 $e2 $f2  $a3 $b3    . . . . . . . .    Now the question, where to find commands to be able to prepare such a command files, can be asked. 1) The first information source is the CodeWarrior help. For example, search for keyword DW and it could find a command list. 2) Tcl Reference Manual   3) http://www.tcl.tk/     Finally, in the attached project can be seen also approach how to write program once field by SW. Of course, mentioned cmd files are also part of the project.
View full article
This application note was already officially released. Please, download it from: AN12086 Simple Serial Bootloader for S12Z AN12086SW software package    1.  Introduction This application note covers the operation and use of a simple serial Bootloader for the S12Z microcontroller families. The Bootloader can be a convenient way to support programming during production or “in-system”, where support for the dedicated HCS12 Background Debug interface (BDM) may not be available. Users must pre-program the S12Z MCU with the Bootloader during production or at a programming vendor. The Bootloader should reside in the MCU for further use. This Bootloader implementation allows User Application software to be downloaded into the MCU flash and EEPROM memory using the SCI serial interface. The Bootloader may be also configured for self-update similar way as a User Application software update. This Bootloader is originally based on AN4258 Serial Bootloader for S12(X) Microcontrollers Based on 180 nm Technology with several modifications and improvements. The Bootloader described in this document is only an example and comes with no guarantees and no direct support.   2. Bootloader Overview The software architecture consists of two independent software projects: Bootloader Project User Application Project For avoiding compatibility issues between these projects, the minimum interface points must be kept. The switching between Bootloader and User Application codes is managed through MCU reset. So, the Bootloader and application are not limited by write-once registers. The Bootloader Project itself contain small user-defined dispatcher code which is executed directly after MCU reset and decide whether Bootloader or User Application will be executed as next. Figure 1 Software Architecture   2.1.     Hardware Compatibility The Bootloader is written for S12Z derivatives (S12ZVM, S12ZVMB, S12ZVMA, S12ZVC, S12ZVL, S12ZVH, S12ZVHY and S12ZVFP). The Bootloader for S12Z microcontrollers is not optimized for the smallest derivatives. Therefore, S12ZVL8 derivative (only 512B RAM) is not supported and only some of derivatives (with 4kB or more RAM) supports Bootloader self-update feature (rewritable).   2.2.     Dispatcher code The Dispatcher code is executed right after MCU reset. It just temporary initializes stack (write stack pointer) and directly executes user code for testing conditions whether Bootloader code should be executed or not. The most typical testing conditions for Bootloader presents: pushed button some specific value in the EEPROM memory waiting loop for command via the communication interface If User Application code is already loaded and Bootloader was not selected, the User Application is automatically started.   2.3.     Serial interface All S12Z microcontrollers include an on-chip serial communication interface. Notice that the RS-232 or USB to TTL level shifter is necessary to communicate with PC. Optionally, the virtual COM port at OSBDM interface may be used. By default, the serial communication is set to format: 8-data bit one start bit one stop bit no parity Xon / Xoff flow control Default baud rate is configured in Config.h file. The baud rate can be changed via the Bootloader’s menu to 38400, 57600, or 115200 bps. The Bootloader implementation currently assumes using just one of SCI channels. However, this may be changed by Bootloader code modification. The same approach may be used for a different type of channel implementation like CAN or LIN.   2.4.     PC software interface A general terminal emulation program like Microsoft HyperTerminal, Tera Term, RealTerm or similar software can be used on a PC to communicate with a microcontroller. A terminal emulation program must support communications over serial COM ports, Xon / Xoff flow control, and it must be able to send a text file.   3.  Functional Description The operation of the Bootloader is straightforward. This section describes only the most important and specific points. Figure 2 Memory map 3.1.     Bootloader Project Folders The C language codes and appropriate header files are located in Sources and Project_Header folders. The exception is Dispatcher.c and start12z.c files located in Project_Settings\Startup_Code folder. The linker file is located in Project_Settings\Linker_Files folder. The FLASH folder contain generated files like elf, map or s19 files. The SRecCvt folder contains a SRecCvt.exe tool for re-formating generated S-record file. The content of Documentation folder should help you in guide how to use this Bootloader. Figure 3 Bootloader Project Folders 3.2.     Bootloader Configuration The most of the Bootloader configuration settings are collected in Config.h file.   If the modified Bootloader will use any derivative specific registers, the mc9s12zvl128.h and mc9s12zvl128.c files should be replaced with appropriate files from CodeWarrior folders: "c:\Freescale\CW MCU v10.7\MCU\lib\wizard_data\S12Z\DataBase\device\include\.." and "c:\Freescale\CW MCU v10.7\MCU\lib\wizard_data\S12Z\DataBase\device\src\.."  And followed by modification of derivative.h file.   The Config.h contains settings for: Bootloader feature configuration Clock settings SCI module settings Dispatcher definitions MCU derivative configuration and addresses Flash Configuration Field configuration   The Bootloader-persistent.prm and Bootloader-rewritable.prm linker files contain definitions of Flash and RAM ranges for Bootloader. The appropriate linker file is selected by Build Configuration. Figure 4 Build Configuration   3.2.1.     Bootloader features SECURE_MCU: The MCU may be secured after Bootloader loading (default 0 = MCU unsecured) USE_BACKDOOR_KEY: The Flash Configuration Field may already contain Backdoor Key for temporary unsecure of MCU (default 0 = backdoor key 0xFFFF FFFF FFFF FFFF). WRITE_EEPROM: When enabled, the Bootloader menu offers an option for erasing EEPROM and program option will be able to program both Flash and EEPROM. BOOTLODER_REWRITABLE: When enabled, the Bootloader code is automatically loaded into RAM and allow unprotect, erase and program Bootloader Flash area. This variable is already defined differently in used Build Configurations. That allows us to keep BOOTLODER_REWRITABLE value and selected linker file synchronized.   3.2.2.     Serial Channel The current S12Z MCU derivatives offer up to 2 SCI channels. The SCI_MODULE defines whether SCI0 or SCI1 will be used for Bootloader communication (default SCI1). The DEFAULT_BAUDRATE specifies default SCI baud rate for initial Bootloader menu display (default Baud9600: 9600bps). The baud rate can be changed via the Bootloader’s menu to 38400, 57600, or 115200 bps. The S12Z MCU derivatives offer routing options for SCI0, SCI1, and other peripherals channels. The BL_MODRR0 value defines MODRR0 value loaded by Bootloader code after a reset.    Note: The MODRR0 values may be written just once in normal mode and cannot be changed until next MCU reset.   3.2.3.     Configure Dispatcher code The default Dispatcher condition is based on the testing value of pin with push button. The PUSH_BOTTON defines tested port and pin (default PTP_PTP1) while PB_ACTIVE_LEVEL defines active logic level – when the push button is pressed (default 0 = push button to GND with pull-up). The BL_REQUEST_ADD defines tested address (default 0x100000) while BL_REQUEST_VALUE defines active value for bootloader request key. When the memory content fits to the BL_REQUEST_VALUE, Bootloader code is executed (default "BOOT" in ASCII = 0x424F4F54).   3.2.4.     Configure Derivative and addresses The FLASH_START_ADD, EEPROM_START_ADD, EEPROM_END_ADD defines MCU derivative memory ranges. The BOOTLOADER_START_ADD value is automatically obtained from linker file (ROM segment start). The Bootloader automatically move User Application reset vector to the APPLICATION_RESET_VEC_ADD address (default BOOTLOADER_START_ADD-4 = placed to the end of User Application flash area)   3.2.5.     Configure Flash Configuration Field The bytes from BACKDOOR_KEY_0 to BACKDOOR_KEY_7 defines Backdoor Comparison Key (default "UNSECURE" = 0x554E534543555245 in ASCII). The bytes PROTECTION_OVERRIDE_KEY_H and PROTECTION_OVERRIDE_KEY_L defines Protection Override Comparison Key (default "AB" = 0x4142 in ASCII). The Bootloader code should be protected against unwanted erase/rewrite operations. Trying to alter data in any protected area in the P-Flash memory will result in a protection violation error and the FPVIOL bit will be set in the FSTAT register. Flash protection scheme allows protecting 2, 4, 8 or 16KB from upper range of Flash memory. The BL_FPROT defines FPROT value automatically loaded from Flash Configuration Field after reset (default 0xD7 = upper 8kB of P-Flash protected.). The BL_DFPROT defines DFPROT value automatically loaded from Flash Configuration Field after reset (default 0xFF = EEPROM unprotected). The initial configuration of COP watchdog and GDU (S12ZVM derivatives) is given by FOPT register value. The BL_FOPT defines FPROT value automatically loaded from Flash Configuration Field after reset (default 0xFF = COP is not active after reset).   3.2.6.     Bootloader linker file Since the preprocessor functionality is no longer supported directly in prm linker file, the Bootloader use two versions of linker file: Bootloader-persistent.prm Bootloader-rewritable.prm The linker file selection is managed by two Build Configurations (Figure 4 Build Configuration).   3.3     Operation The Bootloader handles reset vector. After reset, the Bootloader’s Dispatcher routine is called. As a first step, the Dispatcher initialize stack and reads the push button pin status. If the value of the pin is equal to the PB_ACTIVE_LEVEL, the Bootloader starts its operation. If the value of this pin is not equal to the PB_ACTIVE_LEVEL, the User Application’s reset vector is tested. If the reset vector of the User Application is not available (long word at address APPLICATION_RESET_VEC_ADD is in erased state = 0xFFFFFFFF) then the Bootloader is called anyway. The User Application is called only when User Application reset vector is already programmed and the condition for Bootloader enter is not true. The user can rewrite this code to start the Bootloader or User Application upon another condition. Note: Since this code is executed prior Bootloader/application startup code, the dispatcher code shouldn’t use any uninitialized global variables.   3.4.     Interrupt vector In the case when the User Application using interrupts, it is necessary to relocate the interrupt vector table using the IVBR register. The Bootloader resides in the upper 4/8/16kB fixed block at the address defined by linker prm file. This area is had to be protected (configured in Config.h), so the User Application cannot rewrite a default location of the interrupt vector table at 0xFFFE10-0xFFFFFF. The advantage of this solution is that the Bootloader cannot be affected by a power failure that could occur when rewriting User Application interrupt and reset vectors. The Bootloader automatically moves User Application’s reset vector from address 0xFFFFFD to the  APPLICATION_RESET_VEC_ADD address = typically the end of User Application’s flash area. Since this moving is managed by the Bootloader, the whole phrase (by default from (BOOTLOADER_START_ADD-8) to BOOTLOADER_START_ADD) must be excluded from User Application’s linker usage and the same sector (512B) shouldn’t be used for User Application’s interrupt vector table.   4.  User Guide This section describes the step-by-step procedure to use the Bootloader.   4.1.     Setup procedure for the Bootloader Open the Simple_Serial_Bootloader_for_S12Z project in CodeWarrior Development Studio for MCU. The Bootloader was tested in current versions v10.7. Select the Build Configuration as shown in Figure 4 Build Configuration. The Persistent Bootloader code option allows just update a User Application. The Bootloader Rewritable code option linker allows updating both User Application and Bootloader itself. Optionally edit appropriate linker file Optionally edit the Config.h header file per your target environment (required features, clocks, channels, derivative addresses, backdoor, and protection override keys). Optionally edit the c file with conditions for select User Application/Bootloader code execution.   4.2.     Bootloader Guide   1. Compile the project and download the Bootloader to the MCU via BDM device. Note: The correct derivative should be selected in debug configuration for successful complete MCU Flash erase and programming (Figure 5 Select derivative for Bootloader download). Figure 5 Select derivative for Bootloader download     2. Open the Microsoft HyperTerminal or any other serial terminal utility (e.g. Realterm, Tera Term,…). Set the baud rate 9600 bps, 1 start bit, 8 data bits, 1 stop bit, and flow control Xon / Xoff.   3. Make sure there is a serial (USB to Serial) cable connection between the PC and the board.   4. Hold the PUSH_BOTTON pin low and reset the MCU.   5. The Bootloader is started and the following response is received in HyperTerminal. See Figure 6 Initial screen.   Figure 6 Initial screen   6. Type “a” to erase the flash memory. This is not necessary the first time because the flash has been already erased by the BDM device.   7. Type “b” to program the flash.   8. Now send the desired S-record as a text file — See Figure 7 Send Text File. Browse for S-record which is downloaded to the MCU. For testing purposes, use demo S-records that are attached to this application note. The S-records must have a specified format. Refer to chapter 3 How to write a User Application and to chapter 4.4 How to convert S-Record that will be downloaded by the Bootloader. Figure 7 Send Text File     9. Confirm the dialog and the S-record are downloaded to the MCU. One printed star (*) means that one line of S-record has been programmed. See Figure 8 Download User Application. Figure 8 Download User Application   Note: If User Application contains any EEPROM data, please erase EEPROM by typing “h” prior the step 7. Note: If you want to reprogram Bootloader code, please use subsequently options “e” (it will ask you for entering protection override key), step “f” and step “g” instead steps 6 and 7.   4.3.     How to write a User Application You must ensure that the User Application does not interfere with Bootloader area defined by Bootloader linker file.   1. Create a new User Application project in CodeWarrior Development Studio for MCU.   2. Open the User Application project.prm file   3. Trim the high address of the segment ROM from the original to the (BOOTLOADER_START_ADD-8). For example, to the address 0xFFDFF7. This is because the area 0xFFDFF8–0xFFFFFF is occupied by the Bootloader and the area at address 0xFFDFF8–0xFFDFFF will be used for the User Application reset vector. If interrupts are used:   4. Trim the low address of the segment ROM from the original to (the original address + 0x200). This area will be used for the relocated interrupt vector table. Note: You may use any other Flash sector in User Application memory for that purpose except the last one (already used for the User Application reset vector). Note: The generated CodeWarrior project doesn’t show warning about memory overlapping between linker and user object placement. This warning is disabled by default (Linker option -WmsgSd1912).      5. Create a vector table as shown in the attached demo applications and set the IVBR register accordingly. The IVBR sets the interrupt vector table base address. It contains 15 most significant bits from 24bit vector table address.   4.4.     How to convert S-Record that will be downloaded by the Bootloader The default S12Z MCU project generated by CW10 does not generate a file with s-records automatically.   1. Check option for generating S-Record file in User Application project settings per Figure 9 Generate S-Record file The <YourProjectName>.sx file will be generated when you will build your project. Figure 9 Generate S-Record file For the simplifying, the Bootloader parser, only s-records with specific format are accepted. All records must be aligned to 32 bytes and the length of records must be 32 bytes.   2. Copy SRecCvt directory with SRecCvt.exe tool from Bootloader/Application Example project to your User Application project   3. Exter command “ ${ProjDirPath}/SRecCvt/sreccvt.exe -hc12 -m 100000 FFFFFF 32 -o ..\FLASH\\${BuildArtifactFileBaseName}.s19 ..\FLASH\\${BuildArtifactFileBaseName}.sx ” as post build step into User Application project settings per Figure 10 Adding Post-build step . Figure 10 Adding Post-build step This command will load S-Records from your <YourProjectName>.sx file and create new <YourProjectName>.s19 file with reformatted S-Records when you build your project. Note: The complete SRecCvt utility may be downloaded from NXP web pages. Unfortunately, the graphical user interface doesn’t support directly S12Z derivatives. Therefore we use this tool in command line mode.   4.5.     How to merge the User Application and Bootloader The User Application can be developed independently, that is without the Bootloader. The User Application can be loaded into the microcontroller and can be debugged directly via the BDM device. However, for production purposes, it is worth merging the User Application and Bootloader together, so it can be downloaded into the microcontroller all at once as a single S-Record file. This is a recommended procedure:   1. Open the User Application that was created as per chapter 3, "How to write a User Application" in the CodeWarrior Development Studio for MCU.   2. Replace a User Application reset vector in Project.prm file from default address to the address (BOOTLOADER_START_ADD-3), so the Bootloader can use this vector for start User Application. For example: //VECTOR 0 _Startup VECTOR ADDRESS 0xFFDFFD _Startup   3. Copy the ready-mades19 file to ..\user_application_project\FLASH directory. Note: the s-record file can be renamed for example to the bootloader.s19.   4. Link this file to the User Application be using command at the beginning of Project.prm: HEXFILE Simple_Serial_Bootloader_for_S12Z.s19   5. Build the project. The final S-Record is ready to be downloaded into the microcontroller by the BDM interface.   5.  Testing The Bootloader and example application were tested on evaluation boards: DEVKIT-ZVL128 S12ZVMC256EVB S12ZVM32EVB S12ZVM-MINIBRD   6.  Content of Zip file All mentioned projects and utilities can be found in a zip file associated with this application note: Simple_Serial_Bootloader_for_S12Z — Bootloader project for S12Z microcontrollers. Application_Example_for_SSBZ — Projects that show how to write User Applications. Converted_srecords — S-Records was taken from Bootloader and Application Example that has been converted by the SRecCvt utility (*.s19 file extension). These S-Record files can be downloaded into the MCU by the Bootloader. SRecCvt — Utility for S-Record files converting.   7.  Reference AN4258 AN4258SW: Serial Bootloader for S12(X) Microcontrollers Based on 180 nm Technology Rev 0. February 2011. S12Z Protection Override S12Z constant, variable, code allocation in CodeWarrior S12Z Interrupt catcher for unexpected interrupts S12Z Flash example code S12Z EEPROM example code   I hope it help you. Please let me know when you find any error or if something missing in this document.   Radek Sestak
View full article
Interrupt catcher example code catches all unexpected interrupts. It can be used for debugging or directly in the application software. The Machine Exception routine is used here as example of expected interrupt.   A few notes: 1. For each expected interrupt you must remove a code line for given interrupt     from the part of the code "A Set of unimplemented interrupts" and     create your own service routine as it is, for example, made     for interrupt 5 void Machine_Exception_ISR(void)   2. All interrupt vectors have 32bit size, however, addresses have only 24bit,     therefore the most significant byte in interrupt vector is not used.     Definitions with the keyword "interrupt XX" where XX represents vector     order in the interrupt vector is used to define interrupt service function.      3. Interrupt number 0 is assigned to POR reset vector,                      1 is assigned to Unimplemented page1 op-code trap vector                      2 is assigned to Unimplemented page2 op-code trap vector                      3  ...                      4  ...     Interrupt number = (0x1FC-Vector Address)/4. See Table 1-11. Interrupt     Vector Locations at RM(page 62-65).     For Example: Interrupt number of SCI0 = (0x1FC-0x19C)/4 = 0x18 = 24.     So you can use either form                interrupt VectorNumber_Vsci0 void SCI0_isr(void)     or                interrupt 24 void SCI0_isr(void)     or                interrupt ((0x1FC-0x19C)/4) void SCI0_isr(void)       Note: VectorNumber_Vsci0 is defined in mc9s12zvl32.h      
View full article
Abstract The paper describes basic scaling procedure of a six-step BLDC motor control application with focus on S12ZVM MCU devices.  Abstract Introduction BLDC six-step control Speed scaling Timing Commutation periods Speed calculation Application note links Calculation accuracy Real applications Resources Introduction Based on the various questions regarding the BLDC speed calculation, I've decided to write this document to make the scale calculation clear. Please use it for your reference and comment in case there is something to be explained in more details. BLDC six-step control This document is linked with the six-step control of BLDC motors, known for the trapezoidal back-EMF shaped voltage. The key is to create a torque using DC current in two phases while the third phase is not connected. As the rotor is moving, the phases are switched (commutated) to keep the stator flux ahead the rotor flux. The principles are well described in many application notes, such as AN4718 or AN4704. The instant of the commutations can be driven by Hall sensors or by the back-EMF signal monitoring (so-called "sensorless"). For field-oriented control, please refer to the PMSM control discussed in AN5135 or AN5327. Speed scaling It's more benefitial to describe in details the sensorless algorithm over the hall-sensor-based control. However, the approach is almost the same. Timing The motor speed is calculated based on the zero-cross detection of BEMF voltage on a non-active phase. These zero-cross events times are measured by capturing a timer (TIM0CNT) register at the time the ADC routine detects a zero-cross (or when the Hall sensor commutation event occurs). That means, the time is scaled by the timer TIM0 settings. There is no general guidance how to set up the timer. However, the timer should be set to cover some reasonable number of ticks between two commutations (which is linked to the speed precission at high speeds) and should be able to cover two commutations "far away" from each other at very low speeds, without the timer overflow. A good practice would be: at least 100 timer ticks between two commutations maximum 16bit = 65535 ticks between two commutations The same aproach can be followed using the Hall-sensor events. Commutation periods In the application, zero-cross (or hall-sensor) periods are captured with  periodZC_F_PhA, periodZC_R_PhA , etc. or periodZC[6], defined as tU16 (16 bit unsigned). The periods are captured using a timer, as mentioned above. In electric motor theory, we recognize "electrical" and "mechanical" speed. The "electrical" speed is linked with the rotational field. The mechanical speed is connected directly with the rotor speed. The relation between these two speeds is determined by number of poles or pole-pairs: (1)   mechanical speed = electrical speed / number of pole-pairs = electrical speed / ( number of poles / 2 ) In the following text, 3-phase BLDC motor is discussed. Speed calculation To calculate one "electrical" revolution of a motor = 6 commutations (or 6 zero-crosses), all the 6 commutation time periods shall be summed. For that case, the resulting " period6ZC " is defined, formated as tU32 (or unsigned long) to prevent an overflow if all six 16-bit zero-cross periods are summed. If you sum all the 6 zero-cross periods, you'll get the number of timer ticks per single "electric" revolution. That means, if the motor is 2-pole motor ( = 1 pole-pair motor), it would be the time per single "mechanical" revolution of the rotor. In thsi case: (2)   mechanical speed = electrical speed; You can easily get the time per mechanical revolution for higher-pole motor simply by multipling it by number of pole-pairs. (3)   time per mechanical revolution = period6ZC * number of pole-pairs   The period per 6 zero-crosses  " period6ZC "  is calculated within the control loop, usually in the 1 ms timer interrupt routine. Since the speed (rotor frequency) is just an inverted time period, we can use following code line to calculate the actualSpeed: (4) actualSpeed = SPEED_CALC_NUMERATOR / period6ZC; Now, how to read it's scale and what is the SPEED_CALC_NUMERATOR ? Let's assume the " actualSpeed " is tFrac32 (1.31 formated signed 32bit number). It would mean the maximal fraction number is 1.0, which is represented by its integer value 2^31 = 2,147,483,648. Why to use 32-bit number over 16-bit is obvious - since the period6ZC is 32-bit value, the result should be of the same resolution or width. The task is to find the  right  SPEED_CALC_NUMERATOR . Let's consider the S12ZVM device and the timer TIM0 used to capture the zero-cross events times. The prescaler is set to 16 (TIM0TSCR2_PR = 4) and the bus clock is 12.5MHz, the timer tick is 12.5MHz / 16 = 781.25 kHz, in time scale it is 1.28us. Let's assume the maximum mechanical speed of the motor is 10,000 RPM and the motor has 6-pole-pairs. That would give us (5)   (10,000 RPM) / (60 seconds) = 166.67 revolutions per second, (6)    166.67*(6 pole-pairs) = 1000 electrical revolutions per second, so (7)    1000 * (6 commutations) = 6000 commutations/zero-crosses per second. (8)    That would make 1/6000 = 166.67us per one commutation. (9)   Ticks per one period at max speed = 166.67 us / 1.28us = 130.28 With our 1.28us timer, we can catch upto 130 periods at maximal speed. For maximal speed of the motor 10,000 RPM, we can simply rearrange the " actualSpeed " calulation shown in (4) into (13) and (14), assuming that: (10)    actualSpeed  = FRAC32(1.0) = 2,147,483,648 (11)    period6ZC   = 6 periods * 130 = 780 (rounded down, since the value is still an integer) In case of S12ZVM device, it is more convenient to use 16-bit (tFrac16) calculations than 32-bit. Hence, we can do a trick with the scaling to use 32-bit actualSpeed to prevent an overflow use the same 32-bit number as 16-bit number just by scaling it correctly benefit from the 16bit calculation, which is good enough and fast enough at the same time The trick is hidden in the casting of the   actualSpeed   from Frac32 to Frac16: (12)    speedErr = requiredSpeed - (tFrac16) actualSpeed; That means, only the lower 15 bits are considered the speed (assuming the actualSpeed will never exceed 32767 so the 16th "sign" bit will always be zero). For maximum speed and the SPEED_CALC_NUMERATOR determination, the " actualSpeed " should be 32767 (which is the range of signed tFrac16). Equation (4) can be used to calculate the  SPEED_CALC_NUMERATOR as follows: (13)    32767 = SPEED_CALC_NUMERATOR / 780 (14)    SPEED_CALC_NUMERATOR  = 780 * 32,767 = 25,558,260 Thus  #define SPEED_CALC_NUMERATOR 25558260 Using the equation (4), the speed for the minimum period6ZC would be: (15)    actualSpeed   =   SPEED_CALC_NUMERATOR   /   period6ZC   = 25,558,260 / 780 = 32,767; Masking that value by lower 15 bits and casting it to tFrac16 would give us 1.0. Since the speed scale has been determined by the maximum speed of the motor 10,000 RPM, we can calculate the real speed simply by: (16)   RealScaleSpeedRPM  = (tFrac16) actualSpeed   / 32,767 *   MAX_SPEED   =   (tFrac16) actualSpeed   / 32,767 * 10,000. Application note links In the application note AN4704, there are several macro constants used to control the application. These constants should be calculated using following definitions, with a little help of the SPEED_SCALE - floating point representation of the real scale of the speed. #define SPEED_SCALE 10000.0  // Used for correct calculation of the following: #define REQUIRED_RUN_SPEED FRAC16(2000.0/SPEED_SCALE) // 2000 rpm #define MIN_SPEED FRAC16(500.0/SPEED_SCALE) // 500 rpm minimal speed for Down button control (should be min 10% of nominal motor speed) #define MAX_SPEED FRAC16(5000.0/SPEED_SCALE) // 5 krpm maximum speed for Up button control #define SPEED_STEP FRAC16(100.0/SPEED_SCALE) // 100 rpm, Up/Down step for button controls   If the application uses FreeMASTER to display or control, the scales shall be updated in the FreeMASTER project as well. The new FM scales for AN4704 are: Variable name Variable watch settings requiredSpeed Real type transformation: Linear: a =   SPEED_SCALE   = 10,000; b = 0 actualSpeed Signed int, Size = 4 Show as: REAL Bit fields maks with: word (0xffff) Real type transformation: Linear: a =   SPEED_SCALE   / 32767.0 = 0.3051851; b = 0  Calculation accuracy Now, let's have a look on the speed resolution (or accuracy): At the full speed, if one period changes by 1 tick, then you'll get the   period6ZC   from 780 to 781 at max speed, which makes 12.8041 RPM difference. The higher the   SPEED_SCALE   is, the higher the error is. If the assumption would be a change in all of the 6 periods (thus the   period6ZC   would change from 780 to 786), the resulting change to the speed would be 76.336 RPM. That makes the speed error 10,000 RPM +- 76, which is 0.76%. In terms of accuracy, it makes sense to set the maximum speed (or the SPEED_SCALE) to the maximal speed of the application instead of copying some high number from the datasheet of the motor. Well, the max speed of the application should not exceed the max speed of the motor, but it doesn't help if the speed scale is unnecessarily high. Real applications In real applications, the calculated speed (actualSpeed) reflects all the deviations and changes of the period6ZC. Therefore, it is a good practice to do some kind of filtering of the period6ZC, either by averaging or using a low-pass filter. In case of one or more zero-crosses are lost, there should a mechanism to process and detect if the motor is stalled (mechanical speed loses lock with the commutation) or if it is just a disturbance to the signal. The stall detection or the Hall-signal fault/damage detection is one of the challenges towards high quality application. Resources S12ZVM MCU  - NXP main S12ZVM page AutoMCDevKits - NXP Automotive Motor Control Development Solutions AN4718 - 3-Phase BLDC Hall Sensor Application Using S12ZVM AN4704 -  3-phase Sensorless BLDC Motor Control Kit with the S12 MagniV MC9S12ZVM AN5201 - Integrating the LIN driver with BLDC sensorless motor controller In the S12ZVM128 device AN5330 -   Migration Guide for S12ZVM Devices
View full article
A project presents control of the HD44780 driven display where it is assumed that RW pin of the LCD is permanently connected to “Write” level (GND). The SW contains mirror(s) of the LCD display as array of characters stored within RAM. Both read and write function can be used because writing is performed to the display and also to the array. Read functions are directed to the character array stored within RAM.
View full article
Introduction S12ZVM is a mixed signal MCU for automotive motor control applications. PWM signal for external MOSFETs is managed by integrated gate drive unit, providing gate signals of dedicated profile and strength. In motor control application, current feedback is typically needed and is usually measured in synchronization with PWM signal. In order to schedule sampling commands correctly, delays between PWM signal and actual MOSFET state have to be known. Following text aims to show how to measure delays between PWM and GDU on S12ZVM device. Based on the S12ZVM Reference Manual, the delay is dependent on the slew-rate settings, thus it is important to measure this delay for user configuration. How to Measure Delays in S12ZVM Application? S12ZVM provides PWM probe signals for debugging purposes. In this special mode, PWM signals can be enabled on general purpose pins. User has to make sure the pins are available and not used by another functionality. Pins availability has to be checked for specific product in the Reference Manual. As an example, S12ZVM PMSM/BLDC development kit can be used. S912ZVML12F1MKH or S912ZVML12F3MKH is populated, which introduces PMF_V3 and GDU_V4 in 64-pin LQFP package. On this device, PMF output signals (PWM1_0 to PWM1_5) are routed to pins PP0, PP1, PP2 and PT0, PT1, PT2 and probing can be enabled by PWMPRR1-0 bits in MODRR1 register (see Paragraph 2.3.2.2 Module Routing Register 1 (MODRR1) in the Reference Manual. Note In many motor control applications, probing pins are being used by the application, for example: PP0 - used as EVDD1 external 5V power supply for sensors PP1, PP2 - used for "keyboard wake-up" functionality (e.g. car key signal) PT0, PT1, PT2 - used as Hall-switch sensor inputs (timer input-capture mode signals) or SPI interface or SCI/UART interface. In such cases, it is necessary to have special PCB configured for the test, where the functions above are disabled (e.g. components not populated). System settings Considering S12ZVM PMSM/BLDC development kit as an example, jumper settings should be changed to have the PWM signals clear (with no external load or source, e.g. pull-ups). Jumper Default settings Configuration for the test Notes J9 Enabled Disabled User On/Off switch on PT1 J14 2-3 Removed EVDD / Fault input on PP0 J15 2-3 Removed HALL_A / Res_A on PT1 J16 2-3 Removed HALL_B / Res_B on PT2 J19 Enabled Disabled "Up" button on PP1 J20 Enabled Disabled "Down" button on PP2       Testing Points Oscilloscope of sufficient parameters should be used (at least 500Ms/s) with standard low-capacitance probes or better, with isolated differential probes. Channel connection for the test should be as follows: Channel 1: PWM1_n signal to GND (for PWM1_0, PP0 on J21:1 can be used) Channel 2: GDU HGm or LGm signal to GND (for HG0, TP31 is used) or HGm to PHASE_m if differential probe is used (for HG0, TP31 and PHASE_A / TP35) Channel 3: Phase voltage on PHASE_m to GND (e.g. PHASE_A)   Software Demo software provided on the S12ZVM PMSM/BLDC development kit page can be used for the test with minor changes: In "main.c", buttons and switch handling should be disabled (commented out) INTERRUPT void ADC1done_ISR(void) { static tBool getFcnStatus; EnableInterrupts; //PTT_PTT0 = 1; // Set debug pin to record execution time // Read the user control interface //cntrState.usrControl.btSpeedUp = PTP_PTP1; //cntrState.usrControl.btSpeedDown = PTP_PTP2; // User switch should be checked only if not in init state (see state machine table) //if(cntrState.state != init) // cntrState.usrControl.btFlipFlop = PTT_PTT1; // User accessible switch for stopping the application. if (cntrState.usrControl.btFlipFlop ^ cntrState.usrControl.btFlipFlopTemp) { cntrState.usrControl.btFlipFlopTemp = cntrState.usrControl.btFlipFlop; cntrState.usrControl.switchAppOnOff = (cntrState.usrControl.btFlipFlop) ? false: true; } ... In "src\S12ZVM_system\peripherals\pim.c", pin configuration should be changed as follows: void pim_init(void) { MODRR0_SCI1RR = 1; // SCI - FreeMASTER //DDRS_DDRS4 = 1; // Debugg Signal //DDRS_DDRS5 = 1; // Debugg Signal //DDRT_DDRT0 = 1; // Debugg Signal MODRR1_PWMPRR = 0x01; //PWM to pins enabled //DDRT_DDRT1 = 0; // Input switch signal }  Finally, GDU slew rate should be set to the values assumed by the application: GDUSRC_GSRCHS = 7; // High-side slew rate GDUSRC_GSRCLS = 7; // Low-side slew rate Results Resulting waveforms can be seen on the following figures for normal (room) conditions and using following setup: Item Details Oscilloscope Lecroy WaveRunner 44Xi-A Probes PP008 / 500MHz, 10MΩ, 9.5pF Evaluated PWM signal PWM1_0 / HG0 EVB S12ZVMLEVBLIN Rev.D   Two corner cases have been used to match the specifications in the Reference Manual. However, user-specific slew rate settings may be used to measure the delay in the application. Slowest Slew Rate Settings (GDUsrc=0) Switch-on delay: Switch-off delay: Fastest Slew Rate Settings (GDUsrc=0x77) Switch-on delay:   Switch-off delay:   Summary Measured values are compared with the Reference Manual specifications. Switch-on and switch-off delays are presented. As seen below, the results are within the specified range. Slew rate Edge Minimum Maximum Measured Fastest slew T_delay_ON 0.47 μs 0.89 μs 0.55 μs T_delay_OFF 0.25 μs 0.49 μs 0.32 μs Slowest slew T_delay_ON 0.77 μs 1.43 μs 1.08 μs T_delay_OFF 0.25 μs 0.49 μs 0.33 μs   For higher confidence, high temperature and low temperature tests are recommended. Conclusion This short article shows how to measure propagation delay between PWM signals and GDU outputs on S12ZVM using S12ZVM PMSM/BLDC development kit. The PWM to GDU propagation delay is important information for proper timing of ADC triggering if synchronized with PWM. In simple or simplified use cases, maximum ratings of the delay can be used for consideration. However, unnecessarily higher time span between the PWM edge and ADC trigger may raise a need for lower duty-cycle limit, thus limiting the overall performance e.g. at high speed. Therefore, the importance of proper ADC triggering based on known propagation delay of PWM to GDU signal is obvious. In addition, MOSFET turn-on and turn-off times have to be considered in the overall ADC triggering schedule, based on application-specific settings.
View full article
This short video demonstrates a path through NXP website to the CodeWarrior v5.1 download link. On the final place other downloads are available such as service packs, updates, patches etc. Login to NXP site is required.
View full article