Kinetis Microcontrollers Knowledge Base

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

Kinetis Microcontrollers Knowledge Base

Discussions

Sort by:
I’ve noticed some comments about Kinetis MCUs availability and status that I’d like to address for the entire community. The Kinetis MCU portfolio has seen significant growth in the mass market and is on track for continued strong growth in the coming years. Due to this growth, the demand on the Kinetis MCUs has outstripped the available supply, leading to extended leadtimes.  We have invested additional resources across the manufacturing line for 2018 and beyond to increase overall capacity and are pleased to be able to communicate that the lead time is being reduced from 39 weeks to low 30's this month.  It is anticipated there will be further reduction in Q3 2018 with a target of being back to a typical 12-14wk lead time in Q1 2019.  Additionally, we have increased our product longevity commitment on Kinetis K, L, E, V, M and W MCUs to 15 years to support the strong pipeline of design-in activity across the Kinetis portfolio that we are seeing in the market.  This document was generated from the following discussion: Kinetis Availability & Longevity
View full article
The FlexIO module was first introduced in the Freescale Kinetis KL43 family. It is capable of emulating various serial communication protocols including: UART, SPI and I2C. The FlexIO module is very flexible and you can configure it according to your communication needs. The main components of the FlexIO module are the shifters, timers, and pins. Data is loaded onto a shifter and a timer is assigned to generate the shifter clock and use a pin to output the data from the shifter. The KL43 FlexIO module has 4 32-bit shifters, 4 16-bit timers and 8 bidirectional I/O pins. Each shifter and timer has its own configuration registers. The most important registers that configure the whole FlexIO behavior are the SHIFTCFG, SHIFTCTL, TIMCFG, TIMCTL and TIMCMP registers. There are other registers that contain status flags, interrupt enabling bits and the buffers for the shifters. Shifters have a timer assigned to them to generate the shift clock and it can be configured to shift data in or out. When the shifter is configured to transmit mode, the data from the SHIFTBUF register will be loaded to the shifter and the shifter status flag will be set meaning that the shifter is ready to start the transmission. In receive mode, the shifter status flag is set when SHIFTBUF has been loaded with the data from the shifter, and the status flag is cleared when the SHITBUF register is read. The timers are highly configurable, they can use external or internal triggers to generate certain conditions to reset, enable and disable the timer. The triggers can be a timer output, shifter status flag, pin input or an external trigger input. They can be configured to enable in response to a trigger, pin or shifter condition. Each shifter or timer can be configured to use any FlexIO pin with either polarity. The pins can be used as an input or output. A pin configured as an input for a timer can be used to receive a clock and use it as the shifter clock that is assigned to this timer. Once everything is configured you need to read/write the shifter buffers and the shifter and timer status flags to start a transmission or to read the contents of the shifter buffer when receiving data. The following diagram gives a high-level overview of the configuration of FlexIO timers and shifters. Figure 1. FlexIO block diagram In the following example configuration, the FlexIO module will be configured as a transmitter. It will use one shifter, two timers, and three pins. The pins will be used for the outputs of the shifter and the two timers. One timer will be used as the shifter clock and the other timer will be used as a chip select to show when a transmission is being made. The FlexIO will be configured to have a baud rate of FlexIO clock/4 and will do an 8-bit transmission. Figure 2. Example transmission Timer 0 Timer Configuration 0 Register (FLEXIO_TIMCFG0) = 0x00002200 TIMOUT = 0    Timer output is logic one when enabled and is not affected by timer reset. TIMDEC = 0    Decrement counter on FlexIO clock, Shift clock equals Timer output. TIMRST = 0    Timer never reset. TIMDIS = 2    Timer disabled on Timer compare. TIMENA = 2    Timer enabled on Trigger high. TSTOP  = 0    Stop bit is disabled. TSTART = 0    Start bit disabled. Timer Control 0 Register (FLEXIO_TIMCTL0) = 0x01C30101 TRGSEL = 1    Trigger select. Shifter 0 status flag. TRGPOL = 1    Trigger active low. TRGSRC = 1    Internal trigger selected. PINCFG = 3    Timer pin output. PINSEL = 1    Timer pin 1 select. PINPOL = 0    Pin is active high. TIMOD  = 1    Dual 8-bit counters baud/bit mode. Timer Compare 0 Register (FLEXIO_TIMCMP0) = 0x00000F01 TIMCMP = 0x00000F01        Configure 8-bit transfer with a baud rate of FlexIO clock/4. Set TIMCMP[15:8] = (number of bits x 2) - 1. Set TIMCMP[7:0] = (baud rate divider / 2) - 1. In our case we want an 8-bit transfer so TIMCMP[15:8] = 0xF and a baud rate divider of 4 so TIMCMP[7:0] = 0x1. Timer 1 Timer Configuration 1 Register (FLEXIO_TIMCFG1) = 0x00001100 TIMOUT = 0    Timer output is logic one when enabled and is not affected by timer reset. TIMDEC = 0    Decrement counter on FlexIO clock, Shift clock equals Timer output. TIMRST = 0    Timer never reset. TIMDIS = 1    Timer disabled on Timer N-1 disable. TIMENA = 1    Timer enabled on Timer N-1 enable. TSTOP  = 0    Stop bit is disabled. TSTART = 0    Start bit disabled. Timer Control 1 Register (FLEXIO_TIMCTL1) = 0x00030283 TRGSEL = 0    Trigger select. Doesn’t matter because we won’t use a trigger. TRGPOL = 0    Trigger active high. TRGSRC = 0    External trigger selected. PINCFG = 3    Timer pin output. PINSEL = 2    Timer pin 2 select. PINPOL = 1    Pin is active low. TIMOD  = 3    Single 16-bit counter mode. Timer Compare 1 Register (FLEXIO_TIMCMP1) = 0x0000FFFF TIMCMP = 0x0000FFFF Never compare. Shifter 0 Shifter Control 0 Register (FLEXIO_SHIFTCTL0) TIMSEL = 0    Timer 0 select. TIMPOL = 0    Shift on posedge of Shift clock. PINCFG = 3    Shifter pin output. PINSEL = 0    Shifter pin 0 select. PINPOL = 0    Pin is active high. SMOD   = 2    Transmit mode. Load SHIFTBUF contents into the Shifter on expiration of the Timer. Shifter Configuration 0 Register (FLEXIO_SHIFTCFG0) INSRC  = 0    The input source of the shifter is from a pin. In our cause this doesn’t matter because our shifter is set as transmit mode. SSTOP  = 0    Stop bit disabled. SSTART = 0    Start bit disabled. Once all the FlexIO components are configured you have to enable the FlexIO instance by setting the FLEXEN bit in the FLEX_CTRL register. Initially, the shifter status flag is set and is cleared each time the SHIFTBUF register is written. This flag is set each time the SHIFTBUF data has been transferred to the Shifter (SHIFTBUF is empty).  The shifter status flag 0 is configured to be the trigger of the timer 0, so as soon as the status flag is cleared, the timer 0 will be enabled because TIMENA = 2 (Timer enabled on Trigger high)and TRGPOL = 1 (Trigger active low). The shifter will begin to shift out the data on the positive edge of the clock (TIMPOL = 0) until the timer is disabled. The timer will disable when the timer counter reaches 0 (TIMDIS = 2). The timer 1 is configured to be active (low) when the timer 0 is enabled. This is because TIMDIS = 1 and TIMENA = 1. The compare register is configured to 16-bit counter and set to 0xFFFF. With this value the timer will never compare and always be active when the timer is enabled. To send data, you have to make sure that the previous transaction was completed and you can check this by reading the TIMSTAT flag. This flag sets each time the timer counter reaches 0. Once the TIMSTAT flag is set, you clear it and write your new data to the SHITBUF register to start the transaction. The KSDK 1.2.0 has drivers and a HAL to facilitate the configuration of the FlexIO module. Some of the important functions are: FLEXIO_DRV_Init(uint32_t instance, const flexio_user_config_t *userConfigPtr); Use this function to initialize the FlexIO module before using it. In this configuration you can change the settings in the FLEXIO_CTRL register such as: Doze Enable, Debug Enable, Fast Access and software reset. FLEXIO_HAL_ConfigureTimer(FLEXIO_Type * base, uint32_t timerIdx, const flexio_timer_config_t *timerConfigPtr); Use this function to configure a timer in the FlexIO. This function uses a configuration structure that can change the TIMCFG, TIMCTL and TIMCPM registers. FLEXIO_HAL_ConfigureShifter(FLEXIO_Type * base, uint32_t shifterIdx, const flexio_shifter_config_t *shifterConfigPtr); Use this function to configure a shifter in the FlexIO. This function uses a configuration structure that can change the SHIFTCFG and SHIFTCTL registers. FLEXIO_HAL_SetShifterBuffer(FLEXIO_Type * base, uint32_t shifterIdx, uint32_t value); Use this function to start a transmission. When writing to the SHIFTBUF register, the Shifter Status Flag is cleared. FLEXIO_DRV_Start(uint32_t instance); Use this function to enable the FlexIO module by setting the FLEXEN bit in the FLEX_CTRL register. FLEXIO_HAL_GetTimerStatusFlags(FLEXIO_Type * base); This function returns the contents of the TIMSTAT register. You can use this function to check when a transmission is finished. FLEXIO_HAL_ClearTimerStatusFlags(FLEXIO_Type * base, uint32_t mask); This function clears a specific Timer Status Flag. You can use this function to clear a flag after you read that the flag was set. To change the frequency of the transmission you have to change the value of the TIMCMP register. In dual 8-bit counters baud/bit mode, the lower 8-bits configures the baud rate divider equal to (CMP[7:0] + 1) * 2 and the upper 8-bits configure the number of bits in each word equal to (CMP[15:8] + 1) / 2. In our example the baud rate divider is set to 4, this means CMP[7:0] has the value 1. The number of bits transmitted is set to 8, this means CMP[15:8] has the value 0xF. Let’s change the baud rate divider to 32. To obtain the CMP[7:0] value, we will have to solve the simple equation: 32 = (CMP[7:0]+1)*2 CMP[7:0] = 15=0xF Now let’s change the number of bits to 16. The CMP[15:8] value is defined by: 16 = ((CMP[15:8]+1))/2 CMP[15:8] = 31=0x1F The value for the TIMCMP for the timer 0 has to be 0x00001F0F to get a baud rate divider of 32 and a word length of 16 bits. The waveform will look as follows. Figure 3. 16-bit transmission By default the shifter in the FlexIO transmits the LSB first. To change the transmission order, you have to write to the SHIFTBUFBIS (Bit swapped) register instead of the SHIFTBUF register. There are also other buffer registers: SHIFTBUFBYS and SHIFTBUFBBS. The first register swaps the bytes and the second register swaps the bytes and bits at the same time. When using one of these registers you have to be careful to consider that the length of the SHIFTBUF registers is of 32 bits, so if you choose to use the SHIFTBUFBIS for a transmission and your transmission length is not of 32 bits, you have to start writing your data starting from the most significant bit. The following image shows a MSB transmission. The value 0x6AED0000 was written to the SHIFTBUFBIS register. Figure 4. MSB 16-bit transmission The FlexIO module supports automatic start and stop bit handling. All you have to do is change the SHIFTCFG and the TIMCFG configuration bits. In the SHIFTCFG register set SSTOP to 11 if you want the stop bit to have the value 1, and set the SSTART to 10 if you want the stop bit to have the value 0. In the TIMCFG register set the TSART to 1 and the TSOP to 10. The transmission will look as the following image. Data transmitted 0x0F. Figure 5. Transmission with start and stop bit Changing the phase of the clock is very easy, you just have to set the TIMPOL bit to 1 in the SHIFTCTL register. Figure 6. Shift on negedge of Shift clock The conditions to disable and enable the timers can be configured by changing the TIMENA and TIMDIS values in the TIMCFG register. In our example the timer is enabled by the trigger high. The trigger can be set to be an external pin, a shifter status flag, or a timer output. In our case the trigger was set to the shifter status flag, but you can change this configuration to your communication needs. The timer can also be enabled when the previous timer is enabled, on a certain pin edge, or with a combination of pins and triggers. The timer in the example above disables on the timer compare. This means that when the timer counter reaches zero, the timer will disable automatically. The timer counter is loaded with the timer compare value every time it reaches zero or when it is first enabled.  The timer can also be disabled by other conditions such as: when the previous timer is disabled, on a trigger falling edge, on a pin edge, or on a combination of these. Each pin can be configured to be active high or low. When a pin polarity is changed it only affects the output of the pin, for example, if a timer is set to be the shifter clock and you change the pin polarity, the shifter clock will not change its polarity, only the output to the pin from the timer will change. The configuration for the polarity of the pins is located in the TIMCTL and SHIFTCTL. When the PINPOL value is changed to 1, the pin is active low. In the following image the polarity of the timer pin and the shifter pin was changed to 1, so they are active low. Figure 7. Timer and Shifter active low The FlexIO module can generate an interrupt from 3 sources: Shifter error, Shifter status flag and Timer status flag. To enable the interrupts you need to set the bits in the SHIFTSIEN,SHIFTEIEN and TIMIEN. If you are using KSDK you can enable the interrupt in NVIC by setting true .useInt in the FlexIO user config that the function FLEXIO_DRV_Init utilizes. The default handler for the interruption is named UART2_FLEXIO_IRQHandler. The following example configuration will configure the FlexIO module as a receiver. This configuration works with the first example configuration shown. Both tower boards (TWR-KL43Z48M) have to be connected as shown further below in the Table 1 Hardware connnections. The FlexIO module will use one Shifter, one timer, and three pins. The pins will be used for the input of the shifter, the input clock for the timer and the trigger for the timer. The timer will use pin 1 as an input and its output will be the same as the input clock. The trigger for the timer will be the transmitter chip select pin and it will be used to enable or disable the timer. The FlexIO will be configured to do an 8-bit transmission. Shifter 0 Shifter Control 0 Register (FLEXIO_SHIFTCTL0) = 0x00800001 TIMSEL = 0    Timer 0 select. TIMPOL = 1    Shift on negedge of Shift clock. PINCFG = 0    Shifter pin output disabled. PINSEL = 0    Shifter pin 0 select. PINPOL = 0    Pin is active high. SMOD   = 1    Receive mode. Captures the current Shifter content into the SHIFTBUF on expiration of the Timer. Shifter Configuration 0 Register (FLEXIO_SHIFTCFG0) = 0x00000000 INSRC  = 0    The input source of the shifter is from a pin. In our cause this doesn’t matter because our shifter is set as transmit mode. SSTOP  = 0    Stop bit disabled. SSTART = 0    Start bit disabled. Timer 0 Timer Configuration 0 Register (FLEXIO_TIMCFG0) = 0x01206602 TIMOUT = 1    Timer output is logic zero when enabled and is not affected by timer reset. TIMDEC = 2    Decrement counter on Pin input (both edges), Shift clock equals Pin input. TIMRST = 0    Timer never reset. TIMDIS = 6    Timer disabled on Trigger rising edge. TIMENA = 6    Timer enabled on Trigger falling edge. TSTOP  = 0    Stop bit is disabled. TSTART = 1    Start bit enabled. Timer Control 0 Register (FLEXIO_TIMCTL0) = 0x04C00103 TRGSEL = 4    Trigger select. Pin 2 input. TRGPOL = 1    Trigger active low. TRGSRC = 1    Internal trigger selected. PINCFG = 0    Timer pin output disabled. PINSEL = 1    Timer pin 1 select. PINPOL = 0    Pin is active high. TIMOD  = 3    Single 16-bit counter mode. Timer Compare 0 Register (FLEXIO_TIMCMP0) = 0x0000000F TIMCMP = 0x0000000F Configure 8-bit transfer. Set TIMCMP = (number of bits x 2) - 1. The shifter status flag is set every time the SHIFTBUF register has been loaded with data from the shifter. This occurs every time that the transmitter sends 8 bits of data. You can read the shifter status flag by polling or by enabling an interrupt based on your needs. This flag clears automatically when you read the SHITBUF register. During the transmission, the first thing that happens is that timer from the receiver will be enabled because the chip select signal from the transmitter is configured as a trigger. Once the timer is enabled, the timer will begin to decrement on the pin input, this means that the shifter clock of the receiver will be equal to the pin input. The transmitter shifter is configured to shift data out on the positive edge of the clock and the receiver shifter is configured to shift data in on the negative edge of the clock. After 8 bits have been transmitted, the compare register from the receiver will reach 0 and this generates an event to store the data from the shifter to the SHITBUF register and the Shifter Status Flag will be set. Finally the timer will be disabled by the chip select signal and keep waiting for another transaction. The hardware connections are shown in the following table. Signal name TWR-KL43Z48M transmitter TWR-KL43Z48M receiver Pin name Board Location Pin name Board Location Serial Data PTD0/FXIO0_D0 B46 PTD0/FXIO0_D0 B46 Clock PTD1/FXIO0_D1 B48 PTD1/FXIO0_D1 B48 Chip Select PTD2/FXIO0_D2 B45 PTD2/FXIO0_D2 B45 GND GND B2 GND B2 Table 1. Hardware connections Figure 8. Hardware connections The example projects for the FlexIO transmitter and receiver are developed in KDS 3.0.0 with KSDK 1.2.0. The application lets the user communicate with the transmitter via a serial terminal and the transmitter sends each character to the receiver via FlexIO and the receiver displays the received character on another serial terminal. To be able to compile the project, first you need to compile the library located in C:\Freescale\KSDK_1.2.0\lib\ksdk_platform_lib\kds\KL43Z4. Once the two TWR-KL43Z48M are connected as described above, import both projects into KDS, compile the platform library, and both projects. Open two serial terminals configured to 115200 bauds and run each project on a different tower. On the transmitter terminal you can write anything and it will be displayed and transmitted to the receiver tower via FlexIO and will be shown on the other terminal. Figure 9. FlexIO example application. Transmitter (left terminal). Receiver (Right terminal). The FlexIO module is also capable of generating a PWM signal by configuring one of its timers to the Dual 8-bit counters PWM mode. This mode is configured by writing 01 to TIMOD in the TIMCTL register. In this mode, the lower 8-bits of the counter and compare register are used to configure the high period of the timer output and the upper 8-bits are used to configure the low period of the timer output. The shifter bit count is configured using another timer or external signal. To calculate the frequency of the PWM signal you have to add the lower 8-bits of the counter and the upper 8-bits and divide it by the FlexIO clock*2 (Only if the timer is configured to decrement on the FlexIO clock.) The frequency of the PWM signal is given by: f = (FlexIO clock)/(TIMCMP[15:8]+TIMCPM[7:0]+2) To calculate the TIMCMP values to get a certain frequency you can solve the equation for TIMCMP TIMCMP[15:8]+TIMCPM[7:0] = (FlexIO clock)/f-2 For example, let’s say we want a 200kHz PWM signal, by using the formula above and using the FlexIO clock of 48MHz, we get that the sum of the TIMCMP values must be 238. If we want a 50% duty cycle we need to write the value 238/2 to the lower and upper 8 bits of the TIMCMP register. The waveform generated by these settings is shown in the figure below. Figure 10. 200kHz 50% duty cycle PWM signal To change the duty cycle you need to change the values of TIMCPM[15:8] and TIMCPM[7:0] but without changing the sum of both values, otherwise the frequency will also be altered. For example, if we need a 20% duty cycle we multiply 0.20*238 and 0.8*238. We round up the results and get TIMCPM[7:0] = 48 and TIMCPM[15:8] = 190. The waveform generated will look as shown in the figure below. Figure 11. 200kHz 20% duty cycle PWM signal
View full article
OpenSDA/OpenSDAv2 is a serial and debug adapter that is built into several Freescale evaluation boards. It provides a bridge between your computer (or other USB host) and the embedded target processor, which can be used for debugging, flash programming, and serial communication, all over a simple USB cable.   The OpenSDA hardware consists of a circuit featuring a Freescale Kinetis K20 microcontroller (MCU) with an integrated USB controller. On the software side, it implements a mass storage device bootloader which offers a quick and easy way to load OpenSDA applications such as flash programmers, run-control debug interfaces, serial to USB converters, and more. Details on OpenSDA can be found in the OpenSDA User Guide.     The bootloader and app firmware that lay on top of the original OpenSDA circuit was proprietary.  But recently ARM decided to open source their CMSIS-DAP interface, and now a truly open debug platform could be created. This new open-sourced firmware solution is known as OpenSDAv2.   OpenSDAv2: OpenSDAv2 uses the exact same hardware circuit as the original OpenSDA solution, and out of the box it still provides a debugger, drag-and-drop flash programmer, and virtual serial port over a single USB cable.   The difference is the firmware implementation: OpenSDA: Programmed with the proprietary P&E Micro developed bootloader. P&E Micro is the default debug interface app. OpenSDAv2: Programmed with the open-sourced CMSIS-DAP/mbed bootloader. CMSIS-DAP is the default debug interface app.       Firmware Developer Kinetis K20 Based Hardware Circuit Default Debug Interface Drag-and-drop Target MCU Flash Programming Virtual Serial Port Source Code Available OpenSDA P&E Micro x P&E Micro .srec/.s19 x   OpenSDAv2 ARM/mbed.org x CMSIS-DAP .bin x x   The bootloader and app firmware used by OpenSDAv2 is developed by the community at mbed.org, and is known as “CMSIS-DAP Interface Firmware”. If you explore that site, you will find that this firmware was also ported to run on other hardware, but the combination of this mbed.org firmware with the Kinetis K20 MCU is known as OpenSDAv2.   It is important to understand however that it is possible to run a P&E Micro debug app on the CMSIS-DAP/mbed bootloader found on OpenSDAv2. Likewise it is possible to run a CMSIS-DAP debug app on the P&E Micro bootloader found on OpenSDA. The debug application used needs to be targeted towards a specific bootloader though, as a single binary cannot be used on both the OpenSDA and OpenSDAv2 bootloaders.   OpenSDAv2.1: During development of OpenSDAv2 features and bug fixes, it was found that the reserved bootloader space was too small. Thus a new version of OpenSDAv2 had to be created, which was named OpenSDAv2.1. The difference between the OpenSDAv2.0 and v2.1 is the address where the debug application starts: for OpenSDAv2.0 it expects the application at address 0x5000, while OpenSDAv2.1 expects the application to start at address 0x8000.   The only board with OpenSDAv2.0 is the FRDM-K64F. All other OpenSDAv2 boards (such as the just released FRDM-K22F) use OpenSDAv2.1.   Unfortunately this means that new OpenSDAv2 apps are needed. From a user perspective this mostly affects the JLink app since it was shared across all boards. Make sure you download the correct app for your board based on the OpenSDAv2 version.   OpenSDAv2 Apps: mbed CMSIS-DAP for FRDM-K64F mbed CMSIS-DAP for FRDM-K22F P&E Micro  (use the Firmware Apps link) Segger JLink (look at bottom of page for OpenSDAv2.0 or OpenSDAv2.1 app)   OpenSDAv2 Bootloader: The key difference between OpenSDA and OpenSDAv2 is the bootloader. Boards with OpenSDA use a proprietary bootloader developed by P&E Micro, and it cannot be erased or reprogrammed by an external debugger due to the security restrictions in the firmware. Boards with OpenSDAv2 use the open-source bootloader developed by mbed.org, and it can be erased and reprogrammed with an external debugger.   Apps need to be specifically created to work with either the P&E bootloader (Original OpenSDA) or the CMSIS-DAP/mbed bootloader (OpenSDAv2/OpenSDAv2.1) as the bootloader memory map is different.  Thus it’s important to know which type of bootloader is on your board to determine which version of an app to load.   You can determine the bootloader version by holding the reset button while plugging in a USB cable into the OpenSDA USB port. A BOOTLOADER drive will appear for both OpenSDA and OpenSDAv2.   The OpenSDAv2.0 bootloader (may also be called the CMSIS-DAP/mbed bootloader) developed by mbed.org will have the following files inside.  Viewing the HTML source of the bootload.htm file with Notepad will tell you the build version, date, and git hash commit. For the OpenSDAv2.1 bootloader, this file will be named mbed.htm instead.     The OpenSDAv1 bootloader developed by P&E Micro will have the following inside. Clicking on SDA_INFO.HTM will take you to the P&E website.       Using CMSIS-DAP: When you connect a Freedom board that has OpenSDAv2 (such as the FRDM-K64F) to your computer with a USB cable, it will begin running the default CMSIS_DAP/mbed application which has three main features.   1. Drag and Drop MSD Flash Programming You will see a new disk drive appear labeled “MBED”.   You can then drag-and-drop binary (.bin) files onto the virtual hard disk to program the internal flash of the target MCU.   2.Virtual Serial Port OpenSDAv2 will also enumerate as a virtual serial port, which you can use a terminal program , such as TeraTerm (shown below), to connect to. You may need to install the mbed Windows serial port driver first before the serial port will enumerate on Windows properly. It should work without a driver for MacOS and Linux.   3. Debugging The CMSIS-DAP app also allows you to debug the target MCU via the CMSIS-DAP interface. Select the CMSIS-DAP interface in your IDE of choice, and inside the CMSIS-DAP options select the Single Wire Debug (SWD) option:   Kinetis Design Studio (KDS): Note: OpenOCD with CMSIS-DAP for FRDM-K22F is not supported in KDS V1.1.0. You must use either the P&E app instructions or the JLink app instructions to use KDS with the FRDM-K22F at this time. This will be fixed over the next few weeks. OpenSDAv2 uses the OpenOCD debug interface which uses the CMSIS-DAP protocol. Make sure '-f kinetis.cfg' is specified as 'Other Options':   IAR     Keil:         Resources CMSIS-DAP Interface Firmware mbed.org FRDM-K64 Page FRDM-K64 User Guide OpenSDAv2 on MCU on Eclipse blog OpenSDA User Guide KDS Debugging   Appendix A: Building the CMSIS-DAP Debug Application The open source CMSIS-DAP Interface Firmware app is the default app used on boards with OpenSDAv2. It provides: Debugging via the CMSIS-DAP interface Drag-and-drop flash programming Virtual Serial Port providing USB-to-Serial convertor   While binaries of this app are provided for supported boards, some developers would like to build the CMSIS-DAP debug application themselves.   This debug application can be built for either the OpenSDAv2/mbed bootloader, or for the original OpenSDA bootloader developed by P&E Micro. If you are not sure which bootloader your board has, refer to the bootloader section in this document.   Building the CMSIS-DAP debug application requires Keil MDK. You will also need to have the “Legacy Support for Cortex-M Devices” software pack installed for Keil.   You will also need Python 2.x installed. Due to the python script used, Python 3.x will not work.   The code is found in the MBED git repository, so it can be downloaded using a git clone command: “git clone https://github.com/mbedmicro/CMSIS-DAP.git” Note that there is a Download Zip option, but you will run into a issue when trying to compile that version, so you must download it via git instead.   The source code can be seen below:   This repository contains the files for both the bootloader and the CMSIS-DAP debug interface application. We will concentrate on the interface application at the moment.   Open up Keil MDK, and open up the project file located at \CMSIS-DAP\interface\mdk\k20dx128\k20dx128_interface.uvproj In the project configuration drop-down box, you will notice there are a lot of options. Since different chips may have slightly different flash programming algorithms, there is a target for each specific evaluation board. In this case, we will be building for the FRDM-K64F board. Scroll down until you get to that selection:   Notice there are three options for the K64: k20dx128_k64f_if: Used for debugging the CMSIS-DAP application with Keil. Code starts at address 0x0000_0000 k20dx128_k64_if_openSDA_bootloader: Creates a binary to drag-and-drop on the P&E developed bootloader (Original OpenSDA) k20dx128_k64_if_mbed_bootloader: Creates a binary to drag-and-drop onto the CMSIS-DAP/mbed developed bootloader (OpenSDAv2)   Since the FRDM-K64F comes with the OpenSDAv2 bootloader, we will use the 3 rd option. If we were building the mbed app for another Freedom board which had the original OpenSDA bootloader, we would choose the 2 nd option instead.   Now click on the compile icon. You may get some errors If you get an error similar to the one shown below, make sure you have installed the Legacy pack for ARM as previously described earlier:           compiling RTX_Config.c...             ..\..\Common\src\RTX_Config.c(184): error:  #5: cannot open source input file "RTX_lib.c": No such file or directory            and           compiling usb_config.c...             ..\..\..\shared\USBStack\INC\usb_lib.c(18): error:  #5: cannot open source input file "..\..\RL\USB\INC\usb.h": No such file or directory   If you get an error regarding a missing version_git.h file, make sure that Python 2.x and git are in your path. A Python build script fetches that file. It's called from the User tab in the project options, under "Run User Programs Before Build/Rebuild". If there is a warning about “invalid syntax” when running the Python script, make sure your using Python 2.x. Python 3.x will not work with the build script.   Now recompile again, and it should successfully compile. If you look now in \CMSIS-DAP\interface\mdk\k20dx128 you will see a new k20dx128_k64f_if_mbed.bin file   If you compiled the project for the OpenSDA bootloader, there would be a new k20dx128_k64f_if_openSDA.S19 file instead.   Loading the CMSIS-DAP Debug Application: Now take the Freedom board, press and hold the reset button as you plug in the USB cable. Then, drag-and-drop the .bin file (for OpenSDAv2) or .S19 file (for OpenSDA) into the BOOTLOADER drive that enumerated.   Perform a power cycle, and you should see a drive called “MBED” come up and you can start using the CMSIS-DAP debug interface, as well as drag-and-drop programming and virtual serial port as described earlier in this document.   Appendix B: Building the CMSIS-DAP Bootloader All Freedom boards already come with a bootloader pre-flashed onto the K20.  But for those building their own boards that would like to use CMSIS-DAP, or those who would like to tinker with the bootloader, it possible to flash it to the Kinetis K20 device. Flashing the bootloader will require an external debugger, such as the Keil ULink programmer or Segger JLink.   Also note that the OpenSDA/PE Micro Bootloader cannot be erased! Due to the proprietary nature of the P&E firmware used by the original OpenSDA, it can only be programmed at the board manufacturer and JTAG is disabled. So these instructions are applicable for boards with OpenSDAv2 only.   First, open up the bootloader project which is located at \CMSIS-DAP\bootloader\mdk\k20dx128\k20dx128_bootloader.uvproj   There is only one target available because all OpenSDAv2 boards will use the same bootloader firmware as the hardware circuitry is the same.   Click on the compile icon and it should compile successfully. If you see errors about a missing version_git.h file, note that Python 2.x must be in the path to run a pre-build script which fetches that file.   Now connect a Keil ULink to J10 and then insert a USB cable to provide power to J26. Note that if you have the 20-pin connector, you’ll want to use the first 10 pins.   Then for Keil 5 you will need to change some debug options (CMSIS-DAP is built under Keil 4.x).   Right click on the bootloader project, and go to the Debug tab and next to ULINK Pro Cortex Debugger, click on Settings:   Then under “Cortex-M Target Driver Setup”, change the “Connect” drop down box to “under Reset” and “Reset” dropdown box to “HW RESET”. Hit OK to save the settings.     Then in Keil, click on Flash->Erase.   And then on Flash->Download.   If you get an “Invalid ROM Table” error when flashing the CMSIS-DAP bootloader, make sure you made the changes to the debugger settings listed above.   After some text scrolls by, you should see:   Now power cycle while holding down the reset button, and you should see the bootloader drive come up. You’ll then need to drag and drop the mbed application built earlier onto it. And that’s all there is to it!   The binaries for the bootloader and CMSIS-DAP debug app for the FRDM-K64F board created in writing this guide are attached. Original Attachment has been moved to: k20dx128_bootloader.axf.zip Original Attachment has been moved to: k20dx128_k64f_mbed.bin.zip
View full article
Hello Kinetis community. Attached there is a guide on how to modify an existing KDS project to be loaded using the KBOOT Flash Resident bootloader. Basically it explains 2 procedures: 1- Manipulating linker file to move application and vectors. 2- Adding data for the Bootloader Configuration Area (BCA). I am also including 3 adapted KDS v3.0.0 example projects ready to be used with KBOOT Flash Resident bootloader in a FRDM-K22F: - Baremetal project. - KSDK project. - KSDK project with Processor Expert support. The application simply toggles the red, green and blue LEDs sequentially. I hope you find the document and projects useful! Regards! Jorge Gonzalez
View full article
Hi All Kinetis Lovers, Microcontroller programming is a passion for all we are following this Community, but sometimes, trying to understand the peripherals of a Microcontroller is not an easy task, especially if we are in our first approach to a new module or device. In this post you will find a document that explains in detail the DMA module for Kinetis devices and also some examples for CodeWarrior and Kinetis Design Studio using DMA and other peripherals. The Documentation found here is: Using DMA module in Kinetis devices (complete): Document that includes DMA module explanation: everything you need to know when using DMA and the necessary information to understand the code included (K20_DMA for CW or K20D72_DMA for KDS). Using DMA module in Kinetis devices (example): Document that includes the necessary information to understand the code included (K20_DMA for CW or K20D72_DMA for KDS). Attached are two folders named: DMA examples for CW: include the DMA example projects for CW DMA examples for KDS: include the DMA example projects for KDS. Each folder includes 5 examples that are: Please feel free to modify the examples; I hope this will be useful for you. Many thanks and credits to manuelrodriguez for his valuable help developing and editing this project. :smileyinfo:For the SPI examples it is necessary to make a bridge between MOSI and MISO pins (master loop mode is used for the example). For this the TWR Elevators were used.     In the attachments you can find some extra information when using SPI and DMA. Best Regards, Adrian Sanchez Cano Technical Support Engineer
View full article
@@This article describes how to do in-system reprogramming of Kinetis for Cortex-M4 core devices using standard communication media such as SCI. Most of the codes are written in C so that make it easy to migrate to other MCUs. The solution has been adopted by customers. This bootloader is based on FRDM-K22 demo board and KDS3.0. The bootloader and user application source codes are provided. GUI is also provided. Customer can make their own bootloader applications based on them. The application can be used to upgrade single target board and multi boards connected through networks such as RS485. The bootloader application checks the availability of the nodes between the input address range, and upgrades firmware nodes one by one automatically. Key features of the bootloader: Able to update (or just verify) multiple devices in a network. Application code and bootloader code are in separated projects, convenient for mass production and firmware upgrading. Bootloader code size is small, only around 3k, which reduces on chip memory resources. Source code available, easy for reading and migrating. For Cortex-M0+ products, please refer to here :Kinetis Bootloader to Update Multiple Devices in a Network - for Cortex-M0+ , it based on FRDM-KL26. The main difference between Cortex-M4 and Cortex-M0+ is the FLASH program routine. - In Cotex-M4 core kinetis, we need copy the Flash operating routines to RAM. In the bootloader code, the copy to ram code is realized in the function of “FLASH_Initialization()”: Byte buffer[200]={0}; - In Cotex M0+ core kinetis, we do not need to copy the Flash operating routines to RAM. Platform Control Register (MCM_PLACR) is added. The MCM_PLACR register selects the arbitration policy for the crossbar masters and configures the flash memory controller. Enabling ESFC bit can stall flash controller when flash is busy.  Setting ESFC bit can well-balance time sequence of Flash reading and writing – when writing Flash, reading Flash instruction can wait, and vice versa. Using ESFC bit can make our flash programming easier. Thus one Flash can write itself, which is not possible for other one Flash MCU without ESFC bit control. ESFC bit is easy to be set in C code: For more information, please see attached document and code. User can also download the document and source code from Github: https://github.com/jenniezhjun/Kinetis-Bootloader.git
View full article
This document was created in collaboration with Dragos Musoiu Trying to debug a hard fault on MKW24D512, ARM Cortex M4 based microcontroller, we did not find too much documentation on working with IMPRECISE hard faults.  We started our investigation from the post of Erich Styger Debugging Hard Faults on ARM Cortex-M. Based on this, we used Erich’s code to find the hard fault source, but it was impossible to find the instruction that caused the hard fault, because the executed instructions around the saved PC looked to be correct.  After, we checked the Hard Fault Status Register, from the System Control Block of the ARM Cortex M4 processor, we found the FORCED bit set. The ARM Cortex M4 documentation mentions that this bit indicates a forced hard fault, generated by escalation of a fault with configurable priority that cannot be handled, either because of priority or because it is disabled. When this bit is set to 1, the HardFault handler must read the other fault status registers to find the cause of the fault. We checked the other fault registers and we found, in the Configurable Fault Status Register (Bus Fault Status Register) from the System Control Block of the ARM Cortex M4 processor, the IMPRECISERR bit set. According to the ARM Cortex M4 documentation, if this bit is set a data bus error has occurred, but the return address in the stack frame is not related to the instruction that caused the error. When the processor sets this bit to 1, it does not write a fault address to the BFAR. So that explained why we did not find the instruction that caused the hard fault using Erich’s indications. Also, this is an asynchronous fault. Therefore, if it is detected when the priority of the current process is higher than the BusFault priority, the BusFault becomes pending and becomes active only when the processor returns from all higher priority processes. The Cortex M4 processors have a write buffer feature that when a write is carried out to a bufferable memory region, the processor can proceed to the next instruction before the transfer is completed. This is great for performance, but can cause some complexity in debugging imprecise bus faults. Studying better the documentation, we found in the ARM Cortex M4 Auxiliary Control Register the DISDEFWBUF bit that when set to 1, disables write buffer use during default memory map accesses. This causes all BusFaults to be precise BusFaults but decreases performance because any store to memory must complete before the processor can execute the next instruction. In this way the processor will not continue executing the next instruction until the write operation is completed, and so enabling this bit and using Erich’s code the saved PC pointed to the instruction which caused the hard fault. In other case, if the Bus Fault is triggered by an instruction executed in an interrupt handler, with higher priority than the BusFault handler, setting the DISDEFWBUF can be useful in the debugging process because the BFAR register value remains valid in case of precise error.
View full article
Status: Text content finished, to be updated with more diagrams/images. Foreword First of all. I have to say sorry for my English since I am not a native speaker. This is my personal experience of using AN2295 on FRDM-KL25Z. I want to share it with anyone who is suffering on it, since the existing release from FSL has not been fully tested on FRDM-KL25Z. (I can figure it out in many ways.) Components and Documents The lastest microcontrollers always have some kind of bootloader to download user code to the flash memory. FSL does offer many bootloaders for various mcu families. Among them, AN2295 bootloader is general purpose for most of these families, since it only requires an UART, either hardware or software UART. To make AN2295 work for a system, the developer must have three components: AN2295 bootloader running on target MCU, such as MKL25Z128VLK4 on FRDM-KL25Z. AN2295 bootloader PC software, such as win_hc08sprg, or my Python script, FcBootloaderProgrammer.py AN2295 aware user application, which has different start address and special treatment for interrupt vector. UPDATE Add an2295_programmer_v1.zip for Python source code, you need install PySerial module for Python 2.5. Please visit following URLs to download necessary files: http://www.freescale.com/files/microcontrollers/doc/app_note/AN2295.pdf http://cache.freescale.com/files/32bit/doc/app_note/AN4767.pdf Software for AN2295 AN4767: UART Boot Loader Design on the Kinetis E Series, a more detail application note for AN2295 on E series. Updates for AN2295 on IAR 6.5 The released AN2295 has to be updated before downloading into FRDM. When you open the AN2295_Kinetis project in IAREW, please update the following setup items in IDE. In workspace window, switch to Kinetis L Debug configuration. Right click on AN2295_Kinetis and open Options. Click on Debugger category. In Setup tab, select PE micro in driver, disable Run to options. (The release leaves it as simulator, and run to __main, which makes warning report when you downloading code to debugger) In Download tab, enable Verify download, Use flash loader, Override default .board file, with $TOOLKIT_DIR$\config\flashloader\Freescale\FlashKLxx128K.board . Disable Attach to program. In PE micro, select interface type as OpenSDA - USB In Tools|Options (IDE Options)|stack, you can leave Stack points not valid until program reaches as blank (Optional). In AN2295_LinkerFile.icf, change IntVectTable_end__ from 0x0000003f to 0x000003FF (Optional). In bootloader_cfg.h, enable AN2295_FRDM_KL25Z_cfg.h, comment out AN2295_TWR_KL25Z_cfg In AN2295_FRDM_KL25Z_cfg.h, #define BOOT_UART_BAUD_RATE 57600 Add gpio.h/gpio.c to project, in case you want use them to indicate something. We can conclude a fact that AN2295 is good enough as a bootloader as it has been tested on many MCU families. The source code is open, so you can custom it for your own specific purposes. However, you have to do it yourself. The reason why I change baudrate is I found VCP of OpenSDA will decode 0x00 send from KL25Z as 0x80. So I slow down to 57600. Updates for PC software of AN2295 Unfortunately, The released (10.0.12.0) and updated (10.0.16.0) versions of bootloader PC software don't work with my bootloader. The released PC software of AN2295 is open source as well. However I am not fan for VC++. I prefer to make my own programmer software with Python, as knows as a clue language. The programmer software is released in Windows exe format and works in command line prompt. The user don't bother to install Python/PySerial and other components. The programmer software works in a simple single shot mode, blank/erase/program actions. D:\an2295_programmer>FcBootloaderProgrammer --help ################################################## FC Booloader Programmer v0.1-alpha - An alternative to Freescale AN2295 on FRDM-KL25Z   by Allan K Liu (C)2013 Ennovation LLC ################################################## Usage: -h, --help      :       This help information -p, --port      :       Serial port setting in Windows, like COMxx, depends on your VCP installation -b, --baudrate  :       Baud rate setup from 9600/19200/38400/57600/152000 -f, --file      :       Hex file (Motorola SREC or Intel HEX) -a, --action    :       Action [blank/erase/program] -d, --debug     :       Debug [0:1]    In order to make it simpler, I prepare some DOS batch files. blank.bat FcBootloaderProgrammer --port=COM14 --baudrate=57600 --debug=1 --action=blank erase.bat FcBootloaderProgrammer --port=COM14 --baudrate=57600 --debug=1 --action=erase program.bat FcBootloaderProgrammer --port=COM14 --baudrate=57600 --debug=1 --action=program --file=DemoApp_4_FC_Bootloader_freedom.srec You can disable debug output optionally. Updates for Demo projects for AN2295 on IAR6.5 In order to run a user application with AN2295 bootloader, you have to rebuild it with modified linker script. You can generate a new app based upon Kinetis L Sample Codeby following steps. Run make_new_project.exe under Kinetis L Sample Code\kl25_sc_rev5\klxx-sc-baremetal\build\iar\ Offer a new project name "DemoApp_4_FC_Bootloader_freedom" according to prompt. Open it in IAR IDE. Change project linker options, enable Override default with $PROJ_DIR$\..\config files\Pflash_32KB_AN2295.icf, the modified linker file. The major changes are: define symbol __ICFEDIT_region_ROM_start__ = 0x00001000; define symbol __ICFEDIT_region_ROM_end__   = 32*1024; define exported symbol __VECTOR_TABLE      = 0x00001000; define symbol __code_start__ = 0x00001410; After building the project, we can get similiar srec file, which has start address at 0x1000. S027000044656D6F4170705F345F46435F426F6F746C6F616465725F66726565646F6D2E7372656331 S1131000F80B0020111400002929000029290000F0 S11310102929000029290000292900002929000084 ...... S1132B200A0D4B4C300000000A0D4B4C31000000E4 S1132B300A0D4B4C320000000A0D4B4C33000000D0 S10B2B400A0D4B4C34000000A7 S9032B0DC4 According to SREC file format, its filename: DemoApp_4_FC_Bootloader_freedom.srec. And it ranges from 0x1000 to 0x1B47 Finally, run "erase.bat", then "blank.bat", then "program.bat" Simple! Other Useful Tools During my development for AN2295, I used some other tools, especially PC terminal to monitor events/traffics on RS232/UART. Future Development Here are my plan. More images for step on step. Smart detection for OpenSDA VCP port. Mutli-thread GUI for bootloader tool. More labs to reduce unnecessary empty flash space on VECTOR_TABLE and flash_protection_table in user application. Support cryptographic/authentication in bootloader to support licenses.
View full article
Hi community!! The following example uses a PIT to start an adc conversion, once the conversion has finished it issues a DMA request and the DMA controller stores the converted value in a buffer. The examples were implemented in both CodeWarrior 10.6 and KDS 1.1 for every board. The recommended test circuit is the following: Please feel free to modify the files, I hope this examples will be useful for you and will help you by decreasing your development time. Best Regards Manuel Rodríguez Technical Information Center Intern
View full article
1. How Calibration works There are three main sub-blocks important in understanding how the Kinetis SAR module works.  There is a capacitive DAC, a comparator, and the SAR engine that controls the module. Of those blocks, the DAC is most susceptible to variations that can cause linearity problems in the SAR. The DAC is architected with three sets of binary weighted capacitors arrayed in banks, as in Figure 1. The capacitors that represent the most significant bits of the SAR (B15:B11) are connected directly to the inputs of the comparator. The next bank of five capacitors (B10:B6) is connected to the top plate of the MSB array through an intentionally oversized scaling capacitor. The final six capacitors that makeup the least significant bits of the SAR (B5:B0) are correspondingly connected to the top plate of the middle bank of capacitors through another scaling capacitor. Figure 1. Arrangement of DAC capacitors Only the MSB capacitor bank is calibrated. Because the first scaling capacitor is intentionally oversized, each of the non-calibrated MSB capacitors will have an effective capacitance too small to yield accurate results. However, because they are always too small, we can measure the amount oferror that each of those capacitors would cause individually, and add that back in to the result. Calibration starts with the smallest of the LSB capacitors, B11. The SAR samples Vrefl on all of the capacitors that are lower-than or equal-to the capacitor under test (CUT), while connecting all of the smaller capacitors to Vrefh. The top plate of all of the MSB capacitors is held at VDDA while this happens. After the sampling phase is complete, the top plates of the MSB capacitors are allowed to float, and the bottom plates of the MSBs not under test are connected to Vrefl. This allows charge to redistribute from the CUT to the smaller capacitors. Finally, an 11 bit SAR algorithm (corresponding with the 11 capacitors that are smaller than the MSB array) is performed which produces a result that indicates the amount of error that the CUT has compared to an ideally sized capacitor. This process is repeated for each of the five MSBs on both the plus side and minus side DACs and the five error values that are reported correspond to the five MSBs accordingly. All of these error values are about the same magnitude, with a unit of 16-bit LSBs. See Figure 2 for an example. Figure 2. Example of calibration on bit 11 The DAC MSB error is cumulative. That is, if bit 11 of the DAC is set, then the error is simply the error of that bit. However if bit 12 of the DAC is set, the total error is equivalent tothe error reported on bit 12, plus the error reported on bit 11. For each MSB the error is calculated as below, where Ex is the error found during the calibration for its corresponding MSB bit: When bit 11 of the DAC is set: CLx0 = E0. When bit 12 of the DAC is set: CLx1 = E0+E1. When bit 13 of the DAC is set: CLx2 = E2 + E1 + 2E0. When bit 14 of the DAC is set: CLx3 = E3 + E2 + 2E1 + 4E0. When bit 15 of the DAC is set: CLx4 = E4 + 2E3 + 4E2 + 8E1 + 16E0 Figure 3. Effect of calibration error on ADC response These are the values that are then placed in each of the CLxx calibration results registers. Figure 3 shows how the errors would accumulate if all of the CLxx registers were set to zero. The offset and gain registers are calculated based on these values as well. Because of this, the gain and offset registers calibrate only for errors internal to the SAR itself. Self calibration does not compensate for board or system level gain or offset issues. 2. Recommended Calibration Procedure From the above description it is evident that the calibration procedure is in effect several consecutive analog to digital conversions. These are susceptible to all of the same sources of error of any ADC conversion. Because what is primarily being measured is the error in the size of the MSB capacitors; the recommendation is to configure the SAR in such a way as to make for the most accurate conversions possible in the environment that the SAR is being calibrated in. Noise is the primary cause of run-to-run variation in this process,so steps should be taken to reduce the impact of noise during the calibration process. Such as: All digital IO should be silent and unnecessary modules should be disabled. The Vrefh should be as stable and high a voltage as possible, since higher Vrefh means larger ADC code widths. An isolated Vrefh pin would be ideal. Lacking that, using an isolated VDDA as the reference would be preferable to using VREFO. The clock used should be as noise free as possible, and less than or equal to 6 MHz. For this purpose the order of desirable clock sources for calibration would be OSC > PLL > FLL > ASYNC The hardware averaging should be set to the maximum 32 samples. The Low Power Conversion bit should be set to 0. The calibration should be done at room temperature. The High Speed Conversion and Sample Time Adder will not have much effect in most situations, and the Diff and Mode bits are completely ignored by the calibration routine. The calibration values should be taken for each instance of the SAR on a chip in the above conditions. They should be stored in nonvolatile memory and then written into their appropriate registers whenever the ADC register values are cleared. In some instances, the system noise present will still cause the calibration routine to exhibit greater than desired run-to-run variation. One rule of thumb would be to repeat calibration several times and look at the CLx0 registers. If the value reported in that register varies by more than three, the following procedure can be implemented. Run the calibration routine several times. Twenty to forty times. Place the value of each of the calibration registers into a corresponding array. Perform a bubble sort on each array and find the median value for each of the calibration registers. Use  these median values as described for typical calibration results.
View full article
What is it KSDK? = Kinetis Software Development Kit Kinetis SDK v2 is a collection of comprehensive software enablement for NXP Kinetis Microcontrollers that includes: •system startup •peripheral drivers •USB and connectivity stacks •Middleware •Real-time operating system (RTOS) kernels. Documents – Release Note, API Reference Manual, Getting Started with KSDK, for USB – User Guide, USB Composite Device Guide, USB Device Reference Manual and USB Host Reference Manual. All these documents is possible to find at Software Development Kit for Kinetis MCUs|NXP or <ksdk_path>\SDK_2.0_selected_device\docs KSDK Structure Diagram KSDK Features •ARM® and DSP standard libraries, and CMSIS-compliant device header files which provide direct access to the peripheral registers •Open-source peripheral drivers •Open-source RTOS wrapper driver •Real time operation systems (RTOS) including FreeRTOS OS, μC/OS-II, and μC/OS-III •Stacks and middleware in source or object formats including: − CMSIS-DSP -  a suite of common signal processing functions − FatFs - a FatFile System for small embedded systems − mmCAU - Memory-Mapped Cryptographic Acceleration Unit − SDMMC - software component supporting SD Cards and eMMC − DMA Manager - software component used for managing on-chip DMA channel resources − mbedTLS and WolfSSL - cryptographic SSL/TLS libraries − lwIP and USB Stack - a light-weight TCP/IP stack KSDK Evolution KSDK v1/v2 – what new features KSDK 2.0 brings •MQX Kernel removed from KSDK -> focus on FreeRTOS •MQX RTCS Ethernet and MFS File System Stacks -> lwIP and FatFS •OSA, Power Manager and Clock Manager -> no longer required by the drivers •USB Stack re-write -> BSD licensed solution •No platform library -> single project with all needed files •Mbed TLS now included as part of the accelerated cryptography drivers •Eliminates separate HAL and Peripheral Driver -> single driver for each peripheral •Processor Expert -> Kinetis Expert Tool •Updates for KDS -> via online update tool •Installation of KSDK -> KEX Tool (smaller download & sizes) •KEX Tool -> pin muxing selection & generation, clock configuration, low power estimation Simplified folder structure KSDK highlights & benefits •Collection of software enablement offered by free •KSDK is fully supported in these IDE: − Atollic® TrueSTUDIO® − GNU toolchain for ARM® Cortex® -M with CMake build system − IAR Embedded Workbench − Keil™ MDK-ARM − Kinetis Design Studio IDE •KSDK supports most of Kinetis MCUs •Created examples for drivers, USB, RTOS, demo applications •Start with development without device register knowledge Support & download Official support of KSDK: Kinetis Software Development Kit Create new SR according to: How to submit a new question for NXP Support More about KSDK... KSDK Official Website www.nxp.com/ksdk Introducing Kinetis SDK v2 https://community.freescale.com/docs/DOC-329783 Kinetis SDK 2.0 Transition Guide Kinetis SDK 2.0 Transition Guide KSDK Community https://community.freescale.com/community/kinetis/kinetis-software-development-kit Let´s continue in reading! See Let´s start with FreeMASTER!​
View full article
Revise History: Version 23: NXP kinetis bootloader GUI upgrade from v1.0 to v1.1: added 04 extended linear address record  and 02 sector address record processing for hex format. This article describes how to do in-system reprogramming of Kinetis devices using standard communication media such as SCI. Most of the codes are written in C so that make it easy to migrate to other MCUs. The solution has been already adopted by customers. The pdf document is based on FRDM-KL26 demo board and Codewarrior 10.6.  The bootloader and user application source codes are provided. GUI and video show are also provided. Now the bootloader source code is ported to KDS3.0, Keil5.15 and IAR7.40 which are also enclosed in the SW package. Customer can make their own bootloader applications based on them. The application can be used to upgrade single target board and multi boards connected through networks such as RS485. The bootloader application checks the availability of the nodes between the input address range, and upgrades firmware nodes one by one automatically. ​ Key features of the bootloader: Able to update (or just verify) either single or multiple devices in a network. Application code and bootloader code are in separated projects, convenient for mass production and firmware upgrading. Bootloader code size is small, only around 2K, which reduces the requirement of on chip memory resources. Source code available, easy for reading and migrating. GUI supports S19,HEX and BIN format burning images. For more information, please see attached document and code. The attached demo code is for KL26 which is Cortex - M0+ core. For Cortex-M4 core demo, refer this url: https://community.freescale.com/docs/DOC-328365 User can also download the document and source code from Github: https://github.com/jenniezhjun/Kinetis-Bootloader.git Thanks for the great support from Chaohui Guo and his team. NOTE: The bootloader and GUI code are all open source, users can revise them based on your own requirement. Enjoy Bootloader programming 🙂
View full article
One of the new features that can be found on the FRDM-K82F is the FlexIO header. It’s be specifically designed to interface with the very cost-efficient OV7670 camera, and uses 8 FlexIO lines to read data from the camera. By using the FlexIO feature, it makes it easy to connect a camera to a Kinetis MCU. A demo is included with Kinetis SDK 1.3 which streams the video data from the camera to a host computer over USB. FlexIO: The FlexIO is a highly configurable module found on select Kinetis devices which provides a wide range of functionality including: • Emulation of a variety of serial/parallel communication protocols • Flexible 16-bit timers with support for a variety of trigger, reset, enable and disable conditions • Programmable logic blocks allowing the implementation of digital logic functions on-chip and configurable interaction of internal and external modules • Programmable state machine for offloading basic system control functions from CPU All with less overhead than software bit-banging, while allowing for more flexibility than dedicated IP. Running the Demo: First you’ll need to setup the hardware. An 18 pin header needs to be installed on the *back* of the board. The camera is oriented this way to allow for use of shields on the top, even if the camera is being used. This way the functionality could be extended with WiFi or LCD shields. After the header is soldered on, plug in the camera. It will look like the following when complete: Next we need to program the K82 device with the example firmware. The software can be found in the Kinetis SDK FRDM-K82F stand-alone release, in the C:\Freescale\KSDK_1.3.0_K82\examples\frdmk82f\demo_apps\usb\device\video\flexio_ov7670 folder. Open the project, compile, and program the example specific for your compiler like done for other examples. Make sure you also compile the USB Device library as well. After programming the K82, unplug the USB cable from J5 (OpenSDA) and plug it into J11 (K82 USB). The board will enumerate as a generic USB video device called “USB VIDEO DEMO”. You can then use this device with any video capture software, like Skype or Lync.  Here's a shot of the clock in my cube: The resolution is 160*120, the video image format is RGB565. You may need to manually adjust the focus by rotating the lens on the camera. The frame rate can also be sped up by modifying line 342 in usb_descriptor.c: 5fps: 0x80,0x84,0x1E,0x00, /* Default frame interval is 5fps */ 10fps:  0x40,0x42,0x0F,0x00, 15fps:  0x2A,0x2C,0x0A,0x00, 20fps:  0x20,0xA1,0x07,0x00, The 160*120 max resolution was determined by the amount internal SRAM of the device, as there is not external RAM on the FRDM-K82F board. More Information: One of many places to buy the OV7670 camera module​ OV7670 Reference Manual​ FlexIO Overview ​ FlexIO Training presented at FTF
View full article
For Remote Control means, that is needed two computers - Server Computer and User Computer, which will be in connection. There are two types of connection, which can be used - HTTP or DCOM. There are two different ways how to set up the remote control in Windows. I made the tutorial, which describes both types of Remote Control. Ok - so, let´s start! HTTP Settings On the Server Computer side: 1. Plug the board to the Server Computer 2. Go to Remote Communication Server 3. Set HTTP connection and choose the right COM Port according the plugged board If the plugged board is on e.g. COM23, it is possible to edit number of Port in Device Manager On the User PC side: 1. Open FreeMASTER,  go to Project -> Options 2. Choose Plug-in Module: FreeMASTER CommPlugin for Remote Server (HTTP) and type the IP address of the server, do not forget join to IP address :8080 3. And start communication by STOP button to successful connection DCOM Settings On the Server Computer side: 1. Plug board to the Server Computer 2. Launch DCOM in FreeMASTER Remote Server Choose COM according plugged board or edit COM according to step 2 - Server Computer in HTTP Connection (up). 3. Setting permissions for the user, User PC. Right click on Computer -> Manage. In Computer Management click to Distributed COM Users. In Distributed COM Users Properties add the user, User Computer. After that, set the permissions in Component Services. In cmd type dcomcnfg.exe In Component Services go to Computers -> My Computer -> DCOM Config -> MCB FreeMASTER Remote Server Application Right click on MCB FreeMASTER Remote Server Application and go to Properties. In Security Tab is possible to add the permissions. There are 3 types of permissions. First permission - Launch and Activation Permissions. There are 4 permission options. Local Launch and Remote Launch means, that user, User Computer can launch e.g. FM Remote Server Application. But for success communication is needed allowing Local Activation and Remote Activation. Second permission - Access Permissions. Click to Edit and Allow Local Access and Remote Access for the user. Do not forget that if there is a change of permissions, specifically allowing, it is necessary for User to log out and log in. On the User Computer side: 1. Open Freemaster, go to Project -> Options 2. Choose Plug-in Module: FreeMASTER CommPlugin for Remote Server (DCOM) and for filling Connect string is possible to use Configure. Definitely, type the IP address of the server and ;Port Name. 3. And start communication by STOP button in FreeMASTER to successful connection And now.. you can do anything 🙂
View full article
Introduction This document is being written to communicate the need for serialization of memory operations and events in an end application.  In addition, directions will be provided to properly serialize memory operations in the end application.  Memory operations and event serialization applies to all Kinetis devices but is only necessary in specific scenarios. These scenarios include memory writes and reads, clearing status flags, and changing mode control operations. Serialization of memory operations Serialization of memory operations or events is the action of guaranteeing that said memory operations or events are executed in a specific order.  This action is required when making a change to a peripheral module when that change must complete before continuing with program execution.  Users often make the mistake of assuming that since a peripheral register has been written to, the change is in effect immediately.  However, this is not always the case.  The Kinetis series devices implement a crossbar and peripheral bridge interface system that allows masters (the CPU, DMA, etc.) to interface with the peripherals.  The crossbar allows multiple masters to access the individual peripherals on the bus, and the peripheral bridge functions as a bus protocol translator between the crossbar switch and the slave peripheral bus.  Wait states can be inserted at either stage of the communication channel (crossbar or peripheral bridge).  When a master attempts to access a slave and another master is already accessing this slave or the slave is busy, wait states will be inserted.  If the access is a write, then the master's write is simply pushed to the peripheral bus and the master continues.  However, if the access is a read, the master must wait for a response from the slave.  The slave may insert wait states in this communication as it must finish any commands (or writes) it was previously given before responding.    Peripheral module changes that require serialization actions include clearing interrupt service flags, changing power modes (of the module or the SOC as a whole), or software triggering a hardware event.  If the events or memory operations are not serialized in these situations, the CPU could go on to execute code with undesired effects. When do I need to serialize my memory operations and events? Memory operations and events require serialization anytime the program needs to guarantee that a peripheral access happens before code execution continues.  Examples of these situations includes: Exiting an interrupt service routine (ISR) Changing a clock mode or power mode Configuring a function Configuring a hardware change Software triggering a hardware event How do I serialize my memory operations and events? Memory operations are serialized by performing the following operations: Write the desired peripheral register Read the peripheral register that was just written Continue with the subsequent operations By simply reading the register that was just written, the core is forced to wait for a response from the peripheral module that was written before code execution can continue.   In this manner, it is guaranteed that the peripheral module will have completed the desired operations. Example event serialization The following is an example of a function that services the LPTMR ISR flag and implements the event serialization discussed in this document.  void lptmr_isr(void) {   // Declare dummy variable to store the read of the LPTMR0_CSR register volatile int dummy_var; /****   STEP #1  ****/   // Clear the flag; enable interrupts; enable the timer   LPTMR0_CSR = ( LPTMR_CSR_TEN_MASK | LPTMR_CSR_TIE_MASK | LPTMR_CSR_TCF_MASK  );   /****  STEP #2  ****/    // Store CSR register in dummy_var to serialize the clearing of the TCF flag   dummy_var = LPTMR0_CSR; } Conclusion In conclusion, there are situations where code execution can continue before a peripheral change has taken effect. These situations include clearing interrupt service flags, changing power modes (of the module or the SOC as a whole), or software triggering a hardware event.  Sometimes these events can cause unexpected results or even cause your application to crash.  These situations call for the serialization of memory operations and events, which is simply the act of guaranteeing that events and code are executed in a specific order.  To serialize memory operations, simply follow these directions: Write the desired peripheral register Read the peripheral register that was just written Continue with the subsequent operations Following these steps, you will be guaranteed that peripheral configurations have taken effect before continuing with the application. 
View full article
客户要求:K60 100MHz芯片作为SPI主机读取片外SPI Flash存储器内容(SPI Flash器件数据准备完成会触发K60 GPIO中断),要求在130~150微秒之间读取九个不连续地址上的数据,每个地址需要读取4个字节,SPI波特率为5MHz。读取SPI Flash存储器,需要使用读取命令(1个字节)外加地址(2个字节)。换言之,每读取一次K60需要发送7个字节(1字节读取命令+2字节地址+4字节空读数据)。同时要求减少内核负担。 Customer requirement: Use K60 100MHz product as SPI master communicate with external SPI Flash device (When data ready, SPI Flash device will trigger K60 GPIO interrupt), it need to read data from 9 discontinuous address, each address read 4 bytes within 130~150us. SPI  baud rate is 5MHz. Read data from SPI Flash, it need SPI master send 1byte read command and 2bytes address. In another word, K60 need to send 7bytes(1byte read command+2bytes address+4bytes dummy read) 9times within 130us. SPI communication baud rate is 5MHz. It also require to reduce core work load. 实现方法:使用DMA模块,其中一个DMA通道1用来装载SPI传输TX数据(触发源为SPI TFFF符号,SPI FIFO可装载),另外一个DMA通道0用来接收SPI数据(触发源为SPI RFDF符号,SPI 接收FIFO非空)。通过使用DMA引擎可以自动发起SPI传输,减少内核在SPI传输过程中的干预,达到降低内核工作负荷的效果。SPI模块采用中断方式。 Reality way: Use DMA module, DMA CH0 loads data for SPI transmit, DMA CH1 stores data for SPI receive.  DMA triggered by SPI module and SPI module works in interrupt way. 测试平台:TWR-K60D100M, TWR-MEM, IAR ARM Workbench V6.60 TWR-MEM板子提供SPI Flash设备(AT26DF081A),可以通过TWR-K60D100M SPI2模块进行访问。 Test platform: TWR-K60D100M ,TWR-MEM , IAR ARM Workbench V6.60 SPI Flash AT26DF081A on TWR-MEM board, which could be accessed by TWR-K60D100M via SPI2 module. 测试场景一:读取AT26DF081A设备ID信息 Test scenario 1:  Read device ID AT26DF081A设备提供查询设备ID命令0x9F,返回4个字节设备ID信息(0x1F,0x45,0x01,0x00)。K60作为SPI主机发出查询命令,之后执行4次空写入操作用来读出设备ID信息。测试中SPI传输/接收数据帧大小设定为1个字节(8bit)。由于DSPI模块传输接收均提供4级FIFO,测试中使用两种方式进行SPI数据发送,一种方式使用DMA通道发送读取设备ID查询命令和4次空写入数据,另一种方式通过执行代码(需要内核干预)发送读取设备ID查询命令和4次空写入数据。SPI数据接收均使用DMA完成。为了便于测试使用DMA模块是否降低内核负荷,在DSPI通信同时,主程序在While循环中不停翻转GPIO引脚(PTD7)。 SPI Flash AT26DF081A provides read device ID command(0x9f), will feedback 4 bytes device ID info(0x1F,0x45,0x01,0x00)。K60 works as SPI master send read ID command, then send 4 dummy write data to read back device ID info. During test, SPI data frame size setting to 1byte(8 bit). For DSPI module TX/RX FIFO is 4 entries, so there using two ways do SPI data transfer, one is using DMA CH1 send data, the other way using software code send data. SPI RX using DMA CH0 and in main while loop it will toggle PTD7 pin to show if using DMA module will reduce core work load. 测试流程图(方法一: 使用DMA CH1发送SPI数据): Test flow chart (Way1: Using DMA CH1 do SPI TX): 测试结果(Test Result): 执行一次读ID信息操作,需要花费12.96us,其中内核处理中断的时间为(2.56+2.72)= 5.28us。 根据客户要求,依照此方法每次发送3个字节,接收4个字节,SPI通信过程中内核负荷时间比率为 (5.28/16.16) =32.7% SPI read ID operation once, it will take 12.96us, includes core deal with interrupt time 5.28us. According to this way, customer want to TX 3bytes then RX 4bytes, during SPI communication core work load rate is 32.7% 测试流程图(方法二: 使用软件代码发送SPI数据): Test flow chart (Way2: Using software code do SPI TX): 测试结果(Test Result): 执行一次读ID信息操作,需要花费11.6us,其中内核处理中断的时间为(2.48+1.40)= 3.88us。 根据客户要求,依照此方法每次发送3个字节,接收4个字节,SPI通信过程中内核负荷时间比率为 (3.88/14.80) =26.2% SPI read ID operation once, it will take 11.6us, includes core deal with interrupt time 3.88us. According to this way, customer want to TX 3bytes then RX 4bytes, during SPI communication core work load rate is 26.2% 测试场景二:读取AT26DF081A设备9处不连续地址数据 Test scenario 2: Read 9 discontinue address data from AT26DF081A AT26DF081A设备提供读阵列命令(0x0B),可以连续读取多个字节数据。根据客户要求,测试读取9处不连续地址数据,每处读取4个字节。根据AT26DF081A设备要求,读阵列命令后需要再发送3个字节地址信息外加1个字节空写入数据,之后K60将会收到数据。即如果要读取4个字节数据,K60作为SPI主机需要发送9个字节数据(1个字节读阵列命令+3个字节地址+1个字节空写入+4个字节空写入)。测试中使用两个DMA通道进行SPI数据收发,两个DMA通道交替工作,DMA通道0(SPI接收)优先级高于DMA通道1(SPI发送)。完成9处数据采集后进入SPI中断,清除EOQ标志并且修正DMA通道配置,进行新的一轮9处数据读取测试。为了便于测试使用DMA模块是否降低内核负荷,在DSPI通信同时,主程序在While循环中不停翻转GPIO引脚(PTD7)。 SPI Flash AT26DF081A provides read array command (0x0B) to sequentially read a continuous stream of data out. With customer requirement, the test will read 9 discontinue address data, each address read 4 bytes data. AT26DF081A datasheet shows read array command with 3 bytes address and 1 dummy byte, then following will be data. In order to read 4 bytes data out, K60 as SPI master need TX 9 bytes data (1byte read array command + 3bytes address + 1byte dummy data + 4bytes dummy data). During the test, it using two DMA channels do SPI TX/RX, each channel alternatively work, DMA CH0(SPI RX) with higher priority than DMA CH1(SPI TX). When finish 9 discontinue address data receive, it will clear EOQ flag and refresh DMA CH0/1 setting in SPI interrupt for next round read 9 discontinue address data test. In main while loop it will toggle PTD7 pin to show if using DMA module will reduce core work load. 测试流程图(Test flow chart): 测试结果(Test Result): 读取AT26DF081A设备9处不连续地址数据,需要花费132.32us,其中内核处理中断的时间为2.6us。 根据客户要求,依照此方法每次发送3个字节,接收4个字节,重复9次。SPI通信过程中内核负荷时间比率为 (2.6/103.52) =2.5% SPI read ID operation once, it will take  132.32us , includes core deal with interrupt time 2.6us. According to this way, customer want to TX 3bytes then RX 4bytes, 9times,during SPI communication core work load rate is 2.5% DMA模块提供动态加载DMA传输控制描述符(TCD)功能,当需要连续多次执行SPI传输时,使用这种功能可以进一步减少内核负荷。 DMA module provides dynamic scatter/gather feature, which supports automatically loading a new TCD into a DMA channel. Using this feature will reduce core work load in SPI transfer continuously. 测试结果(使用DMA动态加载功能): Test Result(Using DMA dynamic scatter/gather feature ): 读取AT26DF081A设备9处不连续地址数据,需要花费130.68us,其中内核处理中断的时间为0.76us。 根据客户要求,依照此方法每次发送3个字节,接收4个字节,重复9次。SPI通信过程中内核负荷时间比率为 (0.76/101.88) =0.75% SPI read ID operation once, it will take 130.68 us , includes core deal with interrupt time 0.76us. According to this way, customer want to TX 3bytes then RX 4bytes, 9times,during SPI communication core work load rate is 0.75% 测试结论(Test conclusion) SPI通信过程中DMA模块使用方式不同对于减轻内核负荷作用差异明显。通常SPI进行大量数据传输接收,使用DMA模块能有效减少内核负荷。鉴于客户需求,使用测试场景二的方法可以有效降低内核负荷。 How to use DMA module to reduce core work load, different way lead to different result. In general, using DMA module do amounts of SPI data transfer will reduce core work load . According customer requirement, using test scenario 2 way reduce core work load dramatically。 为什么每次读操作之间需要SPI片选无效 (Why need deassert CS signal between each read operation)? 根据AT26DF081A手册要求,读ID命令和读阵列命令都需要使片选信号无效用以结束当前的读操作,换言之如果要开始新的读操作,需要结束之前的通信(使片选信号无效)。 AT26DF081A datasheet indicates deasserting the CS pin will terminate the read operation and put the SO pin into a high-impedance state. In order to start new read command operation, it need deassert the CS pin. 计算客户要求每次读命令间隔时间为SPI实际通信时间(以5MHz波特率发送7个字节重复9次 100.8us)加上内核处理中断时间。 According customer requirement SPI each read command interval time is SPI communication time (TX 7bytes 9times with 5MHz baud rate take 100.8us) add core deal with interrupt time. 测试代码(Test source code) 测试代码基于Kientis 100MHz Rev2例程中的[spi_demo]工程,将测试代码替换<spi_demo.c>和<isr.h>文件即可。 Test source code is based on KINETIS512_V2_SC (Kientis 100MHz Rev2 Example Project) [spi_demo] project, using test code instead of orignial <spi_demo.c>&<isr.h> files.
View full article
It has been reported that OpenSDA v2/2.1 bootloader could be corrupted when the board is plugged into a Windows 10 machine. An updated OpenSDA bootloader that fixes this issue is available at www.NXP.com/openSDA. There is also a blog article by Arm addressing this issue. To reprogram the bootloader on affected boards, you will require an external debugger, such as Segger JLink or Keil ULink programmer attached to the JTAG port connected to the K20 OpenSDA MCU. For your convenience, the binaries of the OpenSDA v2.2 bootloader is attached at the bottom of this post. If using a Segger JLink, download the latest JLink Software and Documentation pack and use the following JLink.exe commands to connect to the K20 OpenSDA MCU: Connect MK20DX128xxx5 S 4000 And then use the following commands to reflash the bootloader: erase loadbin <your Bootloader Binary> 0x00000000 Here is another post on how to recover bricked OpenSDA boards and to prevent it getting re-bricked. To check more information regarding OpenSDA on your boards, please go to www.nxp.com/opensda.
View full article
for M68HC08, HCS08, ColdFire and Kinetis MCUs by: Pavel Lajsner, Pavel Krenek, Petr Gargulak Freescale Czech System Center Roznov p.R., Czech Republic The developer's serial bootloader offers to user easiest possible way how to update existing firmware on most of Freescale microcontrollers in-circuit. In-circuit programming is not intended to replace any of debuging and developing tool but it serves only as simple option of embedded system reprograming via serial asynchronous port or USB. The developer’s serial bootloader supported microcotrollers includes 8-bit families HC08, HCS08 and 32-bit families ColdFire, Kinetis. New Kinetis families include support for K series and L series. This application note is for embedded-software developers interested in alternative reprogramming tools. Because of its ability to modify MCU memory in-circuit, the serial bootloader is a utility that may be useful in developing applications. The developer’s serial bootloader is a complementary utility for either demo purposes or applications originally developed using MMDS and requiring minor modifications to be done in-circuit. The serial bootloader offers a zero-cost solution to applications already equipped with a serial interface and SCI pins available on a connector. This document also describes other programming techniques: FLASH reprogramming using ROM routines Simple software SCI Software for USB (HC08JW, HCS08JM and MCF51JM MCUs) Use of the internal clock generator PLL clock programming EEPROM programming (AS/AZ HC08 families) CRC protection of serial protocol option NOTE: QUICK LINKS The Master applications user guides: Section 10, Master applications user guides. The description of Kinetis version of protocol including the changes in user application: Section 7, FC Protocol, Version 5, Kinetis. The quick start guide how to modify the user Kinetis application to be ready for AN2295 bootloader: Section 7.8, Quick guide: How to prepare the user Kinetis application for AN2295 bootloader. Full application note and  software attached.
View full article
Using five channels from FTM2 module of the KE02 microcontroller included on the FRDM-KE02Z board for controlling a robotic arm powered by five servomotors. Each servomotor is controlled by a couple of buttons of a matrix keyboard, which is connected to eigth GPIOs. Interrupts are not used in this example. The code was generated and compiled on CodeWarrior for Microcontrollers v10.5.
View full article
The Real Time Clock (RTC) module is the right tool when we want to keep tracking the current time for our applications. For the Freedom Platform (KL25Z) the RTC module features include: 32-bit seconds counter with roll-over protection and 32-bit alarm 16-bit prescaler with compensation that can correct errors between 0.12 ppm and 3906 ppm. Register write protection. Lock register requires POR or software reset to enable write access. 1 Hz square wave output. This document describes how to implement the module configuration. Also, how to modify the hardware in order feed a 32 KHz frequency to RTC module (it is just a simple wire link).     Hardware. The RTC module needs a source clock of 32 KHz. This source is not wired on the board; hence we need to wire it. Do not be afraid of this, it is just a simple wire between PTC3 and PTC1 and the good news are that these pins are external.   PTC1 is configured as the RTC_CLKIN it means that this is the input of source clock.     PTC3 is configured as CLKOUT (several options of clock frequency can be selected in SIM_SOPT2[CLKOUTSEL] register). For this application we need to select the 32 Khz clock frequency.                         RTC configuration using Processor Expert. First of all we need to set the configurations above-mentioned in Component Inspector of CPU component. Enable RTC clock input and select PTC1 in Pin Name field. This selects PTC1 as RTC clock input. MCGIRCLK source as slow in Clock Source Settings > Clock Source Setting 0 > Internal reference clock > MCGIRCLK source. This selects the 32 KHz clock frequency. Set ERCLK32K Clock Source to RTC Clock Input in Clock Source Settings > Clock Source Setting 0 > External reference clock > ERCLK32K Clock Source. This sets the RTC_CLKIN as the 32 KHz input for RTC module. Select PTC3 as the CLKOUT pin and the CLKOUT pin output as MCGIRCLK in Internal peripherals > System Integration Module > CLKOUT pin control. With this procedure we have a frequency of 32 KHz on PTC3 and PTC1 configured as RTC clock-in source. The MCG mode configurations in this case is PEE mode: 96 MHz PLL clock, 48 MHz Core Clock and 24 MHz Bus clock.   For the RTC_LDD component the only important thing is to select the ERCKL32K as the Clock Source. The image below shows the RTC_LDD component configuration for this application.   After this you only need to Generate Processor Expert Code and write your application.  The code of this example application can be found in the attachments of the post. The application prints every second the current time.     RTC bare-metal configuration. For a non-PEx application we need to do the same configurations above. Enable the internal reference clock. MCGIRCLK is active.          MCG_C1 |= MCG_C1_IRCLKEN_MASK; Select the slow internal reference clock source.          MCG_C2 &= ~(MCG_C2_IRCS_MASK); Set PTC1 as RTC_CLKIN and select 32 KHz clock source for the RTC module.          PORTC_PCR1 |= (PORT_PCR_MUX(0x1));              SIM_SOPT1 |= SIM_SOPT1_OSC32KSEL(0b10); Set PTC3 as CLKOUT pin and selects the MCGIRCLK clock to output on the CLKOUT pin.     SIM_SOPT2 |= SIM_SOPT2_CLKOUTSEL(0b100);     PORTC_PCR3 |= (PORT_PCR_MUX(0x5));   And the RTC module configuration could be as follows (this is the basic configuration just with seconds interrupt): Enable software access and interrupts to the RTC module.     SIM_SCGC6 |= SIM_SCGC6_RTC_MASK; Clear all RTC registers.   RTC_CR = RTC_CR_SWR_MASK; RTC_CR &= ~RTC_CR_SWR_MASK;   if (RTC_SR & RTC_SR_TIF_MASK){      RTC_TSR = 0x00000000; } Set time compensation parameters. (These parameters can be different for each application) RTC_TCR = RTC_TCR_CIR(1) | RTC_TCR_TCR(0xFF); Enable time seconds interrupt for the module and enable its irq. enable_irq(INT_RTC_Seconds - 16); RTC_IER |= RTC_IER_TSIE_MASK; Enable time counter. RTC_SR |= RTC_SR_TCE_MASK; Write to Time Seconds Register. RTC_TSR = 0xFF;   After this configurations you can write your application, do not forget to add you Interrupt Service Routine to the vector table and implement an ISR code.   In the attachments you can find two zip files: PEx application and non-PEx application.   I hope this could be useful for you,   Adrián Sánchez Cano. Original Attachment has been moved to: FRDM-KL25Z-RTC-TEST.zip Original Attachment has been moved to: FRDM-KL25Z-PEx-RTC.zip
View full article