Kinetis Microcontrollers Knowledge Base

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

Kinetis Microcontrollers Knowledge Base

Discussions

Sort by:
@@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
        IAR使用过程中有一点不太方便的是:当我们打开一个工程之后,如果再直接双击其他eww文件试图打开另外的工程,那么原来的工程就会被覆盖。解决这个问题的方法是:        1. 双击FileTypesMan.exe(该软件见附件,32位系统请解压filetypesman_x86.zip文件,64位系统请解压filetypesman_x64.zip文件)。打开该软件之后,找到.eww 格式并单击一下,显示界面如下图所示:             2. 双击open 所在行,对此条目进行更改,将Command-Line 中的内容:C:\PROGRA~2\IARSYS~1\EMBEDD~1.0\common\bin\IarIdePm.exe "%1" 先复制出来,Default Action 不选,Disable勾选,如下图所示:       3.在FileTypesMan界面的下方区域点击右键,选择New Action,如下图所示:            4.新建action 如下图所示,Action Name和Menu Caption 可随便命名,Command-Line 将上一步复制的内容粘贴过来即可。Default Action 勾选,Disable不选。          5. 最后配置如下图所示:       经过以上简单设置之后,就可以通过直接双击eww文件打开多个工程了。                  Original Attachment has been moved to: filetypesman_x64.zip Original Attachment has been moved to: filetypesman_x86.zip
View full article
By Paolo Alcantara RTAC Americas Mexico 2012 USB device firmware update (DFU) bootloader provides an easy and reliable way to load new user applications to devices having preloaded the USB DFU bootloader. After loaded, the new user application is be able to run in the MCU. The USB DFU bootloader requires an application running on a PC (USB DFU PC application). The DFU PC application supports loading the firmware to the device by using specific requests as stated in the USB DFU specification class. The USB DFU bootloader is able to enumerate in two ways: -USB composite device mode: also know as run time mode. It’s formed of a DFU device plus another USB device class. For this implementation, human interface device (HID) mouse device is used to avoid increasing the bootloader memory size. The MCU must be in the following conditions prior to enter to this mode: MCU doesn’t contain a valid firmware image or doesn’t contain firmware. An external action is applied to MCU such as pressing a button during a reset event. This is dependant of the USB DFU bootloader implementation. -DFU device mode: used when DFU is ready to upload or download firmware images by a request made from the USB DFU PC Application. Prior to this mode, the MCU was in USB composite device mode. A bootloader is a small application that is used to load new user applications to devices. Therefore, the bootloader needs to be able to run in both, the user application and bootloader mode. As an example: After reset, the device attempts to run the user application. If the user application is not found or corrupted, the device automatically runs into bootloader mode. In case the application is valid and user wants to run bootloader program, external intervention is required such as pressing a specific key at reset time to force the device entering to bootloader mode. Full application note and software attached.
View full article
The SysTick is a part of the Cortex-M0+ core and so is not chip specific - for details of the Cortex core you generally need to use ARM documents. For SysTick: http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.dai0179b/ar01s02s08.html By summary, the SysTick is configured through four registers: 1. SysTick Control and Status(CSR): basic control of SysTick e.g. enable, clock source, interrupt or poll COUNTFLAG: count-down flag, if down to 0, then this bit will be set to 1, otherwise, it will be 0. CLKSOURCE:  when using internal core clock, it will be 1. If using external clock, it will be 0. TICKINT: interrupt enabled when setting to 1. ENABLE: counter enabled when setting to 1. 2. SysTick Reload Value(RVR): value to load Current Value register when 0 is reached. 3. SysTick Current Value (CVR): the current value of the count down. 4.SysTick Calibration Value(CALIB): contain the number of ticks to generate a 10ms interval and other information, depending on the implementation. TENMS: tick value for 10 ms. To configure the SysTick you need to load the SysTick Reload Value register with the interval required between SysTick events. The timer interrupt or COUNTFLAG bit is activated on the transition from 1 to 0, therefore it activates every n+1 clock ticks. If a period of 100 is required 99 should be written to the SysTick Reload Value register. See attached code on how to generate microsecond delay.
View full article
Kinetis Programming using PE multilink Connect All the VDD to +3.3V and all VSS to GND. Connect 10K pullup resistor to RESET_b pin of the controller. If the controller have the option of JTAG/SWD/EZport make sure to connect 10K pullup resistor to NMI_b or EZP_CS_b pin. NMI_b pins selects the interrupt to highest priority so the controller won't enter into programming mode and EZP_CS_b pin is used for selecting Ezport programming method.   At factory reset condition, all the controller is in the continuous watchdog enabled mode and constantly resetting and the voltage level on the reset pin will be approx 1.64V after adding the pullup resistor as mentioned in point 2. Do not add any filter capacitor on the reset pin while programming the controller for the first time. As it will not let the logic level go low while programming. Which is essential. On probing the reset pin to the oscilloscope the following will be the pattern Before programming we need to mass erase the controller otherwise it will be in continuous reset mode. And to do that we need to configure SWD/JTAG mode. The following configurations for K20P48 LQFP in SWD mode. For mass erase following steps we need to follow. Search for thunderbolt icon in code warrior ie flash programmer and click on the drop-down menu on the icon.     Click on edit then      After configuring the above settings then click on the erase whole device option shown on step 9. If the microcontroller have JTAG/SWD and EZPORT then connect the microcontroller to JTAG port using PORT B of multilink with 20 pin headder. Try avoiding jumpers instead connect the 20 pin cable provided with PE multilink programmer. As all GND pins need to be connected on board's GND.   If the problem still persist then refer to this link Freescale community programmer
View full article
Recently I was told that there really lack of enough document && demo regarding the lwIP stack with SDK. So I would like to share more detail regarding this topic, and hope it will been helpful and useful. Introduction Small independent implementations of the TCP/IP protocol suite One of the most widely used TCP/IP stack Under a BSD-style license Support run in both bare metal and RTOS environment Suitable for use in embedded system with tens of free RAM and room for around 40 kilobytes of code ROM lwIP stack on KSDK     - <ksdk_install_dir>/middleware/tcpip/lwip lwIP stack on KSDK - Code Structure lwIP code structure is shown as below: src     This subfolder includes the latest stable lwIP 1.4.1 source code which can be downloaded from this link: download.savannah.gnu.org/releases/lwip/ port     This subfolder includes the adapter code which adapts lwIP stack to SDK. lwIP stack on KSDK - Source Code Structure of source code under is shown below: lwIP stack on KSDK – Adapter code <ksdk_install_dir>/middleware/tcpip/lwip/port <ksdk_install_dir>/middleware/tcpip/lwip/port/arch These Adapter code could be divided into four types:         Ethernet driver adapter code         OSA adapter code         Additional code         lwIP stack configuration code Ethernet Driver Adapter Code Provide Ethernet relevant interface including    − Ethernet hardware initialization    − Network interface initialization    − Send packet to Ethernet hardware    − Receive packet from Ethernet hardware    − Pass packet to lwIP stack Both polling and interrupt mode are provided for packet receiving     - In <ksdk_install_dir>/platform/drivers/inc/fsl_enet_driver.h,          #define ENET_RECEIVE_ALL_INTERRUPT 0 to enable polling mode.          Or set          #define ENET_RECEIVE_ALL_INTERRUPT 1 to enable interrupt mode. Ethernet driver adapter code provides ENET_receive API for polling mode Under RTOS environment, a separate task executing ENET_receive for packet receiving is created in Ethernet hardware initialization code for polling mode Under Bare Metal environment the ENET_receive API need to be called endlessly to do packet receiving OSA Adapter Code Provide OS dependent types and interface for RTOS environment (configured NO_SYS = 0)    −Semaphore    −Mutex    −Mailbox    −Thread Provide time tick for bare metal environment(NO_SYS = 1) sys_now to get the current time sys_assert to print an assertion messages and abort execution. Additional Code Provide definition and interface for:    −Typedefs    −Compiler hints for packing and platform specific    −Diagnostic output lwIP Stack Configuration Code Provides a way to override much of the behavior of lwIP based on opt.h.     − Module support (Code size)           Default inclusions:     ARP (LWIP_ARP)     UDP (LWIP_UDP) and UDP-Lite (LWIP_UDPLITE)     TCP (LWIP_TCP) -- this is a big one!     Statistics (LWIP_STATS)          ……          Default exclusions:    DHCP (LWIP_DHCP)    AUTOIP (LWIP_AUTOIP)    SNMP (LWIP_SNMP)    IGMP (LWIP_IGMP)    PPP (PPP_SUPPORT)    − Memory management (RAM usage)              lwIP’s custom heap-based mem_malloc              C standard library malloc and free              Memory pools lwIP Stack Porting Guide    Possible Situation for Porting New Soc with Limited RAM In current KSDK, the main RAM consumption for lwIP is show below: If resource on the new platform is not enough, could reduce ram consumption for ram_heap and pbuf_pool.         In lwip/port/lwipopts.h: #define MEM_SIZE                (12*1024)    /**the size of ram_heap/ #define PBUF_POOL_SIZE          10      /*the number of buffers in the pbuf pool. */ #define PBUF_POOL_BUFSIZE       1518 /* the size of each pbuf in the pbuf pool. */ pbuf_pool also support dynamically allocate from ram_heap.        In lwip/include/opt.h:          #define MEMP_MEM_MALLOC     1 /*Use mem_malloc/mem_free to do allocate*/ Use libc malloc/free to manage the memory allocation instead of mem_malloc/mem_free, memory definition for ram_heap is not needed.         #define MEM_LIBC_MALLOC       1 /*Use malloc/free/realloc provided by C-library*/   New Soc NOT Support PIT timer OSA adapter code should provide Bare metal lwIP stack with a 1ms period timer. Current the code use pit timer to do this and the definition in sys_arch.c is as below: #define HWTIMER_LL_DEVIF    kPitDevif      // Use hardware timer PIT #define HWTIMER_LL_SRCCLK   kBusClock     // Source Clock for PIT #define HWTIMER_LL_ID       3 #define HWTIMER_PERIOD          1000      // 1 ms interval If the new platform does not provide PIT, we could use other hardware timers to implement the 1ms period timer. Lightweight TCP/IP (lwIP) Stack Porting v Lightweight TCP/IP (lwIP) Stack Porting Guide Lightweight TCP/IP (lwIP) Stack Porting Guide
View full article
Here you can find both the code and project files for the Serial communication project, in this example the serial port (UART) is configured to establish communication between the computer using a serial terminal and the evaluation board. The default baud rate for the serial port is 9600 bauds. The code also implements an echo function, any key pressed in the computer's keyboard will be captured and displayed in the serial terminal. If your computer does not have a serial terminal you can download Tera Term from the following link: Tera Term Open Source Project The communication is established through the USB cable attached to the OpenSDA USB port. Code: #include "mbed.h" //Digital output declaration DigitalOut Blue(LED3); //Serial port (UART) configuration Serial pc(USBTX,USBRX); int main() {     Blue=1;     pc.printf("Serial code example\r\n");        while(1)     {         Blue=0;         pc.putc(pc.getc());     }    }
View full article
Although most of us have a basic understanding of how an ADC works and how to understand some of the basic figures that define an ADC performance, that is far from really understanding how to fully interpret and use the figures depicted in a datasheet ADC section. With all those numbers it is easy to get lost on which ones to look at when we want to know how it will react to conditions such as frequency, signal amplitude, temperature, etc; having such knowledge would allow us to better fit a specific ADC to your application and take full advantage of its features. Having this in mind I took the time to compile some information related to what the most common figures that describe an ADC performance depicted in a datasheet mean, most of the material can be found in any Analog to Digital Conversion theory book; as I mentioned before this is just a general compilation of knowledge I hope will help you better understand those specifications. It assumes those of us who use datasheets are somehow familiar with the basic working of ADCs, so I will spare the basic concepts. Now down to business, this is a extract of a typical ADC section from a microcontroller's datasheet: I am almost certain not a lot of people who use microcontrollers, and more specifically ADCs; have a clear idea of what Total Unadjusted Error, Integral Non-Linearity or Differential Non-Linearity describe in the behavior of an ADC. Even though I will try to describe in detail the most common parameters I might miss some others and there is the possibility some of the information might not be as accurate as I would like it to be, if any of you reading this brief document have specific questions regarding any parameter I describe or miss by all means comment. Common ADC electrical characteristics depicted in datasheets EQ          Quantization error      Since the analog input to an ADC can take any value, but the digital output is quantized, there may be a difference of up to ½ Less Significant Bit between the actual analog input and the exact value of the digital output. This is known as the quantization error or quantization uncertainty as shown below. In ac (sampling) applications this quantization error gives rise to quantization noise. SINAD, SNR and ENOB (Signal to Noise plus Distortion, SIgnal to Noise Ratio and Effective Number of Bits)      Signal-to-Noise-and Distortion (SINAD, or S/(N + D) is the ratio of the rms signal amplitude to the mean value of the root-sum square (rss) of all other spectral components, including harmonics, but excluding dc. SINAD is a good indication of the overall dynamic performance of an ADC      as a function of input frequency because it includes all components which make up noise (including thermal noise) and distortion. It is often plotted for various input amplitudes. SINAD is equal to THD + N if the bandwidth for the noise measurement is the same. SINAD is often converted      to effective-number-of-bits (ENOB) using the relationship for the theoretical SNR of an ideal N-bit ADC: SNR = 6.02N + 1.76 dB, the equation is solved for N, and the value of SINAD is substituted for SNR.      Effective number of bits (ENOB) is a measure of the dynamic performance of an analog to digital converter and its associated circuitry. The resolution of an ADC is specified by the number of bits used to represent the analog value, in principle giving 2 N signal levels for an N-bit signal. However, all real ADC circuits introduce noise and distortion. ENOB specifies the resolution of an ideal ADC circuit that would have the same resolution as the circuit under consideration. Often ENOB is calculated using the relationship for the theoretical SNR of an ideal N-bit ADC: SNR =      6.02N + 1.76 dB, the equation is solved for N, and the value of SINAD is substituted for SNR. SFDR      Spurious Free Dynamic Range     One of the most significant specification for an ADC used in a communications application is its spurious free dynamic range (SFDR). SFDR of an ADC is defined as the ratio of the rms signal amplitude to the rms value of the peak spurious spectral content measured over the bandwidth      of interest. SFDR is generally plotted as a function of signal amplitude and may be expressed relative to the signal amplitude (dBc) or the ADC full-scale (dBFS) as shown in Figure n. For a signal near full-scale, the peak spectral spur is generally determined by one of the first few harmonics of the fundamental. However, as the signal falls several dB below full-scale, other spurs generally occur which are not direct harmonics of the input signal. This is because of the differential nonlinearity of the ADC transfer function as discussed earlier. Therefore, SFDR      considers all sources of distortion, regardless of their origin. INL      Integral Non-Linearity     Integral nonlinearity (acronym INL) is the maximum deviation between the ideal output of an ADC and the actual output level (after offset and gain errors have been removed). The transfer function of an ADC should ideally be a line and the INL measurement depends on the ideal line selected. Two often used lines are the best fit line, which is the line that minimizes the INL result and the endpoint line which is a line that passes through the points on the transfer function corresponding to the lowest and highest input code. In all cases, the INL is the maximum distance between the ideal line selected and the actual transfer function. DNL        Differential Non-Linearity      Differnetial NonLinearity relates to the linearity of the code transitions of the converter. In the ideal case, a change of 1 LSB in digital code corresponds to a change of exactly 1 LSB of analog signal. In an ADC there should be exactly 1 LSB change of analog input to move from one           digital transition to the next. Differential linearity error is defined as the maximum amount of deviation of any quantum (or LSB change) in the entire transfer function from its ideal size of 1 LSB. Where the change in analog signal corresponding to 1 LSB digital change is more or less than 1 LSB, there is said to be a DNL error. The DNL error of a converter is normally defined as the maximum value of DNL to be found at any transition across the range of the converter. The following figure shows the non-ideal transfer functions for an ADC and shows the effects of the DNL error.      A common result of excess DNL in ADCs is missing codes resulting from DNL < –1 LSB. THD      Total Harmonic Distortion Total harmonic distortion (THD) is the ratio of the rms value of the fundamental signal to the mean value of the root-sum-square of its harmonics (generally, only the first 5 are significant). THD of an ADC is also generally specified with the input signal close to full-scale, the harmonics of the input signal can be distinguished from other distortion by their location in the frequency spectrum. The second and third harmonics are generally the only ones specified on a data sheet because they tend to be the largest. EFS     Full Scale Error Full-scale error can be defined as the difference between the actual value triggering the transition to full-scale and the ideal analog full-scale transition value. Full-scale error is equal to the offset error + gain error Offset error The transfer characteristics of both DACs and ADCs may be expressed as a straight line given by D = K + GA, where D is the digital code, A is the analog signal, and K and G are constants. In a unipolar converter, the ideal value of K is zero. The offset error is the amount by which the actual value of K differs from its ideal value. Gain error The gain error is the amount by which G differs from its ideal value, and is generally expressed as the percentage difference between the two, although it may be defined as the gain error contribution (in mV or LSB) to the total error at full-scale. TUE      Total Unadjusted Error This is the result of performing conversions without having calibrated the ADC, it is dominated by the uncalibrated gain and uncalibrated offset terms in the data sheet. Although most devices will be well within the data sheet limits, it should be noted that they are not centered around zero and full range of the incoming analog signal is not guaranteed. Therefore, an uncalibrated ADC will always show unknown levels of gain and offset error, thus reflecting the worst case of conversion error the module can provide.
View full article
1. CycloneMAX,    支持 Kinetis, ColdFire V2/V3/V4, Power MPC5xx/8xx, Qorivva MPC5xxx, DSC, MAC7xxx    PE Micro, http://www.pemicro.com/ 2. Flasher ARM     支持ARM公司全系列内核,包括传统的ARM7, ARM9和ARM11,已经新的Cortex-A, Cortex-M和Cortex-R系列,可以给目标板供电.    Segger, SEGGER - The Embedded Experts - Flasher ARM 3. Flasher Portable    支持ARM公司全系列内核,包括传统的ARM7, ARM9和ARM11,已经新的Cortex-A, Cortex-M和Cortex-R系列,电池供电,便携式烧写器.    Segger, SEGGER - The Embedded Experts-Flaser Portable 4. SmartPRO    支持 Kinetis, S12, S12X, ColdFireV2.    周立功,http://www.zlgmcu.com/ 5. MCP-104    支持飞思卡尔ARM based Microcontroller Kinetis.    祥佑科技(Micetek), http://www.micetek.com 6. 西尔特编程器,http://www.xeltek.com 7. 河洛编程器,http://www.hilosystems.com.tw
View full article
This years annual hacker security conference known as DEFCON used a couple of NXP devices for this years electronic badge. This document is to explain how to program the device and add extra components. The badge was developed by Grand Idea Studio, with engineering help from NXP, and this presentation has details about the development of the badge. I'm the NXP systems engineer that was helping people get started with reprogramming their badge at Defcon, and wanted to create something that gives all the details on how to do that yourself.  Full schematics and firmware source code can be found at: http://www.grandideastudio.com/defcon-27-badge/   The badge has these two NXP devices:  KL27  - MKL27Z64VDA4 - 48Mhz ARM Cortex M0+ microcontroller w/ 64KB flash (Datasheet and Reference Manual) NXH2261UK- Near Field Magnetic Induction (NFMI) chip for the wireless communication. Has a range on the badge of about 6 inches (15cm), but the technology can work a bit further. It's often found in high end headphones because BLE waves are disrupted by your head but these waves aren't. Also less power consumption. Using the serial port: There's a serial interface which prints out helpful information and there's some "secrets" available if you have a completely leveled up badge. It'll also be really helpful if you're writing new code to hack your badge for printf debugging. Note that you cannot program the board by default over the serial port. This particular chip doesn't support that, though some of our other chips do. It of course would be possible to write a serial bootloader for it, but that's definitely not beginner level. You'll need two pieces of hardware: 1) Header Pins 3) Serial-to-USB converter Header Pin: You can solder on a header to the PCB footprint. Because of the quartz, the leads would need to be flat on the PCB. A Harwin M20-8770442 will fit the footprint and is what was provided at the soldering village and what you see in the photos below. You could also try creating your own header.  Serial to USB Converter: Since almost no computer today comes with a serial port, a serial to USB converter dongle is needed. It'll have four pins: GND, Power, TX, and RX. The DEFCON badge runs at 1.8V, but the chip itself is rated up to 3.6V, so a 3.3V dongle can be used *as long as you do not connect the power pin on the serial header*. You only need to connect GND, RX, and TX. In a production design you would not want an IO voltage above VCC, but for hacking purposes it'll work, and I've used it all week without an issue on multiple boards.  There's a lot of options. Here's a 1.8V one if you want to be extra cautious or a 3.3V one that already comes with connectors for $8. Anything that transmits at 1.8V or 3.3V will work so you may already have one, but again, just don't connect the power pin.    Software: You'll need to install a serial terminal program like TeraTerm or Putty.  1) Plug the 3.3V or 1.8V USB converter dongle into your computer and it should enumerate as a COM port.  2) Connect the GND line on the dongle to GND on the header 3) Connect the TX pin on the dongle to the RX pin on the header 4) Connect the RX pin on the dongle to the TX pin on the header (it is not RX to RX, I spent 2 whole days tearing my hair out over that during my robotics project in college) 5) DO NOT CONNECT THE POWER PIN  5) Should look like the following when finished 6) In your serial terminal program, connect to the COM port your dongle enumerated as 7) Find the serial port settings menu (in TeraTerm it's in Setup->Serial Port from the menu bar) , and set the baud rate to 115200. The other settings should not need to be changed (8 data bits, no parity, 1 stop bit).  😎 In the terminal, press enter. You should get a > prompt 9) In the terminal, press the '?' key on your keyboard, and hit enter, you'll see the menu.         10) Note that the key you press won't show up in the terminal, but just press Enter and then the command will be run 11) Hit Ctrl+x to exit interactive mode and turn back on the radio.  12) While not in interactive mode, the terminal will display the transmit packet of any badge you bring close to it.  Reprogramming Your Badge: Hardware:  There's two pieces of hardware needed: 1) Programmer/debugger 2) Programming cable Program Debugger: Most any ARM Cortex M debug programmer can be used, as the KL27 chip has a ARM M0+ core. I'd recommend the LPC-Link2 as it's only $20 and can be bought directly from NXP or from most distributors (like Mouser or DIgikey). Search for "OM13054". But you could also use a J-Link, PEMicro, or others if you already have an ARM programmer. Cable: The DEFCON badge has the footprint for a Tag Connect TC2050-IDC-NL-050-ALL. Because this cable is meant for manufacture programming and not day-to-day debugging, if you plan on stepping through code, you'll also want to pop off the the quartz front and get some retainer clips to keep the programmer connected to the board. If you just simply want to reprogram the board, you can just snip off the 3 long guide clips, and press the cable against the PCB while holding your hand steady for the ~5 seconds it takes to flash it each time.  Alternatively if you already have a JTAG/SWD cable and have soldering skills, you can use some fine gauge wire and hack up your own converter to your board like /u/videlen did with some true hacker soldering. However as /u/int23h pointed out, because it's using Single Wire Debug (SWD) you only need to really solder 2 of the pins, SWDIO and SWDCLK. However nRESET is also recommended as it'll let you take control of the device if it's in sleep mode (which it is most of the time). Power (which is needed so the programmer knows what voltage to send the signals at) and GND you can get from the serial header. Software There's three pieces of software you'll need:  1) Compiler 2) MCUXpresso SDK for the KL27  3) Badge source code Compiler: Recommended Option: Latest version of MCUXpresso IDE - available for Windows, Mac, and Linux Second Option: Download older version of MCUXpresso IDE for Windows from the DEFCON media server  Third Option: If you use the latest SDK, you can easily use ARM-GCC, IAR, or Keil tool chains as well.  MCUXpresso SDK: Recommend Option: Download latest SDK version for KL27 - includes setup for MCUXpresso IDE, ARM-GCC, IAR, and Keil compilers Other option: Download the older 2.4.2 SDK version on the DEFCON server which only has MCUXpresso IDE compiler support.  Badge Source: Recommended Option: Download zip off Joe Grand Website: http://www.grandideastudio.com/wp-content/uploads/dc27_bdg_source.zip  Other option: Download from DEFCON media server. However the .project and .cproject files do not show up by default, so you must make sure to explicitly download them as well and put them in the main firmware folder (at the same level as the .mex file). These are the exact same files as in the zip.  wget -r -np -R "index.html*" https://media.defcon.org/DEF%20CON%2027/DEF%20CON%2027%20badge/Firmware/ wget  https://media.defcon.org/DEF%20CON%2027/DEF%20CON%2027%20badge/Firmware/.cproject wget  https://media.defcon.org/DEF%20CON%2027/DEF%20CON%2027%20badge/Firmware/.project  Getting Started with MCUXpresso IDE:      1) Open up MCUXpresso IDE. When it asks for a workspace directory to use, select (or make) a new empty directory that is in a different location than where you          downloaded the firmware source.       2) Drag and drop the SDK .zip file from your file system into the MCUXpresso IDE "Installed SDKs" window. This is how the compiler learns about the KL27 device and the flash algorithms.  3) Drag and drop the badge firmware folder from a file explorer window into the MCUXpresso IDE "Project Explorer" window 4) In the Quickstart panel hit Build 5) In the Console tab, you should see the message that it compiled successfully 7) In the Quickstart panel hit Debug.  If you're not using a LPC Link2 for programming, you'll need to hold Shift when clicking this the first time so it'll rescan for your debugger.  If using the latest MCUXpresso IDE, you'll see a dialog box that the launch configuration needs to be updated. Click on "Yes".    7) A dialog box will come up confirming your debug probe. 😎 Connect the programming cable to the board and press to make a good connection. Make sure the alignment pins match up with the alignment holes on the PCB, and that pin 1 (the red stripe) matches the photo below. You may hear the badge beep, as it's being reset. 9) Then hit OK in the dialog box to start programming. Make sure to keep the probe held there until the programming is finished - about 5 seconds. 10) You should see it program successfully and hear the board beep as it reboots.  Programming Troubleshooting/Tips: If you're not using a LPC Link2, hold down the Shift key when you hit the Debug button, and it'll re-search for new probes. Also make sure your debug settings and probe is using SWD mode and not JTAG mode.  If you have the programming cable not lined up with the pads, you'll see this error. Re-align your probe and try again. Also you must have power from the battery as the MCU needs to be turned on while programming. You can hit the GUI flash programmer at the top for a quicker download experience since it won't load the debug view. Useful if just flashing the device without wanting to step through code.  Finally, some of the game state variables are stored in the non-volitale internal flash, and may not automatically get erased when reprogramming the firmware as the programmer doesn't realize that area of flash memory is being used and thus to save time, doesn't bother to erase it. You can force a complete erase of the flash to wipe all the game variables by setting the mass erase option. Double click on the dc27_badge LinkServer Debug.launch file which contains the debug settings, and go to GUI Flash Tool->Program and set Program (mass erase first).  Getting Started with ARM-GCC: To make this easier, you'll need to download the latest SDK from the NXP website first.  Follow the instructions in Section 6 of the MCUXpresso SDK User Guide for how to setup the environment and test it out on Hello World. You can then use that project for copying the badge source code into. I'm sure someone can put together a Makefile for the badge specifically. See this series of blog posts on how to use the SDK (compiling/debugging) with arm-gcc in Linux. My badge isn't working: First thing to try is power cycling the badge by gently prying the battery out (with a butter knife or something) and putting it back in. A couple of things might happen: If nothing at all happens, you battery might be dead. Try replacing the battery.  If nothing at all happens still, the battery holder might be loose. Use a multimeter ot measure the voltage between GND and VCC on the serial header, it should read 1.8V. If it does not, check the battery holder. If you hear beeps, all 6 LEDs light up, and then 4 LEDs (2 on each side) flash in sync a few times, it means there was an issue communicating with the NFMI device. This could be due to a loose solder joint on one of the chips or the I2C pull up resistors (SCL and SDA on the pinout image). You could also do a reflow if you have the equipment, but it may not be fixable. Also could see if see any I2C communication on those SCL/SDA pins. If you hear a normal startup beep, the lights flash, and then it goes back to the startup beep, and so on, forever, something is causing the MCU to keep resetting. Could be a short or ESD damage. Check soldering. Connecting your board to a serial terminal and see how far it gets in the boot process to help narrow down the cause.  Sometimes the flags don't get saved properly. A power cycle usually works, and could also try reflashing the badge.  If your badge isn't responding to other badges with the NFMI, it could be one of two things: Your copper antenna is loose/broken/missing. This happened a lot. Solder it back on. If missing, it's a Sunlord MTNF6040FS3R7JTFY01 but it's not available online anywhere at the moment. Datasheet is here. See this post for more details on possible alternatives. If you were previously in interactive mode, you have to explicitly exit it with Ctrl+X to receive packets again.  Further hacking: For basic hacking of the code, try changing your game flags to trick it to giving you a fully unlocked badge. From there, you could try to make your own chameleon badge like others have done (https://github.com/japd06/defcon27_badge and https://github.com/nkaminski/DC27-badge-CFW and https://github.com/NickEngmann/Jackp0t among others if you want ideas). Or make your own songs with the piezo. Or some ASCII art on the terminal. For more advanced hacking on the badge, PTE22 and PTE23, the TX and RX pins on the serial header, could be programmed to be ADC input pins instead. Or timer inputs or outputs for PWM or input capture.  And with some good soldering, you could even add an additional I2C device by soldering to the resistor points. t.   Finally if you want a more flexible platform for exploring embedded development, you can pick up a FRDM-KL27Z dev kit for $20 which has the same chip as the badge. You can buy it direct or all major distributors online. The programmer and serial interface are built into the board so you only need to use a USB cable to do all the programming. The KL27 SDK also includes dozens of example programs that show how to use all the features of the chip and there's some getting started videos (mostly what I covered already in this post though). While it does not have a NFMI chip on it, it does have USB support, as well as an Arduino hardware footprint on it so it can be easily expanded with extra boards. You can find the example programs by going to "Import SDK examples" from the Quickstart panel window.  If you have any more questions about the badge, post a response! 
View full article
Hello all.   I would like to share an example project for FRDM-KL25Z board on which C90TFS Flash Driver was included to implement emulated EEPROM (Kinetis KL25 doesn’t have Flex Memory). It is based on the “NormalDemo” example project. A string of bytes is stored on the last page of the flash memory (address 0x1FC00-0x1FFFF), and then, it is overwritten with a different string.   The ZIP file also includes the “Standard Software Driver for C90TFS/FTFx Flash User’s Manual” document. For more information, please refer to Freescale website and search for “C90TFS” flash driver. Hope this will be useful for you. Best regards! /Carlos
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
为了提高我们FAE对客户支持的效率,我们有必要将我们在客户支持过程中遇到的问题和解决方法以FAQ的形式列出来,方便大家查阅和参考。FAQ的形式比较灵活,大家可以以简单问答的形式言简意赅的描述,也可以是参考文章的链接,众人拾柴火焰高,希望大家能多收集问题并及时更新到该帖子中。 版本更新说明: Version 22: Rename "软件和例程" with "软件和文档", Add "常用的应用笔记" into "软件和文档" list; Version 20, 21: Remove "WIFI" solution, Add "SPI接口读写SD卡"; Version 19: Replace "iBeacon" with "BLE"; More version informations, please go to "Kinetis M0+ FAQ 版本更新历史" FAQ使用规范 1.FAQ Notes(Internal Use Only) 芯片选型 1.Kinetis L、E、V、W、M系列选型指南 软硬件开发环境 1.调试工具 2.量产工具 3.开源工具 4.IDE开发环境 5.开发板 硬件设计 1.电路设计注意事项 软件和文档 1.外设模块相关 2.Kinetis SDK 3.Kinetis Bootloader 4. 常用的应用笔记​ 参考设计及解决方案 1.Wireless Charging 2.Motor Control 3.BLE​ 4.M0+ 与Android手机通讯(基于AOAP协议) 5.SPI接口读写SD卡​ 常用网站资料 1.Amobbs(阿莫电子技术论坛) 2.与非网飞思卡尔技术社区 3.21IC飞思卡尔论坛 4.苏州大学教材光盘资料下载区 5.针对飞思卡尔单片机的快速上手指南 6.飞思卡尔MAPS开发板资料​ 7.FAE Technical Blogs​
View full article
RNN on FRDM_K64 to denoise 1 Introduction Ordinary MCUs are limited by resources, and it is difficult to do some complex deep learning. But although it is difficult, it can still be done. Last time we used CNN for handwritten recognition. This time ,we use RNN for audio noise reduction. This audio noise reduction uses fixed-point noise reduction. MFCC and gain are used as input parameters for training. MFCC, Mel frequency cepstrum, is often used for audio feature extraction. RNN achieves the effect of noise reduction by adjusting the gain of different frequencies.        2 Experiment 2.1 Required tools: frdm-k64, python 3.7, Pip, IAR   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 Transplant fatfs file system to bubble project   Figure 2   2.5 In the bubble.c file, add the following header file        #include "nnom_port.h" #include "nnom.h" #include "weights.h" #include "denoise_weights.h" #include "mfcc.h" #include "wav.h" #include "equalizer_coeff.h"   2.6 Find main.c under ‘examples\rnn-denoise’ in the framework, ‘main_arm.c’ is used for stm32. Main.c is provided for windows running routines. This code is used to open the audio file, then run the network, and finally generate noise reduction. Use this code to facilitate experiments. The APIs for file operations in this file need to be manually changed to MCU APIs. I added a progress bar display. You can refer the attachment.   2.7 This example also uses DSP, so DSP support needs to be turned on, as shown in the figure                                                           Figure 3 2.8 Add macro                                             Figure 4   2.9 After the compilation is passed, download the program. The tested wav needs to be named ‘sample.wav’, and the mcu will reduce noise for it. Finnally mcu will generate ‘filtered_sample.wav’. Plug the SD card into the computer to listen to the noise-reduced audio. This is serial message.     Figure 5 This is the audio analyzed by the audio analysis software. The upper part is the noise reduced, and the lower part is the original sound. You can see that a lot of noise has been suppressed.                                                    Figure 6 3 training Through the above steps, we have achieved audio noise reduction, so how is this data trained? You need to install tensorflow, and keras. How to train is written in the README_CN.md file. This tensorflow needs to install the gpu version, and needs to install cuda. Please check the installation yourself. 3.1 Download the voice data https://github.com/microsoft/MS-SNSD and put it under the MS-SNSD folder 3.2 Use pip3 to install the tools in requirements.txt 3.3 Run ‘noisyspeech_synthesizer.py’ directly, this will report an error. You need to change the 15-line float to int type. 3.4 Run the script gen_dataset.py to generate mfcc and gain 3.5 Run main.py, this will generate the noise file of the sample, which can be used for testing and also generated ‘weights.h,denoise_weights.h,equalizer_coeff.h’ PS: Put the code in directory 'boards/frdmk64f/demo_app'. 'sample.zip' has the noise wave.
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
Hello Kinetis fans, This time I bring to you a document which explains what is and how to configure scatter/gather feature which is present in the Enhanced Direct Memory Access (eDMA). This document includes an example project for the Kinetis Design Studio (KDS) which works in the FRDM-K64F board but the configuration is the same for any MCU which includes the eDMA peripheral. If you are interested in the channel linking feature, please take a look into the document What is and how to configure the eDMA channel linking feature​. I hope you find this document useful. Best regards, Earl Orlando Ramírez-Sánchez Technical Support Engineer NXP Semiconductors
View full article
在电机控制,Audio等很多应用中,我们经常会用到一些常见的正余弦,矩阵变换,FFT等一些DSP函数,提到DSP库,通常会想到使用ARM 公司提供的 CMSIS 库。CMSIS 库是ARM和一些半导体厂家针对Cortex-M系列制定的一套接口标准,包括针对内核操作的CMSIS-CORE API,针对DSP应用的CMSIS-DSP Library,针对RTOS的CMSIS-RTOS API,与外设接口的CMSIS-SVD以及提供Debug访问接口的CMSIS-DAP。 其中,又以DSP应用的CMSIS-DSP 库的应用最为广泛。针对Cortex-M4中的DSP功能,CMSIS-DSP部分提供了超过60多种功能的DSP算法库,尤其是随着Cortex-M4中集成了FPU硬件单元,CMSIS-DSP 库的应用也越来越广泛。 在KEIL 和IAR中都集成了对CMSIS的支持,然而在CodeWarrior中没有直接支持CMSIS,需要用户移植到自己的CW工程中,所以就需要使用者了解CMSIS的结构,手动添加库文件和头文件,并完成一些重要的编译参数配置。特别是有些芯片支持FPU浮点运算单元,有些不支持,在配置选项上差别很大。在飞思卡尔Kinetis系列芯片中,FPU浮点运算单元也是一个可选的部件,只有在名称中带有FN和FX的芯片才支持FPU硬件浮点功能,如MK60FN1M0, MK60FX512。本文档分别介绍在使用和不使用FPU的情况下如何一步步移植CMSIS的DSP库到自己的CodeWarrior工程中。 需要注意的是 FPU 单元是指的芯片上的一个独立于 CPU 处理的浮点运算单元,整个单元在大多数厂家的芯片中都是可以被使能和关闭的。相对于芯片,编译器也设置了相应的 FPU 功能开启/关闭的选项,在编译时需要告诉编译器是否开启 FPU 功能。编译器一旦开启 FPU 功能,在处理单精度浮点运算的语句时就会用带 V-开头的汇编指令进行编译。如果编译器使能了 FPU 功能,而芯片未开启 FPU 单元,程序运行到浮点语句时就会出现异常。相反,如果编译器未使能 FPU 功能,芯片即使开启了 FPU单元,程序还是会按照未使能 FPU 的代码进行处理。在本例程中,为对比分析是否采用FPU的编译指令差别以及在板的执行效率,选用Kinetis K70FN1M为实验对象。 硬件平台:TWR-K70F120M核心板      软件环境:CodeWarrior v10.5        CMSIS版本 :V3.2 一. 准备工作: 下载CMSIS的库,当前最新的版本为V3.2,解压后名称为CMSIS-SP-00300-r3p2-00rel1,其目录结构如下图。分别包含CMSIS-DSP, CMSIS-RTOS和CMSIS-SVD的库文件。在本Cortex M4的CMSIS-DSP的应用中,真正用到的文件包括CMSIS\Include中CM4相关的头文件,CMSIS\Lib\GCC文件夹中的库文件libarm_cortexM4l_math.a(软浮点)和libarm_cortexM4lf_math.a(硬浮点),以及Device\ARM\ARMCM4\include中外设访问相关的两个头文件。 二. 不使用K70的FPU浮点运算单元,移植CMSIS的DSP库到CW的步骤;      Step 1:    新建一个Baremental的工程,选择器件器件MK70FN1M0(支持硬件FPU);     Step 2:    选择Floating Point浮点运算实现的类型,即指定编译器将C代码编译成汇编代码时使用的规则; 在Floating Point四个选项含义如下: Software选项:表示不使用FPU硬件,而是使用GCC的整数算术运算来模拟浮点运算; Handware(-mfloat –abi=hard) 选项:表示使用FPU硬件来进行浮点运算,函数的参数直接传递到FPU的寄存器(s0-d0)中; Handware(-mfloat –abi=softfp)选项:表示使用FPU硬件来进行浮点运算,但是函数的参数传递到整数寄存器(r0-r3)中,然后再传递到FPU中; Handware(-mfloat –abi=softfp –fshort -double)选项:其配置项同上,只不过使能了fshort  double功能,并且此处的double数据的宽度等同于float; 有兴趣研究各个选项意义的可以参考CW for MCU技术文档的第3章,在本例程中使用的是软浮点,所以选择Software项。需要注意的是:此配置选项仅出现支持FPU硬件单元的芯片工程中,如MK60FN1M0, MK60FX512等,否则默认没有此选项,默认为软件浮点。 Step 3:    点击“Next”进入下图,选择使用Processor Expert,点击“Finish“完成工程的建立; Step 4:    进入当前工程的文件夹,新建文件夹CMSIS,从之前在准备步骤解压的CMSIS文件包\...\CMSIS-SP-00300-r3p2-00rel1\CMSIS中拷贝Include和Lib文件夹到当前工程新建的CMSIS文件夹。另外,拷贝\...\CMSIS-SP-00300-r3p2-00rel1\Device\ARM\ARMCM4\Include中的ARMCM4.h和system_ARMCM4.h到当前工程新建的CMSIS文件夹中; Step 5:    回到CodeWarrior主界面选择新建的工程文件,F5刷新可以看到CMSIS出现在工程文件中。其中Include是CMSIS库的一些头文件,包括M0+/M3/M4的一些头文件;在Lib文件中是已经编译好的库文件,ARM文件夹是使用在KEIL IDE中的库文件,G++文件夹是使用在IAR中的库文件,而由于当前CW工程使用的GCC的编译器,所以GCC文件夹才是CW需要的,因此,为缩减工程大小可以删除ARM和G++文件夹;     Step 6:    打开工程属性框,选择Target Processor的Float ABI为No FPU; Step 7:    在GCC Complier的Defined symbols中添加编译的宏定义ARM_MATH_CM4; Step 8:    在GCC Complier的Include paths中添加CMSIS库的头文件,路径为:工程目录\CMSIS\Include; Step 9:    在GCC C Linker的Miscellaneous项的Other objects中指定使用的库文件(位于CMSIS\Lib\GCC文件夹中)。因为本例程中不使用FPU,所以选择libarm_cortexM4l_math.a,此处需要特别注意,否则编译会报错; Step 10: 在ProcessorExpert.c文件中添加代码; #include <math.h> #include "arm_math.h" #define DELTA    (0.000001f) const float32_t testRefOutput_f32 = 1.000000000; const float32_t radians=1.047197533333333; float32_t  cosOutput, sinOutput, diff; float32_t cosSquareOutput,sinSquareOutput,testOutput; int main(void) {   int m,n;   PE_low_level_init();   cosOutput = arm_cos_f32(radians); /*求正余弦*/                   sinOutput = arm_sin_f32(radians);                                 arm_mult_f32(&cosOutput, &cosOutput, &cosSquareOutput, 1); /*求积运算*/   arm_mult_f32(&sinOutput, &sinOutput, &sinSquareOutput, 1);               arm_add_f32(&cosSquareOutput, &sinSquareOutput, &testOutput, 1); /*求和运算*/   diff = fabsf(testRefOutput_f32 - testOutput);  /* 求绝对值 */                 if(diff > DELTA)   {                         while(1)                                 {                                   for(m=0;m<2000;m++)                                                 for(n=0;n<200;n++){};                                                 D7_NegVal();                                 }     }                 } Step 11:    编译并下载Debug,在  sinOutput = arm_sin_f32(radians);处设置断点,可以看到CMSIS-DSP库中的正余弦浮点数运算函数运算正常,其反汇编的得到为普通的ARM指令(FPU 单元汇编指令通常在普通指令前加字母V,仅在 FPU 功能被使能时使用),完成一个正弦计算; 至此,完成了不使用K70的FPU浮点运算单元,移植CMSIS的DSP库到CW的步骤。     三.     使用K70的FPU浮点运算单元,移植CMSIS的DSP库到Codewarrior的步骤 使用K70的FPU硬件浮点运算单元,移植CMSIS的DSP库到Codewarrior的方法有两种:一种是按照上面软浮点的方式Step By Step的建立工程,步骤和上面二的步骤基本一致,主要的两个区别在于:(1). Step 2要选择Handware(-mfloat –abi=hard) 选项,(2). Step 9 改为libarm_cortexM4lf_math.a。另外一种就是在上面工程的基础上修改配置选项。鉴于方便,本教程采用第二种方案,完成在Codewarrior中调用CMSIS的DSP库,通过K70的FPU浮点运算单元执行浮点运算,即硬浮点。 Step 1:    打开工程属性对话框,选择Target Processor的Float ABI为FPU with hard vfp passing(-mfloat –abi=hard); Step 2:    在GCC Complier的Defined symbols中添加编译的宏定义:_VFPV4; Step 3: 在GCC C Linker的Libraries项的library search path中指定链接的规则,把上面工程中默认的"${MCUToolsBaseDir}/ARM_GCC_Support/ewl/lib/armv7e-m"修改为 "${MCUToolsBaseDir}/ARM_GCC_Support/ewl/lib/armv7e-m/fpu"; Step 4:    在GCC C Linker的Miscellaneous项的Other objects中指定使用的库文件(位于CMSIS\Lib\GCC文件夹中)。因为本例程中使用FPU,所以选择libarm_cortexM4lf_math.a,此处需要特别注意,否则编译会报错; Step 5:    完成以上配置后,编译工程并下载调试(此处建议编译之前先Clean一下整个工程),同样,在  sinOutput = arm_sin_f32(radians);处设置断点,可以看到CMSIS-DSP库中的正余弦浮点数运算函数运算正常,其反汇编的得到为FPU指令(FPU指令通常是指在普通指令前加字母V,仅在 FPU功能被使能时使用),并且在Register观察窗口中也多了个FPU寄存器列表,感兴趣的读者可以对比一下和前面实验汇编出代码的差异,此处不再赘述; 至此,分别完成了使用和不适用K70的FPU浮点运算单元情况下, CMSIS的DSP库到Codewarrior的移植。在实际应用中需要用到更多的DSP函数,在项目中直接调用即可。下一步, Just Enjoy The Convenience of  The CMSIS! 有一点需要说明的是,前文中讲到使用FPU单元需要两步设置:(1). 在编译器中开启相应的 FPU 功能选项;(2). 开启芯片FPU 单元。似乎我们前面的设置是完成了第一个步骤,然而第二个步骤呢?仔细查看_arm_atart.c文件,可以发现代码_fp_init()正是完成了开启芯片FPU单元的过程,如下图,是一个条件编译函数,这也就解释了为什么在上面Step 2中定义了_VFPV4,其本质也就是使能芯片的FPU单元,其具体实现可以查看ARM手册的第74页的描述。 #ifdef   __VFPV4__        //Step 2中的宏定义                 __fp_init();      // 开启芯片的FPU单元 #endif
View full article
飞思卡尔拥有成套的电机控制处理器产品、强大的工具和专家支持,为大量应用提供高性价比且节能的电机控制解决方案,您可以在飞思卡尔官网电机控制主页上找到相应的电机控制参考方案。链接如下: http://www.freescale.com/zh-Hans/webapp/sps/site/homepage.jsp?code=MOTORCONTROLHOME 下文也列出BLDC和PMSM常用的控制参考方案,方便查询。 BLDC(无刷直流电机)参考设计 M0+方案 AN4776 - BLDC motor control with Hall sensor based on FRDM-KE02Z 附代码包AN4776SW AN4869 - 基于FRDM-KE04Z和Tower Board的BLDC电机正弦波控制 附代码包AN4869SW AN4796 - 基于FRDM-KE02Z和Tower Board的无传感器BLDC电机控制 附代码包AN4796SW AN4862 - 利用MKV10x实现三相BLDC无传感器控制   附代码包AN4862SW DRM144 - Three-phase BLDC sensorless motor control application AN4870 - Tuning 3-Phase BLDC motor sensorless control using MKV10  附代码包AN4870SW DRM151 - 采用Kinetis KEA128 MCU的3相无传感器BLDC电机控制参考设计 M4方案 AN4376 - 基于 kinetis 和 MQX 的带霍尔传感器的无刷直流电机控制 AN4254 - 在Freescale MQX实时操作系统下进行电机控制 DRM135 - 3-phase BLDC sensorless control with Kinetis MCU (MQX) 附代码包DRM135SW AN4597 - BLDC Sensorless Algorithm Tuning Three-Phase BLDC Sensorless Motor Control Using the MKV4x In Quadcopter Application 附代码包AN5169SW DSC方案 AN4413 - BLDC Motor Control with Hall Sensors Driven by DSC  附软件包AN4413SW AN1916 - 基于 56800/E 数字信号处理器和霍尔传感器的三相 BLDC电机控制 DRM025 - 3-Phase BLDC Motor Control with Hall Sensors Using 56F805 Designer DRM022 - 3-Phase BLDC Drive Control with Hall Sensors Reference Design AN1913 - 3-phase BLDC Motor Control with Sensorless Back-EMF ADC Zero Crossing Detection using DSP 56F80x AN1914 - 3-Phase BLDC Motor Control with Sensorless Back EMF Zero Crossing Detection Using DSP56F80x DRM108 - 采用 MC56F8006 的 BLDC 无传感器参考设计 DRM077 - PMSM and BLDC Sensorless Motor Control using the 56F8013 Device Designer DRM078 - 3-Phase BLDC Drive Using Variable DC Link Six-Step Inverter Designer DRM027 - 3-Phase Sensorless BLDC Motor Control with Back-EMF Zero Crossing Detection Using 56F805 Designer DRM098 - Direct PFC Using the MC56F8013 DRM070 - Three-Phase BLDC Motor Sensorless Control Using MC56F8013/23 Design DRM026 - 3-Phase BLDC Motor Control with Sensorless BACK-EMF ADC Zero Crossing Detection Using 56F805 AN1961 - 3-Phase BLDC Motor Control with Quadrature Encoder Using the 56F800/E PMSM(永磁同步电机)参考设计 M0+方案 AN5049 - Three-Phase PMSM Sensorless FOC Using the MKV10Z32 with Automated Motor Parameters Identification 附代码包AN5049SW AN4935 - 利用Kinetis KV10实现适用于风扇的PMSM无传感器磁场定向控制 (FOC)   附代码包AN4935SW DRM148 - 无位置PMSM矢量控制参考设计 M4方案 DRM128 - PMSM Vector Control with Quadrature Encoder on Kinetis AN4911 - 利用MKV31F实现三相PMSM无传感器FOC  附代码包AN4911SW AN5004 - Sensorless PMSM Control on MKV46F256 Using Kinetis SDK 附代码包AN5004SW AN4912 - Tuning 3-Phase PMSM Sensorless control application using MCAT Tool DRM140 - PMSM Sensorless Vector Control on Kinetis AN4489 - Using CMSIS-DSP Algorithms with MQX and Kinetis MCUs AN4381 - Configuring the FlexTimer for position and speed measurement AN3729 - Using FlexTimer in ACIM/PMSM Motor Control Applications MCLIBCORETXM4UG - Set of General Math and Motor Control Functions for Cortex M4 core PMSMCONUG - PMSM Vector Control with Encoder on Kinetis AN4680 - PMSM electrical parameters measurement DSC方案 AN4656 - PMSM FOC of Industrial Drives using the 56F84789 PMSMUG - PMSM Field-Oriented Control Using MC56F84789 DSC With Encoders DRM098 - Direct PFC Using the MC56F8013 DRM029 - 3-Phase PM Synchronous Motor Control with Quadrature Encoder Using 56F805 Designer DRM102 - PMSM Vector Control with Single-Shunt Current-Sensing Using MC56F8013/23 Design DRM018 - 3-Phase PM Synchronous Motor Torque Vector Control Using 56F805 Designer DRM036 - Sine Voltage Powered 3-Phase Permanent Magnet Synchronous Motor with Hall Sensors Designer AN5014 - Three-Phase PMSM Sensorless FOC using MC56F82748 and MC56F84789 with Automated Motor Parameter Identification  附代码包AN5014SW DRM110 - Sensorless PMSM Control for an H-axis Washing Machine Drive Designer DRM099 - Sensorless PMSM Vector Control with a Sliding Mode Observer for Compressors Using MC56F8013 DRM139 - Dual Sensorless PMSM Field-Oriented Control With Power Factor Correction on MC56F84789 DSC AN4608 - 在MC56F84789上使用PWM和ADC,驱动双PMS电机FOC AN4583 - MC56F84789 Peripherals Synchronization for Interleaved PFC Control                 若文档链接有变动或失效,请在飞思卡尔官方网站上通过文档名称(如AN4912、DRM139等)搜索相应文档。
View full article
Symptoms As we know: Flash must be programmed after an erase operation. Violation of this rule will cause programming fail and even hardfault(when AHB reading) on Kinetis K64 parts. Customer accidently uses SDK’s API programming same sector twice(over-programming) without an erase operation. Then when perform AHB reading of this sector(include using JFLash to read this sector), an Hardfault occurs. Diagnosis K64 flash has internal ECC on each sector. When over-programming happens, ECC will be crushed and trigger Hardfault when AHB reading of this sector. Solution Using SDK API FLASH_VerifyErase to check if this sector is erased. Call FLASH_VerifyErase every time before you want to program the flash. This problem will impact all Kinetis device which has FTFE flash module.   Thanks for Alex Yang provide the material.
View full article
A vulnerability (CVE-2022-22819) has been identified on select NXP processors by which a malformed SB2 file header sent to the device as part of an update or recovery boot can be used to create a buffer overflow. The buffer overflow can then be used to launch various exploits. Refer to the attached bulletin for more information.   09/26/2022 - Bulletin updated to include fix datecode information. 11/01/2022 - Bulletin updated with clarification that mixed datecodes are RT600 only.    
View full article