Kinetis Microcontrollers Knowledge Base

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

Kinetis Microcontrollers Knowledge Base

Discussions

Sort by:
This hint will demonstrate how to verify ADC conversion rate (with oscilloscope) during testing phase.   Refer to the phenomenon descripted in"Figure 1. Voltage drops at ADC input during sampling process" of AN4373. If too large values is selected for the external RC components, serious voltage disturbances (voltage drops/peaks) at the ADC input (see Figure 1) can be observed. The disturbance at the ADC input in this case results from the basic principle of operation of the sample and hold (S/H) circuit inherent in a SAR ADC. Although we should avoid this happening, but it can be used to measure the ADC conversion rate with oscilloscope during testing phase.   According to the 'Table 30. 16-bit ADC operating conditions' of K64P144M120SF5, we can know that the max ADC conversion rate is 818.330 ksps. Here I create an example by using KDS3.2 with Processor Expert(See the attach file). After select same configuration according to that table, I got almost the same ADC conversion rate. The conversion time meet equation given in Reference Manual too. Now let's measure the ADC conversion rate on FRDM-K64F board with oscilloscope. After connected an external 1.5KΩ resistance, the value of external RC components is big enough to be observed. Below is the waveform observed with oscilloscope, the frequency between voltage drops at ADC input during sampling is about 818 ksps. This test result is consistent with the theoretical calculated value.
View full article
   1.  K60 eDMA 16-channel implementation Local memory containing transfer control descriptors for each of the 16 channels 32-byte TCD stored in local memory for each channel    2.  DMA memory to memory performance In the traditional M2M data movement, performance is best expressed as the peak data transfer rates In most implementations, this transfer rate is limited by the speed of the source and destination address spaces.     3.  eDMA peak transfer rate   4. Performance test         With K60 100MHz (TWR-K60D100M), implement internal SRAM-SRAM eDMA data transfer. If  transfer size setting as 32-bit in TCD Transfer Attributes (DMA_TCD_ATTR), there will has one wait state during each read/write. That's why the DMA performance doesn't up to 200MB/s as the manual stated.       We highly recommend setting DMA transfer size to 16-byte at DMA_TCD_ATTR register, it will much increase the DMA performance.(Get 162MB/s transfer rate with TWR-K60D100M board.) 5.  Testing code attached.
View full article
Hello Kinetis friends! The launch of new Kinetis devices and development tools called "Kinetis K2" brought some new K22_120 MHz devices to the K22 family portfolio. :smileyinfo: Please notice the name "Kinetis K2" only refers to the Kinetis generation, but it is not related to part number (e.g. K63/K64 are part of K2 generation). Previously existing Kinetis portfolio already had some K22_120 MHz devices, so this  caused confusion regarding the documentation, header files, features, development boards and others, because the part numbers are very similar. I created the next reference table outlining the existing K22_120 MHz parts with their corresponding files and boards. The last column is an overview of the features or peripherals that are either missing or added in each device. :smileyalert: IMPORTANT NOTES:           - I gathered and put together this information as reference, but it is not official. For the most accurate information please visit our webpage www.nxp.com.           - Header files MK22F12.h and MK22FA12.h apply for legacy K22_120 devices. However TWR-K21F120M(A) board has a K21_120 part, so use MK21F12.h or MK21FA12.h instead.      Colleague Carlos Chavez released an Engineering Bulletin (EB811) with good information related to this document:      http://cache.nxp.com/files/microcontrollers/doc/eng_bulletin/EB811.pdf Regards! Jorge Gonzalez
View full article
This document covers some of the more common questions about the new Kinetis K8x family. Any new specific issues or questions should be posted into it's own thread, and will be added to this document as appropriate. Kinetis K80 Basics What is the K8x family? It is a new Kinetis family of Cortex-M4F devices, running up to 150MHz, that include 256K of Flash and 256K of SRAM. It features FS USB, SDRAM, QuadSPI, SPI, I2C, LPUART, and much much more. How does the Kinetis K8x family differ from other Kinetis K families? The K8x family offers the same advantages and compatibility as other Kinetis K families, but also offers several new features not found on other Kinetis K families: QuadSPI Support Dual Voltage Domains (independent VDDIO domain down to 1.8V for QuadSPI or other interfaces) EMVSIM (Euro, MasterCard, Visa Serial Interface Module) FlexIO Additionally the K81 and K82 families offer the following new security modules: LTC (Low Power Trusted Cryptography) Encryption / Decryption algorithms in hardware (as opposed to using mmCAU s/w libs) OTFAD (On The Fly AES Decryption) Zero latency decryption when executing encrypted code from QuadSPI Secure RAM 2KB of Secure Session RAM Because of the addition of a second voltage domain and QuadSPI, there is no hardware pin compatibility with previous Kinetis derivatives. However there is significant module and enablement re-use, so if you’re familiar with other Kinetis devices, it will be easy to get started with the K80. Where can I find reference manuals, datasheets, and errata? These can be found on the K8x documentation pages. Detailed information on the K81 is under NDA, so please contact your NXP sales representative for those documents. What’s the difference between the different K8x devices? K80 is the base version, which includes QuadSPI controller, SDRAM controller, FS USB, and much more. K81 adds DryIce Tamper Detect and the LTC/OTFAD modules K82 adds just the LTC/OTFAD modules K80 and K82 families have the same pin out for their respective packages. The pinout for K81 is slightly different but can still be compatible. What boards are available to evaluate the K80 family? FRDM-K82F: A Freedom board with a 100LQFP K82 device. Also includes dual QuadSPI, touch pad, Arduino compatible footprint, and FlexIO header compatible with OV7670 camera. TWR-K80F150M: A Tower board with 121XFBGA K80 device. Includes dual QuadSPI, SDRAM, EVMSIM, SDCard holder, touch pads, and more. TWR-POS-K81: A Point of Sale reference design board in tower form factor. This board is only available via your NXP sales representative. The K8x MCU Family Hardware Tools selection guide has more details on board differences. What packages are available? The 100 LQFP and 121 XFBGA packages are lead packages available today. The 144 LQFP package and the WLCSP are part of the Package Your Way (PYW) program, and you should contact your NXP sales representative if interested in those packages. What is the difference between K8x and KL8x families? The KL8x family shares many of the same features as the K8x family. The biggest differences are that the KL8x family uses the Cortex-M0+ core (instead of Cortex-M4F), has a lower max clock speed, and has less internal Flash and RAM. It also reduces the instances of peripherals available, but still includes QuadSPI, FlexIO, LTC, and BootROM peripherals like on the K80. See the KL8x Fact Sheet for more details. KL8x devices will be available in the first quarter of 2016. Software/Tools Where can I find instructions and details on the hardware used to evaluate the K8x family? FRDM-K82F: http://nxp.com/frdm-k82f/startnow​ TWR-K80F150M: http://nxp.com/twr-k80f150m/startnow ​ Which version of Kinetis SDK supports the K8x family? Kinetis Software Development Kit (KSDK) support is split depending on the evaluation platform. For TWR-K80F150M, support can be found in the Kinetis SDK 1.3 Mainline Release. For FRDM-K82F, support can be found in the Kinetis SDK FRDM-K82F Stand-alone release. Note that the FRDM-K82 standalone release is truly standalone, and does not require the mainline release to be installed. How do I run the FRDM-K82F OV7670 camera demo? See this Community post: https://community.freescale.com/docs/DOC-329438 How can I use the micro SD card reader on the TWR-K80F150M? Because the SD card signals are shared with the QuadSPI signals, the SD card slot is not connected by default. See section 3.14 of the TWR-K80F150M User Guide for details on how to connect it, with the understanding that QuadSPI will not be available on the board while using SDHC. How do I use the SDRAM on the TWR-K80F150M? See section 3.9 of the TWR-K80F150M User Guide. Due to the layout of the board, the OpenSDA UART feature cannot be used while running the SDRAM as jumpers J6 and J8 need to be removed. QuadSPI What is QuadSPI Flash? Why should I use it? QuadSPI is a name for a popular type of serial NOR flash memory that is SPI compatible, but also allows for multiple data lines (up to 4 per device, or 8 if done in parallel) with bi-directional data for increased memory bandwidth. The QuadSPI controller on the K8x also allows for Execute-In-Place (XIP) mode so that code can be executed out of this external memory. QuadSPI memory can be used for either extra memory storage or for extra code space, or a combination of both. After initialization, it appears as a readable area of memory starting at 0x6800_0000 (as well as at the alias regions). How can I program the QuadSPI? There is an example application in Kinetis SDK that shows how to program the QuadSPI at C:\Freescale\KSDK_1.3.0\examples\twrk80f150m\driver_examples\qspi For programming an entire application, the ROM bootloader can be used. Details are in the K80 Bootloader Tools Package. The Kinetis Bootloader QuadSPI User's Guide that comes as part of that package describes all the steps needed to get up and running with QuadSPI. There is also an example Kinetis SDK application that runs out of QuadSPI at C:\Freescale\KSDK_1.3.0\examples\twrk80f150m\demo_apps\hello_world_qspi_alias What performance tips are there if doing QuadSPI XIP? A few key performance factors: Ensure both the data and instruction cache is enabled Use as many data lines as possible (4, or 8 if available in dual/octal modes) Use DDR mode Any critical code should be placed in Flash/RAM for fastest performance If using XIP, code should be executed out of the QuadSPI aliased address space which starts at 0x0400_0000. A more detailed app note is under development. How do I debug code located in QuadSPI? You must make use of the aliased QuadSPI address space at 0x0400_0000. There is an example of this in the hello_world_qspi_alias example in Kinetis SDK. Due to the architecture of the M4 core on Kinetis, breakpoints cannot be set in the 6800_0000 address space, which is why the alias address space is provided. What app notes are available for the QuadSPI? Because the QuadSPI module found on the K8x family has also been used on other NXP devices, there are some app notes available that can be useful for QuadSPI development. Note that some of the implementation details and features as described in the app notes will be different for K8x, so please use the K8x reference manual for full details. AN4186​ AN4512​ AN4777​ ROM Bootloader Where can I find more information on the bootloader that comes built into the silicon of the K8x family? Download the K80 Bootloader Tools package. If interested in QuadSPI, the Kinetis Bootloader QuadSPI User's Guide that comes as part of that package describes all the steps needed to get up and running with QuadSPI. The other information found on the Kinetis Bootloader website is also useful as this is what the ROM Bootloader is based off of. What interfaces does the ROM Bootloader support? The ROM Bootloader on the K8x family can interface via LPUART, I2C, SPI, or USB HID (via BLHost) to erase and program both the internal flash and/or QuadSPI flash. This is the same bootloader found on other Kinetis devices, but also includes some more advanced features to support QuadSPI. How can I enter bootloader mode? By default, when using a Kinetis SDK project, the bootloader is disabled and the code immediately jumps to the address in Flash pointed at location 0x4. By asserting the NMI pin at reset though, the part can be forced to enter bootloader mode. This is useful for programming the QuadSPI or interfacing with the bootloader in other ways. This feature is controlled via the FOPT[BOOTPIN_OPT] bit, which the Kinetis SDK code sets to '0' to enable the NMI pin to enter bootloader mode. The NMI button on each board is: FRDM-K82F: SW2 TWR-K80F150M: SW2 The FOPT register (at 0x40C) can be modified to always go into Bootloader mode if desired. Details are in boot chapter of the K80 reference manual. Where is the bootloader configuration data found in Kinetis SDK? The Bootloader Configuration Area (BCA), which begins at address 0x3C0, is defined in C:\Freescale\KSDK_1.3.0\platform\devices\MK80F25615\startup\system_MK80F25615.c starting on line 133. You must also add the define BOOTLOADER_CONFIG in the project settings to let the linker files know to program this BCA area. The FOPT configuration register (at 0x40D) is defined in C:\Freescale\KSDK_1.3.0_K82\platform\devices\MK82F25615\startup\<compiler>\startup_MK80F25615.s and by default is set to 0x3D which disables the bootloader, but does enable the option to enter bootloader via the NMI pin at reset (see previous question) How can I use the UART port on the FRDM-K82F with the BootROM? The OpenSDA/UART lines on the FRDM-K82F use LPUART4, which is not used by the BootROM. If you would like to use the serial UART lines to interact with the BootROM, you can blue wire a connection from either J24 or J1, and connect to R32 (RX) and R36 (TX). This was due to muxing trade-offs. The OpenSDA/UART lines on the TWR-K80F150M are connected to UART1 and thus no modification is necessary for that board. Also keep in mind that you can use the USB interface with the BLHost tool on both boards with no modification. The examples in Kinetis SDK setup the QuadSPI Configuration Block (QCB) data using a qspi_config.bin file. How can I generate my own custom QCB file? There is a C file that come as part of Kinetis SDK (C:\Freescale\KSDK_1.3.0\examples\twrk80f150m\demo_apps\hello_world_qspi\qspi_config_block_generator.c) or in the KBoot zip file, that can be compiled with various toolchains on a host computer, that will then produce a .bin file. You could import this file, and then after compilation, run it, and it will write out the new .bin to your hard drive. There is a tool under development that simplifies this process by reading in that example .bin file and then you can modify the fields in the app, and then it will write out the modified .bin file. Can I jump directly to QuadSPI for Execute in Place (XiP) after booting? Yes. However note that you must still put the Bootloader Configuration Area (BCA) into internal flash. And you also may want to put the QuadSPI Configuration Block (QCB) in flash as well since it needs to be read before the QuadSPI is setup. Thus even if all your code is in QuadSPI address space, the internal flash must also be written at least once to put in the configuration data. Once you have that set though, then you can develop code by only programming the QuadSPI address space. Troubleshooting I’m having debugger connection issues when using an external debugger, like a Segger JLink. Why? It’s likely that the OpenSDA circuit is interfering, and thus needs to be isolated via jumpers on the board. For TWR-K80F150M: Pull J16 and J17 For FRDM-K82F: Pull J6 and J7 Also make sure you are using the correct debug header for the K8x device on the board: For TWR-K80F150M: J11 For FRDM-K82F: J19 Where is the CMSIS-DAP/OpenOCD debug configuration for the K8x family in Kinetis Design Studio? KDS 3.0 does not support programming the K8x family via the CMSIS-DAP interface. You will need to change the OpenSDA app on the board to either J-Link or P&E as described in the K8x Getting Started guides (Part 3). I can't get OpenSDA on the FRDM-K82F into bootloader mode. Make sure jumper J23 is on pins 1-2 to connect the reset signal to the OpenSDA circuit. On some early versions of the board this was incorrectly installed on pins 2-3 instead. When using IAR with the default CMSIS-DAP debug interface, I sometimes get the error: “Fatal error: CPU did not power up” This is an issue in some older versions of IAR. Upgrade to at least version 7.40.5 which fixes this. When using KDS with the JLink interface with the FRDM-K82F board, I get an error. If you see the error "The selected device 'MK82FN256XXX15' is unknown to this version of the J-Link software." it's because the J-Link driver that comes with KDS 3.0.0 does not know about the K82 family. You can either select a MK80FN256XXX15 device (which is compatible with the K82 on the board) or update the JLink software by downloading and installing the latest JLink Software and documentation pack. At the end of the installation process it will ask to update the DLLs used by the IDEs installed on your computer, so make sure to check the KDS checkbox on that screen. I’m using the P&E OpenSDA App and debugging is not working. I get either "Error reading data from OpenSDA hardware. E17925" or “The system tried to join a drive to a directory on a joined drive” in KDS If using IAR, make sure you have the latest version (7.40.7 or later) If using KDS, you need to update the P&E plugin in KDS. Go to Help->Check for Updates, and select the P&E debug update. Make sure not to select the other debugger updates as it will break it in KDS 3.0.0 (see this thread)
View full article
    作者 Shaozhong Liang     YAFFS(Yet Another Flash File System)文件系统是专门针对NAND闪存设计的嵌入式文件系统。在YAFFS中,文件是以固定大小的数据块进行存储的,块的大小可以是512字节、1024字节或者2048字节。这种实现依赖于它能够将一个数据块头和每个数据块关联起来。每个文件(包括目录)都有一个数据块头与之相对应,数据块头中保存了ECC(Error Correction Code)和文件系统的组织信息,用于错误检测和坏块处理。     YAFFS在文件进行改写时总是先写入新的数据块,然后删除旧的数据块,这样即使意外掉电,丢失的也只是这一次修改数据的最小写入单位,从而实现了掉电保护,保证了数据完整性。 YAFFS是为NAND FLASH设计的,它作了以下的假设或定义。     NAND Flash是基于块(block)的,每一个Block大小相同,由整数个chunk组成。每一个Block可单独擦除。一页(page,或chunk)为Flash的分配单元。所有的访问(读或者写)都是基于页(或chunk)的。     当对NAND Flash编程时,只有二进制中的0被编程,而1则“不关心”。比如,一个字节包含的二进制数为1010,那么当编程1001,会导致这两个数的位与操作。结果为1000.这和NOR FLASH不同。     YAFFS 分别用块号和 chunk id 标示块和 chunk 。它将空块(填满0xFF)当作空闲块或者已擦除块。这样,格式化一个YAFFS分区等价于擦除所有未损坏的块。 因此YAFFS最少需要一些函数能够擦除块,读一个页,写一个页。 1. 直接接口(Direct Interface)的相关文件     仅需要提取少量文件。使用yaffs的直接接口,你不需要所有的文件。你实际需要的文件列在下面,其余文件不需要编译。 direct/yaffsfs.c yaffs_guts.c direct/yaffscfg.c yaffs_nand.c yaffs_tagsvalidity.c yaffs_checkptrw.c yaffs_qsort.c yaffs_tagscompat.c yaffs_ecc.c yaffs_packedtags2.c 2. YAFFS  存储设备     YAFFS对文件系统上的所有内容(比如正常文件,目录,链接,设备文件等等)都统一当作文件来处理,每个文件都有一个页面专门存放文件头,文件头保存了文件的模式、所有者id、组id、长度、文件名、Parent Object ID等信息。因为需要在一页内放下这些内容,所以对文件名的长度,符号链接对象的路径名等长度都有限制。前面说到对于NAND FLASH上的每一页数据,都有额外的空间用来存储附加信息,通常NAND驱动只使用了这些空间的一部分,YAFFS正是利用了这部分空间中剩余的部分来存储文件系统相关的内容。以512+16B为一个PAGE的NAND FLASH芯片为例,Yaffs文件系统数据的存储布局如下所示: 0 to 511 数据区域 512 to 515 YAFFS TAG 516 Data status byte 517 Block status byte 坏块标志位 518 to 519 YAFFS TAG 520 to 522 后256字节数据的ECC校验结果 523 to 524 YAFFS TAG 525 to 527 前256字节数据的ECC校验结果     可以看到在这里YAFFS一共使用了8个BYTE用来存放文件系统相关的信息(yaffs_Tags)。这8个Byte的具体使用情况按顺序如下: Bits Content 20 ChunkID,该page在一个文件内的索引号,所以文件大小被限制在2^20 PAGE 即512Mb 2 2 bits serial number 10 ByteCount 该page内的有效字节数 18 ObjectID 对象ID号,用来唯一标示一个文件 12 Ecc, Yaffs_Tags本身的ECC校验和 2 Unused     其中Serial Number在文件系统创建时都为0,以后每次写具有同一ObjectID和ChunkID的page的时候都加一,因为YAFFS在更新一个PAGE的时候总是在一个新的物理Page上写入数据,再将原先的物理Page删除,所以该serial number可以在断电等特殊情况下,当新的page已经写入但老的page还没有被删除的时候用来识别正确的Page,保证数据的正确性。 ObjectID号为18bit,所以文件的总数限制在256K即26万个左右。     由于文件系统的基本组织信息保存在页面的备份空间中,因此,在文件系统加载时只需要扫描各个页面的备份空间,即可建立起整个文件系统的结构,而不需要像JFFS1/2 那样扫描整个介质,从而大大加快了文件系统的加载速度。     一个YAFFS设备是一个逻辑设备,它代表了一个物理设备的部分或整体。你可以认为它是一个Nand上的一个“分区”。比如,该分区可能覆盖整个NAND,也许只是一半,而另外一半就是另一个Yaffs_Device.它也可以用于你使用一个非flash设备(比如RAM)来测试的情况下。 一个Yaffs_Device记录了起始和结束块。通过改变它的起始和结束块,你就可以在同一个物理设备上使用不止一个的Yaffs_Device。 这里将需要你自己建立的Yaffs_Device结构的数据域列出,其他数据域由Yaffs自动创建。 int nDataBytesPerChunk     如其名,这是每一个chunk的字节数,还记得吧,在yaffs术语中,一个页就是一个chunk,因而它也是一页的字节数。它是数据字节数,即不包含OOB的数据。比如一页时2048字节+64字节的OOB,那么数值nDataBytesPerChunk为2048。 int nChunksPerBlock     物理Nand设备中每页包含的chunk(就是Nand上的页)的数目,最少是2。 int spareBytesPerChunk     空闲域(spare area)大小,比如:每个chunk(页)的OOB字节数。 int startBlock     该逻辑Yaffs_Device设备第一个块的块号(而字节地址),注意,yaffs需要第一个块是空闲的,因此你不可以设置该变量为0,如果设置为0,Yaffs会给它加1,并且会在结束块号上也加1,在你设置设备从块0开始,到最后一个块结束,这意味着yaffs试图写一个不存在的块,从而出现错误。 int endBlock     该逻辑Yaffs_Device设备的最后一个块号。如果startBlock为0,那么yaffs会使用endBlock+1,至少使startBlock+nReservedBlocks+2 int nReservedBlocks     这是YAFFS必须保留,用于垃圾回收和块错误恢复的可擦除块的数目。至少是2,但是5更好。如果你使用一个不会损坏的介质,比如RAM或者RAM盘,或者主机文件系统模拟,那么可以是2。 int nShortOpCaches     配置当前设备YAFFS Cache项的数目。0值表示不使用cache。对于大多数系统,推荐使用10到20之间的一个数值。不能大于YAFFS_MAX_SHORT_OP_CACHES定义的数值。 int useNANDECC     这是一个标志,用于指示是由yaffs执行ECC计算,还是由NAND驱动程序来执行ECC计算。(译者注:此数值取0,则使用yaffs来执行ECC计算,软件ECC计算。如果想要使用硬件ECC校验时,应该设置为1,并且在NAND驱动程序中加入硬件ECC校验的代码。) void *genericDevice     这是一个指针,它应该指向任何数据,底层NAND驱动程序需要知道以从物理设备读、写。 int isYaffs2     我们使用的是否YAFFS2版本? int inbandTags     是否为OOB区,如果不是,那么它为真,仅用于yaffs2 u32 totalBytesPerChunk     这个名字可能有点误导人,它应该等于nDataBytesPerChunk ,而非其名字暗示的nDataBytesPerChunk + spareBytesPerChunk。如果inbandTags为真,那么yaffs设置nDataBytesPerChunk,因此有足够的空闲空间存储数据,yaffs会在空闲域中正常存储。 write/readChunkWithTagsFromNAND, markNANDBlockBad queryNANDBlock 这些都是函数指针,你需要提供这些函数来给YAFFS,读写nand flash。 3.NAND Flash 访问函数 int (*writeChunkWithTagsToNAND) (struct yaffs_DeviceStruct * dev, int chunkInNAND, const u8 * data, const yaffs_ExtendedTags * tags);   dev: 要写入的yaffs_Device逻辑设备. chunkInNAND: 将chunk写入的页 Data: 指向需要写入的数据的指针 tags: 未压缩(打包)的OOB数据 Return: YAFFS_OK / YAFFS_FAIL 该函数将页(chunk)写入nand中,向nand中写入数据。数据和标签(tags)永远不应为 NULL. chunkInNand 是将要写入的页的页号,而不是需要转换的地址。 int (*readChunkWithTagsFromNAND) (struct yaffs_DeviceStruct * dev, int chunkInNAND, u8 * data, yaffs_ExtendedTags * tags);  dev: 要写入的yaffs_Device逻辑设备. chunkInNAND: 将chunk读入的页 Data: 指向需要读入的数据的缓冲区指针 tags: 指向未压缩(打包)的OOB数据的缓冲区指针 Return: YAFFS_OK / YAFFS_FAIL 该函数执行上一个函数的相反的功能,首先,读取数据和OOB字节,接着将这些输入放在一个由参数data指向的缓冲区中 int (*markNANDBlockBad) (struct yaffs_DeviceStruct * dev, int blockNo);   dev: 要写入的yaffs_Device逻辑设备. blockNo: 要标记的块. Return: YAFFS_OK / YAFFS_FAIL int (*queryNANDBlock) (struct yaffs_DeviceStruct * dev, int blockNo, yaffs_BlockState * state, u32 *sequenceNumber);   dev: 要写入的Yaffs_Device逻辑设备. blockNo: 要标记的块. state: Upon returning this should be set to the relevant state of this particular block. Sequance number: 该块的顺序号(The Sequence number),为0表示此块未使用 Return: YAFFS_OK / YAFFS_FAIL     它应检查一个块是否是有效的。如果在OOB中设置了坏块标记,那么*state应该被赋值为YAFFS_BLOCK_STATE_DEAD,*sequenceNumber赋值为0,然后返回YAFFS_FAIL。     如果该块没坏,那么应解压缩标签。标签解压缩后,若发现chunk已使用(查看tags.chunkUsed),则*sequenceNumber应赋值为tags.sequenceNumber,*state赋值为YAFFS_BLOCK_STATE_NEEDS_SCANNING,否则该块未使用,则*sequenceNumber赋值为0,*state赋值为YAFFS_BLOCK_STATE_EMPTY 4. YAFFS的缓存机制     由于NandFlash是有一定的读写次数的,所以在对一个文件进行操作的时候往往是先通过缓冲进行,对最后一次性写入NandFlash,这有效的减少了用户对NandFlash的频繁操作,延长了NandFlash的寿命。下面大致说一下YAFFS的缓存机制: 4.1.首先在yaffs_mount的时候会对yaffs_dev这个结构体进行注册,和缓冲部分相关的有: dev->nShortOpCaches//这个变量决定了有多少个缓冲,因为缓冲会大量的占用堆栈的空间,所以在yaffs不建议缓冲的数量很大,即使你填一个很大的数,系统也不会超过YAFFS_MAX_SHORT_OP_CACHES的总数。 yaffs_ChunkCache *srCache;//缓冲区的首地址,dev->srCache = YMALLOC( dev->nShortOpCaches * sizeof(yaffs_ChunkCache));下面介绍一下缓冲区这个结构体的组成: typedef struct { struct yaffs_ObjectStruct *object;//一个缓冲区对应一个文件 int chunkId; int lastUse; //通过lastUse来 int dirty; //标志了这一个缓冲区是否被使用 int nBytes; __u8 data[YAFFS_BYTES_PER_CHUNK];//数据区 } yaffs_ChunkCache; 4.2.什么时候用到缓冲区?        用到缓冲区最多的地方显而易见是对已经创建的文件进行写操作。而且是需要写的大小和512不一致的时候,这是因为如果是刚好512的话,系统会直接写入NandFlash中。对于小于512的系统首先会调用yaffs_FindChunkCache(in,chunk)这个函数来判断in这个object是否在缓冲区中存在。如果存在会调用已有缓冲区进行操作。当然如果是第一次对一个object进行操作,肯定在缓冲区中是不存在对应它的空间的,因此系统会调用yaffs_GrabChunkCache函数为此次操作分配一个缓冲区。 5. 应用层接口     YAFFS为连接的应用程序提供了一组函数。大部分跟标准C库函数,如open/close一致,只是增加了yaffs_前缀,如 yaffs_open. 这些函数定义在direct/yaffsfs.h中。     初始化yaffs来完成读写,你必须在每个你要使用的yaffs设备上调用yaffs_mount。比如yaffs_mount(”/boot”)。这可以在系统启动的时候执行,如果存在一个操作系统,那么程序需要考虑这点。在你完成使用的时候,你也需要调用yaffs_umount函数,这样yaffs就会将它需要状态写入磁盘。 如果读写文件的应用层接口已经存在,你可以根据相关的操作系统调用来封装相关的函数调用。 1 yaffs_mount( ) 功能说明:加载指定器件。 输入参数:path    要加载的器件。 输出参数:无。 返回值: 表明加载的状态。 调用的函数:yaffsfs_FindDevice( )、yaffs_GutsInitialise( )。 2 yaffs_open( ) 功能说明:按照指定方式打开文件。 输入参数:path    文件的绝对路径;           Oflag   打开的方式;           Mode    文件许可模式。 输出参数:无。 返回值:句柄。 调用的函数:yaffsfs_GetHandle( )、yaffsfs_FindDirectory( )、yaffs_MknodFile( )、yaffsfs_PutHandle( )、yaffs_ResizeFile( )、yaffsfs_FindObject( )。 3 yaffs_write( ) 功能说明:根据打开文件的句柄,从指定数组处读指定字节写入文件中。 输入参数:fd      要写入的文件的句柄;           Buf     要写入的数据的首地址;           Nbyte   要写入的字节数。 输出参数:无。 返回值: 写入了的字节数。 调用的函数:yaffs_WriteDataToFile( )、yaffsfs_GetHandlePointer( )、yaffsfs_GetHandleObject( ) 4 yaffs_read( ) 功能说明:根据打开文件的句柄,从文件中读出指定字节数据存入指定地址。 输入参数:fd       要读出的文件的句柄;           Buf      读出文件后要存入的数据的首地址;           Nbyte    要读出的字节数。 输出参数:无。 返回值: 读出了的字节数。 调用的函数:yaffs_ReadDataFromFile( )、yaffsfs_GetHandlePointer( ) 5 yaffs_close( ) 功能说明:关闭已经打开的文件句柄,yaffs 有缓冲机制,当调用yaffs_close()关闭文件之后能够保证将内容写入nandflash。 输入参数:fd    需要关闭的文件的句柄; 输出参数:无。 返回值:无。 6. YAFFS在MQX的应用案例     YAFFS提供了直接调用模式,可以方便移植到 none-OS或者light-weighted OS中。附件是将YAFFS移植到Freescale MQX实时操作系统的源代码和工程,可以在II型集中器的Demo Board上运行。     初步的测试表明YAFFS工作正常,能够完成创建目录,创建/删除文件,读/写文件操作等。 YAFFS非常适合none-OS或者是light-weighted OS,使用YAFFS需要关注的是RAM的消耗,适合小量文件(<20)。 如果不想使用MQX默认的MFS(FAT32文件系统),YAFFS可以作为一个文件系统的备选方案。
View full article
Introduction What is a gated timer and why would I need one? A gated timer is a timer whose clock is enabled (or "gated") by some external signal.  This allows for a low code overhead method of synchronizing a timer with an event and/or measuring an event. This functionality is not commonly included on Freescale microcontroller devices (this functionality is only included on devices that are equipped with the upgraded TPM v2 peripheral; currently K66, K65, KL13, KL23, KL33, KL43, KL03) but can be useful in some situations.  Some applications which may find a gated timer useful include asynchronous digital sampling, pulse width duty cycle measurement, and battery charging. How do I implement a gated timer with my Kinetis FTM or TPM peripheral? To implement a true gated timer with a Kinetis device (that does not have the TPM v2 peripheral), additional hardware will be required to implement the enable/disable functionality of a gated timer.  This note will focus on two different ways (low-true and high-true) to implement a gated timer.  The method used will depend on the requirements of your application. Implementing a gated timer for Kinetis devices without the TPM v2 peripheral requires the use of a comparator and a resistive network to implement a gated functionality (NOTE:  Level shifters could be used to replace the resistive network described; however, a resistive network is likely more cost effective, and thus, is presented in this discussion).  Figure 1 below is the block diagram of how to implement a gated timer functionality.  The theory behind this configuration will be explained in later sections. Theory of Operation Comparator and resistive network implementation The comparator is the key piece to implementing this functionality. For those with little experience with comparators (or need a refresher), a comparator is represented by the following figure.  Notice that there are three terminals that will be of relevance in this application: a non-inverting input (labeled with a '+' sign), an inverting input (labeled with a '-' sign), and an output. A comparator does just what the name suggests: it compares two signals and adjusts the output based on the result of the comparison.  This is represented mathematically in the figure below. Considering the above figure, output of the comparator will be a  logic high when the non-inverting input is at a higher electric potential than the inverting input.  The output will be a logic low if the non-inverting input is at a lower electric potential than the inverting input.  The output will be unpredictable if the inputs are exactly the same (oscillations may even occur since comparators are designed to drive the output to a solid high or solid low).  This mechanism allows the clock enable functionality that is required to implement a gated timer function provided that either the non-inverting or inverting input is a clock waveform and the opposite input is a stable logic high or low (depending on the desired configuration) and neither input is ever exactly equal.  Comparator Configurations There are two basic signal configurations that an application can use to enable the clock output out of the comparator: low-true signals and high-true signals.  These two signals and some details on their implementation are explained in the following two sections.  Low-true enable A low-true enable is an enable signal that will have zero electric potential (relative to the microcontroller) or a "grounded" signal in the "active" state.  This configuration is a common implementation when using a push button or momentary switch to provide the enable signal.  When using this type of signal, you will want to connect the enable signal to the non-inverting input of the comparator, and connect the clock signal to the inverting input. The high level of the enable signal should be guaranteed to always be the highest voltage of the input clock plus the maximum input offset of the comparator. To find the maximum input offset of the comparator, consult the device specific datasheet.  See the figure below to see a graphical representation of areas where the signal will be on and off. The external hardware used should ensure that the low level of the enable signal never dips below the lowest voltage of the input clock plus the maximum input offset of the comparator. The following figure displays one possible hardware configuration that is relatively inexpensive and can satisfy these requirements. High-true enable A high-true enable is an enable signal that will have an electric potential equal to VDD of the microcontroller in the "active" state.  This configuration is commonly implemented when the enable signal is provided by an active source or another microcontroller.  When interfacing with this type of signal, you will want to connect the enable signal to the inverting input of the comparator, and connect the clock signal to the non-inverting input.  When the comparator is in the inactive state, it should be at or below the lowest voltage of the clock signal minus the maximum input offset of the comparator.  Refer to the following figure for a diagram of the "on" and "off" regions of the high true configurations. The external hardware will need to guarantee that the when the enable signal is in the active state, it does not rise above the highest voltage of the clock signal minus the maximum input offset of the comparator. The following figure displays one possible hardware configuration that is relatively inexpensive and can satisfy these requirements. Clocking Options Clocking waveform requirements will vary from application to application.  Specifying all of the possibilities is nearly impossible.  The point of this section is to inform what options are available from the Kinetis family and provide some insight as to when it might be relevant to investigate each option. The Kinetis family provides a clock output pin for most devices to allow an internal clock to be routed to a pin.  The uses for this option can vary.  In this particular scenario, it will be used to provide the source clock for the comparator clock input. Here are the most common clock output pin options across the Kinetis K series devices.  (NOTE:  If the application requires a clock frequency that the CLKOUT signal cannot provide, a separate FTM or TPM instance or another timer module can be used to generate the required clock.) In the Kinetis L series devices, the following options will be available. The clock option selected should be the slowest allowable clock for the application being designed.  This will minimize the power consumption of the application.  For applications that require high resolution, the Bus, Flash, or Flexbus clock should be selected (note that the Flexbus clock can provide an independently adjustable clock, if it is not being used in the application, as it is always running).  However, if the target application needs to be more power efficient, the LPO or MCGIRCLK should be used.  The LPO for the Kinetis devices is a fixed 1 kHz frequency and will, therefore, only be useful in applications that require millisecond resolutions.
View full article
           This is a demo of NFC device to read and write the contactless card. Kinets K60 tower board and NXP PN512 board are used for this test enviroment. These connected pins from K60 tower board to PN512 RF board are listed as below:   SPI1:     SPI1_SIN : PTE1/SDHC0_D0     SPI1_SCK : PTE2/SDHC0_DCLK     SPI1_SOUT : PTE3/SDHC0_CMD     SPI1_PCS0 : PTE4/SDHC0_D3     Reset:     PTB9   External interrupt:     PTA26         Because the SPI1 port is used as the host interface of pn512, it is necessary to enable the SPI1 driver in the user configuration file of MQX.           To open the project file in the /build folder with CW10.5.    And the PSP and BSP libraries had to be built before test image is built, as they are needed in this test project.   The following diagram shows the serial numbers and block data of reading from the test card of Mifare one.
View full article
Introduction Even with the prevalence of universal asynchronous receiver/transmitter (UART) peripherals on microcontrollers (MCUs), bit banged UART algorithms are still used.  The reasons for this vary from application to application.  Sometimes it is simply because more UARTs are needed than the selected device provides.  Maybe application or layout restrictions require certain pins to be used for the UART functions but the device does not route UART pins to the required package pins.  Maybe the application requires a non-standard or proprietary UART scheme. Whatever the reason, there are applications where a bit banged UART is used and is typically a pure software implementation (a timer is used and the MCU core controls a GPIO pin directly).  A better alternative may be to use Flextimer (FTM) or Timer/PWM Module (TPM) to take advantage of the features of these peripherals and possibly offload the CPU.  This document will explain and provide a sample application of how to emulate a UART using the FTM or TPM peripheral.  A Kinetis SDK example (for the TWR-K22F120M and FRDM-K22F platforms) and a baremetal legacy code example (for the FRDM-KL26Z) are provided here. UART protocol Before creating an application to emulate a UART, the UART protocol and encoding must be understood. The UART protocol is an asynchronous protocol that typically includes a start bit, payload (of 7-10 data bits), and a stop bit but does allow for many variations on the number of stop bits and what/how to transfer the data.  For this document and application example, the focus will be UART transmission that follows 1 start bit, 8 data bits, 1 stop bit, no parity, and no flow control.  The data will be transmitted least significant bit (LSB) first.  The following image is a block diagram of this transmission. However, this doesn't specify what the transmission looks like electrically. The figure below shows a screenshot of an oscilloscope capture of a UART transmission.  The data transmitted is 0x55 or a "U" in the ASCII representation. Notice that the transmission line is initially a logic high, and then transitions low to signal the start of the transmission.  The transmission line must stay low for one bit width for the receiver to detect it.  Then there are 8 data bits, followed by 1 stop bit.  In the case shown above, the data bits are 0x55 or 0b0101_0101.  Remember that the transmissions are sent LSB first, so the screenshot shows 1-0-1-0-1-0-1-0.  The last transition high marks the beginning of the stop bit and the line remains in that state until the start of the next transmission.  The receiver, being asynchronous, does not require any type of identifying transition to mark the end of the stop bit. FTM/TPM configuration The first question many may ask when beginning a project like this is "How do I configure the FTM/TPM when emulating a UART".  The answer to this depends on the aspect of this problem you are trying to solve.  Transmitting and receiving characters require two different configurations.  Transmission requires a configuration that manipulates the output pin at specific points in time.  Receiving characters requires a configuration that samples the receive pin and measures the time between pin transitions.  The FTM and TPM have the modes listed in the following table: The FTM and TPM have four different modes that manipulate an output:  Output compare (no pulse), Output compare (with pulse), Edge-aligned PWM, and Center-aligned PWM.  Neither PWM mode is ideal for the requirements of the application.  This is because the PWM modes are designed to produce a continuous waveform and are always going to return to the initialized state once during the cycle of the waveform.  However, the UART protocol may have continuous 1's or 0's in the data without pin transitions between them. The output compare mode (high-true or low-true pulse modes) is designed to only manipulate the pin once, and only produces pulses that are one FTM/TPM clock cycle in duration.  So this is obviously not desirable for the application.  The output compare mode (Set/Clear/Toggle on match) is promising.  This mode manipulates the output pin every cycle.  There are three different options:  clear output on match, set output on match, and toggle output on match.  Neither "clear output on match" nor "set output on match" are ideal as either would require configuration changes during the transmission of a character.  The "toggle output on match", however, can be used and is the selected configuration mode for this sample application. To receive characters, there is only one mode that is intuitive:  "the input capture mode".  This mode records the timer count value on an edge transition of the selected input pin.  Similar to the output compare mode chosen for the transmit functionality, the input capture mode has three sub-modes:  capture on rising edge, capture of falling edge, and capture on either edge.  It is clear from the descriptions that capture on either edge should be selected. Transmit encoding The selection of the FTM/TPM mode is moderately intuitive, but using this mode to emulate a UART transmission is not.  There are two issues that make this a little tricky. 1) The output pin is initialized low. However, the UART protocol needs the pin to begin in a logical high state. 2) The pin transitions on every cycle provided the channel value is less than the value of the MOD register. Due to continuous strings of 1's or 0's, it is necessary to have periods where the pin does not transition. Both of these points have workarounds. Output pin initialization For the first issue, the channel interrupt is first enabled and the channel value register is loaded with a value much less than the value in the MOD register.  Then in the channel interrupt service routine, the pin is sampled to ensure that it is in the logic high state and the channel interrupt is disabled (and will not be re-enabled throughout the life of the application).  The code for this interrupt service routine is as follows. Output pin control For the second issue, a method of not transitioning the pin value while allowing the timer to continue counting normally is necessary.  The Output Compare mode uses the channel value register to determine when the pin transition occurs.  If a value greater than MOD is written to the channel value register, the channel value will never match the count register and thus, a pin transition will never occur.  So, when a series of continuous 1's or 0's need to be transmitted, a value greater than the value in the MOD register can be written to the channel value register to keep the output pin in its current state. However, when a value greater than MOD is written to the channel value register, no channel match will occur (which means channel interrupts will not occur).  So the timer overflow interrupt must be used to continue writing values.  This requires the updates to be output pin to be planned ahead of time and makes the transmission algorithm a little tricky.  The following diagram displays when which values should be written to the channel value register at which points in time to generate the appropriate pulses. Writing a function to translate a number into the appropriate series of MOD/2 and MOD+1 values can be a little tricky. To do this, we must first notice that MOD/2 needs to be written when changes on the transmission pin are need and MOD+1 needs to be written when pin transmissions are not desired.   So, what logical function can we use to determine when a change has happened?  XOR is the correct answer.  So what two values need to be XOR'd together?  One value is obviously the value that we want to send.  But what is the second value?  It turns out that the second value is a shifted version of the value that we want to send.  Specifically, the second value is the desired value to send shifted to the left by one.  (You can think of it as sort of a "future" value of the desired value).  The following pictures show how to determine the queue to use for the transmission. Receive decoding The receive functionality has an advantage over the transmit functions in that it is possible to use DMA for the reception of characters.  This is because the receive function takes advantage of the input capture functionality of the FTM / TPM and therefore can use the channel match interrupt.  The example application provided with this document implements a DMA method and a non-DMA method for reception. First, the non-DMA method will be discussed. Before discussing the specifics of gathering the input pulse widths, some details of the receive pin need to be discussed. Detecting the start bit The receive pin needs to be able to determine when the start of the packet transmission begins.  To do this, the receive pin is configured as an FTM / TPM pin. At the same time, the GPIO interrupt functionality is configured on the same pin for a falling edge interrupt.  The GPIO interrupt capabilities are enabled in any digital mode, so the GPIO interrupt will still be able to be routed to the Nested Vector Interrupt Controller (NVIC).  The pin interrupt is used to start the FTM / TPM clock when a new character reception begins. In the GPIO interrupt for this pin, the FTM / TPM counter register is reset and the clock to the FTM / TPM is turned on.  The code for the GPIO interrupt service routine is shown below.  Receiving characters without DMA Now, when receiving characters and not using DMA, the first thing to understand is that the Interrupt Service Routine (ISR) will be used and it will mainly be used to record the captured count values.  The interrupt service routine also tracks the current receive character length and resets the counter register.  This is so that the values in the receive queue reflect the time since the last pin transition.  The interrupt function for the non-DMA application is shown below. Notice that the first two actions in the ISR are resetting the count register, and clearing the channel event interrupt flag.  Then the channel value is stored in the receive pulse width array (this is simply an array that holds the receive pulse widths of the current character being received).  Next, recvQueueLength, the variable which holds the current length of the character being received, is updated to reflect the latest character length.  The next step is to determine if the full character has been received.  This is determined by comparing recvQueueLength to the RECV_QUEUE_THRESH, which is the threshold as determined by multiplying the number of expected bits by the expected bit width plus another bit width (for the start bit).  If the recvQueueLength is greater than the RECV_QUEUE_THRESH, then a semaphore is set, recvdChar, to indicate that a full character has been received.  The FTM / TPM clock is turned off, and the pin interrupt functionality of the receive pin is enabled.  The final step in the interrupt routine is to increment the receive queue index, recvQueueIndex.  This variable points to the current entry in the receive queue array. Using DMA to receive characters When using DMA, the receive FTM / TPM interrupt is much different. The interrupt routine simply needs to clear the channel interrupt flag, stop the FTM / TPM timer, disable the DMA channel, and set the received character semaphore.  The character is then decoded outside of the interrupt routine.  The interrupt function when using DMA is shown below: Decoding the received pulse widths Once the array of pulse widths has been populated, the received character needs to be translated into a single number.  This varies slightly when using DMA and when not using DMA. However, the basic principle is the same.  The number of bits in a single entry is determined by dividing by the expected bit width and this is translated into a temporary array that contains 1's and 0's, and then that is used to shift in the appropriate number of 1's and 0's into the returned char variable.  A temporary array is needed because the values are shifted into the UART LSB first, so the bit must be physically flipped from the first entry to the last.  There is no logical operation that will do this automatically. The algorithm to perform this translation is shown below.  In this algorithm, note that recvPulseWidth is the array that contains the raw count value of the pulse width.  The array tempRxChar holds the decoded character in reverse order and rxChar is a char variable that holds the received character. Conclusion This document provides an overview of the UART protocol and describes a method for creating a software UART using the timing features of the FTM or TPM peripheral.  This method allows for accurate timing and while not relying entirely on the CPU and the latency associated with the interrupt and the GPIO pins.  The receive function is open to further optimization by using DMA, which can provide further unloading of the CPU.
View full article
Heart rate monitors measure the heart rate during exercise or vigorous activity and gauge how hard the patient is working. Newer heart rate monitors consist of two main components: a signal acquisition sensor/transmitter and a receiver (wrist watch or smart phone). In some cases, the signal acquisition is integrated into fabric worn by the user or patient. MCUs analyze the ECG signal and determine the heat rate, while an 8-bit MCU can suffice for a simple heart rate monitor. For more complex analysis, such as heart rate variability, activity level and breathing rate, a high-end 32-bit MCU may be used. Furthermore, low power wireless technologies are used to allow the sensor to communicate to the receiver. Freescale offers 8-bit and 32-bit MCUs that are applicable across the entire spectrum of heart rate monitors. In addition, the Freescale portfolio includes inertial sensors or accelerometers for activity monitoring and ZigBee® and proprietary wireless solutions to enable communication between the sensors and the receiver. For more information go to freescale.com/APLHRM
View full article
    Curve22519 is a Montgomery elliptic-curve. Such as Apple HomeKit, most of network and IoT software use it in Diffie-Hellman algorithm for key exchanging.     On the Security Kinets MCU chip,if we use just the software algorithm (base on mbedTLS), Curve25519 will spend 180ms for calculation of the shared security.     It is faster than other 256bit elliptic-curve with software algorithm, Because of the shared security calculation will take more than 1200ms with a Weierstrass’s BP256R1curve when use software algorithm.     With LTC ECC HW acceleration, it take only 16ms to calculate the shared security on 256bit elliptic-curve. Whatever you do, the speed of hardware acceleration always faster than the software algorithm.     Now that we should also want to use the LTC to accelerate the Curve22519. The LTC, however, only supported Weierstrass form curve, but Curve22519 is a Montgomery curve…     Although, we can't use LTC in Curve22519 directly, we can use it by mapping it to a Weierstrass form to use it.  As below, we gave parameters of these curves, transform formulas, example code and test result to show how and why to do it. 1. Curve parameter:    Cuvre22519 in Montgomery form:    Y^2 = X^3 + A*X^2 + X    Fp = 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed    A= 486662    Gx = 9    Gy = 0x20ae19a1b8a086b4e01edd2c7748d14c923d4d7e6d7c61b229e9c5a27eced3d9    Order of G point  =  0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed      Cuvre22519 in Weierstrass form :    Y^2 = X^3 + a*X + b    Fp = 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed    a  =  0x2aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa984914a144L    b  =  0x7b425ed097b425ed097b425ed097b425ed097b425ed097b4260b5e9c7710c864L    Gx = 0x2aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaad245a    Gy = 0x20ae19a1b8a086b4e01edd2c7748d14c923d4d7e6d7c61b229e9c5a27eced3d9    Order of G point  =  0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed    2. Calculation formula:   x_w –  x-coordinate value in  Weierstrass form   y_w –  y-coordinate value in  Weierstrass form   x_m - x-coordinate value in  Montgomory form   y_m -  we don’t care y-coordinate value in  Weierstrass mode   a_m – a coefficient of Montgomery equation (   Y^2 = X^3 + a_m * X^2 + X)   a_w – a coefficient of Weierstrass equation (   Y^2 = X^3 + a*X + b )   b_w – a coefficient of Weierstrass equation (   Y^2 = X^3 + a*X + b )     a)  x_w = (x_m + a_m/3)  %  p     b)  y_w ^2 = x_w ^ 3 + a_w*x_w + b_w c)   x_m = (x_w - a_m/3) % p You could reference these document as below: https://en.wikipedia.org/wiki/Curve25519 https://en.wikipedia.org/wiki/Montgomery_curve 3. example code: // public and private at Montgomery end #define M255_d      "0x7178DAC11D42AA5F39B10A62A8584DB0C8864564ADC9DF84EC0B13D9AEC220F8" #define M255_Qx     "0x3BA5048381744348D84E754B9944ABE080B37F7D4158DCE60CD79F66B98AB89E" // public and private at Weierstrass end #define WTS255_d    "0x09CC5CCF43C656C1309EE5A3491D5A8361607CEEB0C9B2B31A575E0FEF2B8835" #define WTS255_Qx   "0x3F4BDE110EE7AF71EF428D1018D188E35BAFB019F34F84E6465C5194B363DC2D" #define WTS255_Qy   "0x7540577CE6F920354E2A9D38CE88847D7447E66FA4D188AC75CB63C17210B718" #define WTS255_Qx_TO_M255_Qx     "0x14A13366643D04C74497E2656E26DE38B105056F48A4DA3B9BB1A6EA08B6B7DC" #define AM_INV3                  "0x2aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaad2451" int ecdh_wts_curve_end( ) {     unsigned int ticks;     int ret = 0;     size_t blen = 0, blen_peer = 0;     ecdh_context ecdh;     ecdh_context ecdh_peer;   // to_wts255     ecdh_context ecdh_peer_m255;     mpi R;     mpi_init(&R);     ecdh_init( &ecdh);     ecdh_init( &ecdh_peer);     ecdh_init( &ecdh_peer_m255);     MPI_CHK(ecp_use_known_dp( &ecdh.grp, ECP_DP_WTS25519 ));     MPI_CHK(ecp_use_known_dp( &ecdh_peer.grp, ECP_DP_WTS25519 ));     MPI_CHK(ecp_use_known_dp( &ecdh_peer_m255.grp, ECP_DP_M255 ));     blen = set_hash_buff(/*TEST_ECP_GRP_ID*/ECP_DP_WTS25519, &secret_buf, ecp_name);     if(blen == 0) {         ret = -1;         goto cleanup;     }     mpi_read_string(&ecdh.d, 16,  WTS255_d);     mpi_read_string(&ecdh.Q.X, 16,  WTS255_Qx);     mpi_read_string(&ecdh.Q.Y, 16,  WTS255_Qy);     mpi_lset(&ecdh.Q.Z, 1);     mpi_read_string(&ecdh_peer_m255.d, 16, M255_d);     mpi_read_string(&ecdh_peer_m255.Q.X, 16, M255_Qx);     mpi_init(&ecdh_peer_m255.Q.Y);     mpi_lset(&ecdh_peer_m255.Q.Z, 1);     // map M255 point to WTS255 point     my_timer_start();     mpi_read_string(&R, 16, AM_INV3);         mpi_add_mpi(&ecdh_peer.Q.X, &ecdh_peer_m255.Q.X, &R);     mpi_mod_mpi(&ecdh_peer.Q.X, &ecdh_peer.Q.X, &ecdh_peer_m255.grp.P);        mpi_lset(&R, 3);     mpi_exp_mod (&ecdh_peer_m255.Q.Y , &ecdh_peer.Q.X, &R, &ecdh_peer_m255.grp.P, NULL);     mpi_mul_mpi(&R, &ecdh_peer.grp.A, &ecdh_peer.Q.X);     mpi_mod_mpi(&R, &R, &ecdh_peer.grp.P);          mpi_add_mpi(&ecdh_peer_m255.Q.Y, &ecdh_peer_m255.Q.Y, &R);     mpi_add_mpi(&ecdh_peer_m255.Q.Y, &ecdh_peer_m255.Q.Y, &ecdh_peer.grp.B);     mpi_mod_mpi(&ecdh_peer_m255.Q.Y, &ecdh_peer_m255.Q.Y, &ecdh_peer.grp.P);     mpi_mod_sqrt(&ecdh_peer.Q.Y, &ecdh_peer_m255.Q.Y, &ecdh_peer_m255.grp.P);     // z = 1     mpi_lset(&ecdh_peer.Q.Z, 1);     MPI_CHK(ecp_copy(&ecdh.Qp,  &ecdh_peer.Q));     MPI_CHK(ecdh_calc_secret_wts2mont( &ecdh, &blen, secret_buf, blen, myrand, NULL));     mpi_read_string(&R, 16, AM_INV3);         mpi_sub_mpi(&ecdh_peer_m255.Q.X, &ecdh.Q.X, &R);     mpi_mod_mpi(&ecdh_peer_m255.Q.X, &ecdh_peer_m255.Q.X, &ecdh_peer_m255.grp.P);     ticks = my_timer_stop();     // print out message     polarssl_printf("Weierstrass curve shared secutiy:\n");     mpi_printf_string( &ecdh.z, 16);     polarssl_printf("%s ecdh peer to peer: %lu ticks, %d ms (%d) \n", ecp_name , ticks, ticks / (CLOCK_SYS_GetPitFreq(0) / 1000),CLOCK_SYS_GetPitFreq(0) );     cleanup:     if( ret !=0 )         polarssl_printf( "%s test Unexpected error, return code = %08X\n", ecp_name, ret );     mpi_free(&R);     ecdh_free( &ecdh);     ecdh_free( &ecdh_peer);     ecdh_free( &ecdh_peer_m255);         return( 0 );    } int ecdh_mont_curve_end( ) {     int verbose = 1;     unsigned int ticks;     int ret = 0;     size_t blen = 0, blen_peer = 0;     ecdh_context ecdh;     ecp_point Q_peer;          // peer public point     ecdh_init( &ecdh);     ecp_point_init( &Q_peer);     MPI_CHK(ecp_use_known_dp( &ecdh.grp, ECP_DP_M255 ));     blen_peer = set_hash_buff(ECP_DP_M255, &secret_buf_peer, ecp_name);     if(blen_peer == 0) {         ret = -1;         goto cleanup;     }     mpi_read_string(&ecdh.d, 16,  M255_d);     mpi_read_string(&ecdh.Q.X, 16,  M255_Qx);     mpi_init(&ecdh.Q.Y);   // don't care Y, only init it     mpi_lset(&ecdh.Q.Z, 1);     mpi_read_string(&Q_peer.X, 16, WTS255_Qx_TO_M255_Qx);     mpi_init(&Q_peer.Y);     mpi_lset(&Q_peer.Z, 1);        MPI_CHK(ecp_copy(&ecdh.Qp,  &Q_peer));     my_timer_start();     MPI_CHK(ecdh_calc_secret( &ecdh, &blen_peer, secret_buf_peer, blen_peer, myrand, NULL));     ticks = my_timer_stop();     polarssl_printf("%s ecdh peer to peer: %lu ticks, %d ms (%d) \n", ecp_name , ticks, ticks / (CLOCK_SYS_GetPitFreq(0) / 1000),CLOCK_SYS_GetPitFreq(0) );     polarssl_printf("Montogemory curve shared secutiy:\n");     mpi_printf_string( &ecdh.z, 16);     polarssl_printf( "passed\n" );     cleanup:     if( ret !=0 && verbose != 0 )         polarssl_printf( "%s test Unexpected error, return code = %08X\n", ecp_name, ret );     ecdh_free( &ecdh);     ecp_point_free( &Q_peer);     if( verbose != 0 )         polarssl_printf( "\n" );         return( 0 );    } ‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍ 4. Test result: Test result of curv25519 in  Weierstrass form with LTC:     2. Test result of curve25519 in Montgomery form with software algorithm:      We could see that the shared security both in Weierstrass form with LTC and Montgomery form are “0x1454BDCD6A94D6336AA5A76F3CB40BBE12B65A2CDC9DA6B478948906638896D1”. But the calculation speed with LTC was ten times faster than other one.
View full article
How to byte program SPI flash via QSPI QSPI module are used in many Kinetis MCU, like K8x, K27/28 and KL8x. QSPI expands the internal flash range and can run in a fast speed. Compared to DSPI, QSPI is very complex and often takes a lot of time to learn. In KSDK there are two QSPI demo which shows how to program SPI flash in DMA mode and polling mode. Both of them program the QSPI flash with a word type array. But can the QSPI module program SPI Flash in byte? Yes, this article shows how to do it. Device: FRDM_KL82Z Tool: MCUXpresso IDE Debug firmware: JLINK I build the test project base on KL82 SDK/driver_example/qspi/polling_transfer. To byte program SPI flash, a new LUT item must be added. uint32_t lut[FSL_FEATURE_QSPI_LUT_DEPTH] =    {/* Seq0 :Quad Read */          /* CMD:       0xEB - Quad Read, Single pad */          /* ADDR:       0x18 - 24bit address, Quad pads */          /* DUMMY:     0x06 - 6 clock cyles, Quad pads */          /* READ:       0x80 - Read 128 bytes, Quad pads */        …        …        [32] = QSPI_LUT_SEQ(QSPI_CMD, QSPI_PAD_1, 0x02, QSPI_ADDR, QSPI_PAD_1, 0x18),        [13] = QSPI_LUT_SEQ(QSPI_WRITE, QSPI_PAD_1, 0x1, 0, 0, 0),        …        /* Match MISRA rule */        [63] = 0}; This item tells system how to program a single byte. Then when we write the data to TxBuffer, we must write the byte 4 times. This is because a write transaction on the flash with data size of less than 32 bits will lead to the removal of four data entry from Txbuffer. The valid bit will be used and the rest of the bits will be discard. Then before we start programming, we must set the data size.      QSPI_SetIPCommandSize(EXAMPLE_QSPI,1);   After byte program, we can see the result from 0x68000000. Attachment is the demo project. You can find that 0x03 was written to 0x68000005 after running.
View full article
This document explains a potential issue where interrupts appear to be disabled after enterring debug mode. This is as a result of the NMI being active when debug is enabled.
View full article
You can put the code directory in the SDK_2.6.0_FRDM-K64F\boards\frdmk64f to use. 1、Introduction As is known to all, we use debugger to download the program or debug the device. FRDMK64 have the opsenSDA interface on the board, so wo do not need other’s debugger. But if we want to design a board without debugger but can download the program, we can use the bootloader. The bootloader is a small program designed to update the program with the interface such as UART,I2C,SPI and so on. This document will describe a simple bootloader based on the FRDMK64F.The board uses SD card to update the application. User can put the binary file into the card. When the card insert to the board ,the board will update the application automatically. The bootloader code and application code are all provided so that you can test it on your own board.   2、Bootloader’s implementation   The schematic for SD card is shown below. The board uses SDHC module to communicate with SD card.                                                  Figure 1.Schematic for SD card   We use the 2.6.0 version of FRDM-K64F’s SDK.You can download the SDK in our website. The link is “mcuxpresso.nxp.com”. The bootloader uses SDHC and fafts file system. So we should add files to support it.                   Figure 2.The support file   In main code, the program will wait until the card has inserted. Then it will find the file named “a000.bin” in sd card to update the application. If the file do not exist, the board will directly execute the application. If there is no application, the program will end. The following code shows how the program wait for inserting sd card. It will also check if the address has the application’s address.                      Figure 3.The code -- wait for inserting card   The following code shows how the program opens the binary file. If sd card doesn’t have the file, the program will go to the application. Figure 4.Open the binary file   If the program opens the file normally, the update will begin. It will erase 200k’s space from 0xa000. You can adjust it according to your project. Now I will explain update’s method in detail. Our data is written to the buffer called “rBUff”. The buffer size is 4K. Before write data to it, it is cleared.  Please note that when we erase or program the flash, we should disable all interrupts and when the operations finish we should enable the interrupts.  The file size will decide which way to write the data to flash.  1、If the size < 4k ,we just read the file’s data to buffer and judge if its size aligned with 8 byte. If not , we increase the size of “readSize” to read more data in our data buffer called “rBuffer”. The more data we read is just 0.    2、If the size > 4K, we use “remainSize” to record how much data is left. We read 4k each time until its size is smaller than 4k and then repeat step 1. When finish the operation at a  time, we should clear the buffer and increase the sector numer to prepare the next transmission. Figure 5.Write flash operation code   The way to clear the space is shown in the figure. It will initialize the flash and erase the given size from the given address.  “SectorNum” is used to show which sector to erase. Figure 6.Erase operation code   The following figure shows how to write the data to flash.              Figure 7.Program operation code    Before we go to the application, we should modify the configuration we did in the bootloader.     Close the systick, clear its value.     Set the VTOR to default value.     Our bootloader runs in PEE mode. So we should change it to FEI mode.     Disable the all pins. You should disable the global interrupt when run these codes. And don’t forget to enable the global interrupt. Figure 8.Deinitalization code   Then we can go to the application. Figure 9.Go to Application   3、Memory relocation The FRDMK64 has the 1M flash, from 0x00000000 to 0x00100000.As shown in figure 10,we use the 0xa000 as the application’s start address.            Figure 10.The memory map   Now, I will show you how to modify the link file for user application in different IDE. In IAR                                    Figure 11.IAR’s ICF In MDK Figure 12.MDK’s SCF   In MCUXpresso Figure 13.MCUXpresso’s flash configuration 4、Run the demo 1) Download the bootloader first. 2) Prepare a user application program. We use the “led blinky” as an example. 3) Modify the Link file. 4) Generate the binary file with your IDE, please name it as “a000.bin”. 5) Put it into the sd card like figure 5. Figure 14.SD card’s content        6) Insert the card. And power on. Wait for a moment, the application will execute automatically. 5、Reference 1) Kinetis MCU的bootloader解决方案 2) KEA128_can_bootloader
View full article
  CNN on FRDM_K64 1 Introduction Limited by resources, ordinary MCU is difficult to do some complex deep learning. However, although it is difficult, it can still be done. CNN, convolutional neural network, is a kind of deep learning algorithm, which can be used to solve the classification task. After the implementation of CNN, ordinary MCU can also be used as edge computing device. Next, we introduce how to run CNN on frdm-k64 to recognize handwritten numbers. The size of digital image is 28x28. 28x28 image as input for CNN will output a 1x10 matrix. There are few deep learning libraries written for MCU on the Internet. Even if there are, there will be various problems. NNoM framework is easy to transplant and apply, so we use it     2 Experiment 2.1 Required tools: frdm-k64, python 3.7, Pip, IAR, tcp232   2.2 Download the source code of deep learning framework, https://github.com/majianjia/nnom This is a pure C framework that does not rely on hardware structure. Transplantation is very convenient   2.3  we select the example ‘bubble’ to add the Inc, port and Src folders in NNoM to the project, as shown in the figure          Figure 1 Open the file ‘port.h’ . The definitation of NNOM_LOG is changed to PRINTF (__ VA_ ARGS__ ), Open the ICF file, and change the heap size to 0x5000, define symbol__ size_ heap__ = 0x5000; Malloc, which is used in this library, allocates memory from here. If it is small, it can't run the network   2.4 From the download framework, go into ‘mnist-simple/mcu’, which has trained file ‘weights.h’, and randomly generated handwritten image file, ‘image.h’. Add these two files to the project   2.5 Add headfile to ‘bubble.c’        #include "nnom_port.h" #include "nnom.h" #include "weights.h" #include "image.h"   2.6 Delete the original code, add the following code   nnom_model_t *model; const char codeLib[] = "@B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/\\|()1{}[]?-_+~<>i!lI;:,\"^`'.   "; /*******************************************************************************  * Code  ******************************************************************************/ void print_img(int8_t * buf) {     for(int y = 0; y < 28; y++)        {         for (int x = 0; x < 28; x++)               {             int index =  69 / 127.0 * (127 - buf[y*28+x]);                      if(index > 69) index =69;                      if(index < 0) index = 0;             PRINTF("%c",codeLib[index]);                      PRINTF("%c",codeLib[index]);         }         PRINTF("\r\n");     } }   // Do simple test using image in "image.h" with model created previously. void mnist(char num) {        uint32_t predic_label;        float prob;        int32_t index = num;        PRINTF("\nprediction start.. \r\n");               // copy data and do prediction        memcpy(nnom_input_data, (int8_t*)&img[index][0], 784);        nnom_predict(model, &predic_label, &prob);          //print original image to console        print_img((int8_t*)&img[index][0]);               PRINTF("\r\nTruth label: %d\n", label[index]);        PRINTF("\r\nPredicted label: %d\n", predic_label);        PRINTF("\r\nProbability: %d%%\n", (int)(prob*100)); }   int main(void) {     uint8_t ch;     /* Board pin, clock, debug console init */     BOARD_InitPins();     BOARD_BootClockRUN();     BOARD_InitDebugConsole();     /* Print a note to terminal */     model = nnom_model_create();        // dummy run        model_run(model);     PRINTF("\r\nwhich image to distinguish? 0-9 \r\n");     for(uint8_t i=0; i<10; i++)     {         print_img((int8_t*)&img[i][0]);     }     while(1)     {         PRINTF("\r\nwhich image to distinguish? 0-9 \r\n");         ch = GETCHAR();         if((ch >'9') || ch < '0')         {             continue;         }         PRINTF("\r\n");         mnist(ch-'0');     } }   An error will be reported when compiling ‘weights.h’, due to lack of few parameters. In layer [1], layer [4], layer [7], you need to add ‘division (1,1)’ after ‘stride (1,1)’. In this way, the compilation passes.   2.7 As a result, open the serial port software. At the beginning, the terminal will print out a variety of handwritten digital pictures, and then enter a number, The corresponded picture will be recognized.                                                    Figure 2 When we input ‘8’, the recognition is the handwriting '9'                        Figure 3   The ‘Truth label’ corresponds to IMG9_LABLE in ‘image.h’ and ‘Predicted label’ is the prediction results   3 training Through the above steps, we have realized a simple handwritten numeral recognition. Next, we will introduce ‘weights.h’. How to generate the weight model here? The image data here are all from MNIST digital set. How can we make a handwritten number for MCU to recognize?   3.1 Under ‘nnom-master\examples\mnist-simple’, there is a ‘mnist_ simple.py’. You need to run it to generate ‘weights.h’ and ‘image.h’. To run this, you need to install tensorflow, keras and so on. When you run it, you can use pip to install what is missing The network operation process is as shown in the figure                               Figure 4 Conv2d-> convolution operation, Maxpool-> pooling. The meaning of convolution operation is to extract the features of the image. Pooling is a bit like compressing data, which can reduce the running space. 28x28 input and output a 1x10 matrix, representing the possibility of 0-9   3.2 We can use the ‘Paint’ program of WIN to adjust the canvas to 28x28, write numbers on it and save it in PNG format. I wrote a ‘4’     Figure 5   Change the code as following.   nnom_model_t *model; uint8_t temp[28*28]={0}; const char codeLib[] = "@B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/\\|()1{}[]?-_+~<>i!lI;:,\"^`'.   "; /*******************************************************************************  * Code  ******************************************************************************/ void print_img(int8_t * buf) {     for(int y = 0; y < 28; y++)        {         for (int x = 0; x < 28; x++)               {             int index =  69 / 127.0 * (127 - buf[y*28+x]);                      if(index > 69) index =69;                      if(index < 0) index = 0;             PRINTF("%c",codeLib[index]);                      PRINTF("%c",codeLib[index]);         }         PRINTF("\r\n");     } }     void mnist_pic(uint8_t *temp) {        float prob;     uint32_t predic_label;        PRINTF("\nprediction start.. \r\n");          // copy data and do prediction        memcpy(nnom_input_data, (int8_t*)temp, 784);        nnom_predict(model, &predic_label, &prob);          //print original image to console        print_img((int8_t *)temp);        PRINTF("\r\nPredicted label: %d\n", predic_label);        PRINTF("\r\nProbability: %d%%\n", (int)(prob*100)); }   int main(void) {     /* Board pin, clock, debug console init */     BOARD_InitPins();     BOARD_BootClockRUN();     BOARD_InitDebugConsole();     /* Print a note to terminal */     model = nnom_model_create();        // dummy run        model_run(model);     while(1)     {         PRINTF("\r\n Send picture by serial\r\n");            DbgConsole_ReadLine(temp,784);         PRINTF("\r\n Got picture\r\n");           mnist_pic(temp);     } }   3.3 Then use pic2mnist.py(see the attachment), run this script with CMD and enter 'Python pic2mnist.py 1. PNG ', 1. PNG is the image to be parsed, and then ‘content.txt’ will be generated. The file contains the data of the picture. Send the data to the MCU through the serial port. Note that ‘Send as Hex’ should be checked. Similarly, the handwritten picture will be displayed first, and then the picture will be recognized.                                                           Figure 6   We can see that '4' was identified
View full article
Reference Solution being developed with Kinetis V (also can be done with a Kinetis K device) of a Class-D audio amplifier. 16-bit ADC sampling the audio input FlexTimer doing the PWM's for the Class-D amplifier DC/DC switched power supply with input of 12V and output of 130V to 180V (generates the power you need for making some good noise - 1kW) being controlled by the Kinetis MCU also. Capabiltiy of Audio processing/filtering using the Cortex-M4 DSP capabilities. Solution originally designed for cost-effective Automotive aftermarket sound systems. But can be adapted for implementing other audio amplifier applications also in the consumer space! Can you thing of cool applications/markets that this solution can be also quickly adapted? Soon, plan to make the reference solution design files available in the community. Stay tunned. Cheers! PK
View full article
My customer wanted to use K60 in his design but he only has the Keil IDE, so I helped to port some examples in KINETIS_SC for him as a starting point. The attachment is my porting work, which also includes a exe file to create new keil project. You may refer to "keil\build\uv4\make_new_project_keil.exe" for details. Hope that helps, B.R Kan
View full article
Dear all :      I would like to share an IoT application note to you. The note will help us to setup a FRDM-K64F to connect to Microsoft Azure and get alarm message from Azure. Detail please refer to attachment. Demonstration : IoT client (FRDM-K64F) report data to Cloud (Microsoft Azure) IoT client receive data from Cloud Could computing IoT client data and take action Tools : FRDM-K64F ( http://www.freescale.com/FRDM-K64F ) Device Explorer ( http://aka.ms/iot-hub-how-to-use-device-explorer ) Visual Studio 2015 SSH client ( PuTTY  or Tera Term ) mbed  ( http://www.mbed.com ) Microsoft Azure ( https://azure.microsoft.com )
View full article
        在我们嵌入式工程应用中,中断作为最常用的异步手段是必不可少的,而且在一个应用程序中,一个中断往往是不够用的,多个中断混合使用甚至多级中断嵌套也经常会使用到,而这样就涉及到一个中断优先级的问题。         以我们最熟悉的Cortex-M系列为例,我们知道ARM从Cortex-M系列开始引入了NVIC的概念(Nested Vectors Interrupts Controller),即嵌套向量中断控制器,以它为核心通过一张中断向量表来控制系统中断功能,NVIC可以提供以下几个功能: 1)可嵌套中断支持; 2)向量中断支持; 3)动态优先级调整支持; 4)中断可屏蔽。         抛开其他不谈,这里我们只说说中断优先级的问题。我们知道NVIC的核心工作原理即是对一张中断向量表的维护上,其中M4最多支持240+16个中断向量,M0+则最多支持32+16个中断向量,而这些中断向量默认的优先级则是向量号越小的优先级越高,即从小到大,优先级是递减的。但是我们肯定不会满足于默认的状态(人往往不满足于约束,换句俗话说就是不喜欢按套路出牌,呵呵),而NVIC则恰恰提供了这种灵活性,即支持动态优先级调整,无论是M0+还是M4除了3个中断向量之外(复位、NMI和HardFault,他们的中断优先级为负数,它们3个的优先级是最高的且不可更改),其他中断向量都是可以动态调整的。         不过需要注意的是,中断向量表的前16个为内核级中断,之后的为外部中断,而内核级中断和外部中断的优先级则是由两套不同的寄存器组来控制的,其中内核级中断由SCB_SHPRx寄存器来控制(M0+为SCB_SHPR[2:3],M4为SCB_SHPR[1:3]),外部中断则由NVIC_IPRx来控制(M0+为NVIC_IPR[0:7],M4为NVIC_IPR[0:59]),如下图所示: M0+中断优先级寄存器: M4中断优先级寄存器:         其中M4所支持的动态优先级范围为0~15(8位中只有高四位[7:4]才有效),而M0+所支持的动态优先级范围则为0~3(8位中只有高两位[7:6]才有效),而且秉承着号越小优先级越高的原则(0最高,15或3为最小),同时也间接解释了为什么复位(-3)、NMI(-2)和HardFault(-1)优先级最高的原因,很简单,人家都是负的了,谁还能比他们高,呵呵,而且这三位中复位优先级最高,NMI其次,HardFault最低(这个最低仅限于这三者)。 下面给出个ARM CMSIS库中关于M0+和M4中断优先级设置的API函数NVIC_SetPriority(IRQn_Type IRQn, uint32_t priority)实现供大家来参考: M0+: NVIC_SetPriority(IRQn_Type IRQn, uint32_t priority) {   if(IRQn < 0) {     SCB->SHP[_SHP_IDX(IRQn)] = (SCB->SHP[_SHP_IDX(IRQn)] & ~(0xFF << _BIT_SHIFT(IRQn))) |         (((priority << (8 - __NVIC_PRIO_BITS)) & 0xFF) << _BIT_SHIFT(IRQn)); }  /* set Priority for Cortex-M  System Interrupts */   else {     NVIC->IP[_IP_IDX(IRQn)] = (NVIC->IP[_IP_IDX(IRQn)] & ~(0xFF << _BIT_SHIFT(IRQn))) |         (((priority << (8 - __NVIC_PRIO_BITS)) & 0xFF) << _BIT_SHIFT(IRQn)); }   /* set Priority for device specific Interrupts  */ } M4: void NVIC_SetPriority(IRQn_Type IRQn, uint32_t priority) {   if(IRQn < 0) {     SCB->SHP[((uint32_t)(IRQn) & 0xF)-4] = ((priority << (8 - __NVIC_PRIO_BITS)) & 0xff); } /* set Priority for Cortex-M  System Interrupts */   else {     NVIC->IP[(uint32_t)(IRQn)] = ((priority << (8 - __NVIC_PRIO_BITS)) & 0xff);    }        /* set Priority for device specific Interrupts  */ }
View full article
Here you will find the code and project files corresponding to the I2C-Accelerometer project. The accelerometer/magnetometer is connected to the I2C port, although bot the accelerometer and magnetometer are contained within a single package, they must be initialized individually. In this example the measurements from both devices (X,Y and Z axis) is performed and displayed at the serial terminal. In order to compile the project, the following library must be imported: FXOS8700Q.h Code: #include "mbed.h" #include "FXOS8700Q.h" //I2C lines for FXOS8700Q accelerometer/magnetometer FXOS8700Q_acc acc( PTE25, PTE24, FXOS8700CQ_SLAVE_ADDR1); FXOS8700Q_mag mag( PTE25, PTE24, FXOS8700CQ_SLAVE_ADDR1); //Temrinal enable Serial pc(USBTX, USBRX); MotionSensorDataUnits mag_data; MotionSensorDataUnits acc_data; int main() {     float faX, faY, faZ;     float fmX, fmY, fmZ;     acc.enable();     printf("\r\n\nFXOS8700Q Who Am I= %X\r\n", acc.whoAmI());     while (true)     {         acc.getAxis(acc_data);         mag.getAxis(mag_data);         printf("FXOS8700Q ACC: X=%1.4f Y=%1.4f Z=%1.4f  ", acc_data.x, acc_data.y, acc_data.z);         printf("    MAG: X=%4.1f Y=%4.1f Z=%4.1f\r\n", mag_data.x, mag_data.y, mag_data.z);         acc.getX(&faX);         acc.getY(&faY);         acc.getZ(&faZ);         mag.getX(&fmX);         mag.getY(&fmY);         mag.getZ(&fmZ);         printf("FXOS8700Q ACC: X=%1.4f Y=%1.4f Z=%1.4f  ", faX, faY, faZ);         printf("    MAG: X=%4.1f Y=%4.1f Z=%4.1f\r\n", fmX, fmY, fmZ);                 wait(1.0);     } }
View full article
The ARM Cortex-M4 Kinetis K50 MCU integrates an analog measurement engine consisting of integrated operational and transimpedance amplifiers and high-resolution ADC and DAC modules that make it ideal for portable healthcare and medical applications. For more information visit www.freescale.com/kinetis
View full article