LPC Microcontrollers Knowledge Base

cancel
Showing results for 
Search instead for 
Did you mean: 

LPC Microcontrollers Knowledge Base

Discussions

Sort by:
The power measurement board includes eight measurement channels which support for eight programmable gain amplifiers(LTC6915) and two ADC converters(AD7175). The measurement board measures the voltage drop across sampling resistor, and send to the ADC after the voltage drop is processed by amplifier and make it available via SPI. Microcontroller LPC55S69 collects the data from the measurement circuit and send it to the host computer via USB VCOM port. The MCU can control the gain value of programmable gain amplifiers by SPI when different power circuit are measured. The host computer connects to the power measurement board through the USB virtual serial port, the MCU initializes and configures the measurement unit by SPI, and starts to measure the inside current and monitor the voltage. MCU adjust the gain parameter and then transmit current and voltage data to MCU by SPI, then MCU transmits the data to the host computer for processing and display through the virtual serial port. The voltage drop of the measured circuit to be measured is firstly amplified by the programmable amplifier LTC6915, and MCU monitor the state which whether the data is abnormal at the same time. R0 is the sampling resistor, LTC6915 is a selectable programmable amplifier, the gain can be set to 14 kinds, PGA gain parameter is adjusted when the current changes. ADC7175 is the 24-bit high-precision ADC, which is more advantageous in the application of small current measurement. When the MCU switches the low power mode to the normal mode, and the LTC6915 will reduce the gain value by SPI. The power measurement board provides easy connection method by two-wires cable. For example, the MIMXRT1180EVK and MIMXRT1020EVK are connected with power measurement board. The USB virtual COM is used for data transfer, and display by PMT(power management tool) or other PC GUI, the measurement power data include current, voltage and power. There are more detailed descriptions in the attachment.
View full article
New update to errata will be published regarding the vendor_usage field in the PFR. In ROM, the 16-bit monotonic counter is implemented in the upper 16 bits of the 32-bit VENDOR_USAGE field and the inverse of the monotonic counter is in the lower 16 bits. Users must take care when using the ROM API to increment the upper end of this field and write the inverse on the lower 16 bits in order for ROM to validate the value correctly. The initial value that shall be written is 0x0000FFFF. Then the updates will be as follows: 0x0001FFFE 0x0002FFFD . . 0x0005FFFA . . 0x1010EFEF . . 0xFFFF0000   Example Code using ROM API: *This example demonstrates the increment of the version in CFPA page as well as the vendor usage, it does not cover all use cases, so please use this as a reference only* case APP_INCREASE_VENDOR_USAGE_ONLY: PRINTF("Disable Flash Protect...\r\n"); /* Initialize flash driver */ FLASH_Init(&flashInstance); if (FFR_Init(&flashInstance) == kStatus_Success) { PRINTF("Flash init successfull!!. Halting...\r\n"); } else { error_trap(); } status = FFR_GetCustomerInfieldData(&flashInstance, (uint8_t *)g_CFPAData, 0x0, FLASH_FFR_MAX_PAGE_SIZE); PRINTF("\r\n"); PRINTF("Header 0x%08x , Version 0x%08x , SecureFW Version 0x%08x , NonSecureFW Version 0x%08x\r\n", g_CFPAData[0], g_CFPAData[1], g_CFPAData[2], g_CFPAData[3]); PRINTF("ImageKey Revoke 0x%08x , Reserved 0x%08x , RothRevoke 0x%08x , Vendor Usage 0x%08x\r\n", g_CFPAData[4], g_CFPAData[5], g_CFPAData[6], g_CFPAData[7]); PRINTF("NS PIN 0x%08x , NS DFLT 0x%08x , Enable FA Mode 0x%08x , Reserved1 0x%08x\r\n", g_CFPAData[8], g_CFPAData[9], g_CFPAData[10], g_CFPAData[11]); PRINTF("\r\n"); /* Clean-up CFPA area */ g_CFPAData[8] = 0; g_CFPAData[9] = 0; /*Increase Monotonic counter*/ p32 = (uint32_t *)(uint32_t)g_CFPAData; version = p32[1]; if (version == 0xFFFFFFFFu) { return kStatus_Fail; } version++; p32[1] = version; PRINTF("Version to write: 0x%08x \r\n", version); /*Increase Vendor Usage*/ uint32_t vendor_usage = p32[7]; if(vendor_usage == 0x0) { vendorUsage_right = 0xFFFF; vendorUsage_left = 0x0000; } else { vendorUsage_right = vendor_usage & 0xFFFF; vendorUsage_left = vendor_usage >> 16; } vendorUsage_left += 0x1; vendorUsage_right -= 0x1; vendor_usage = (vendorUsage_left << 16) | vendorUsage_right; p32[7] = vendor_usage; PRINTF("Vendor_Usage to write: 0x%08x \r\n", vendor_usage); Status = FFR_InfieldPageWrite(&flashInstance, (uint8_t *)g_CFPAData, FLASH_FFR_MAX_PAGE_SIZE); if (kStatus_FLASH_Success == Status) { status = kStatus_Success; PRINTF("CFPA Write Done!\r\n"); } else { status = kStatus_Fail; }
View full article
Contents 1. Principle of energy measurement 2. Energy measurement test   2.1 Use in non-Debug state   2.2 Use in Debug state   During the operation of MCU, real-time measurement of board current and voltage is of great significance to the stability of system power consumption. Especially in scenarios that are sensitive to voltage and current fluctuations, it is particularly important to collect and analyze high-frequency samples. MCUXpresso IDE integrates the power measurement function, which can measure the current and voltage of the development board in real time and calculate the real-time power consumption. Based on MCUXpresso IDE v11.5.0, this article mainly explains power measurement function usage. 1.   Principle of energy measurement Currently the MCUXpresso IDE energy measurement function supports the following development boards: -LPCXpresso546x8/540xx/54S0xx -LPCXpresso54102 -LPCXpresso51U68/54114 -QN9090-DK006/ JN5189-DK006/IOTZKB-DK006 -QN9080DK The power measurement actually uses the LPC-Link2/MCU-Link debugger on the development board to collect the conversion value of the A/D conversion chip, and perform software calculation to obtain the power measurement result. Taking LPCXpresso54628 development board as an example, the following is the circuit diagram of the power measurement part: Fig.1 The MAX9634TEUK+T is a precision current amplifier. And ADC122S021 is a 12-bit A/D converter with dual-channel sampling, its rate can reach 200ksps. ADC122S021 collects LPC54xx_CURR and SHLD_CURR voltages, IDE sets Target resistor (Total Rvsense in the figure) and Shield resistor (resistance value corresponding to SHLD_CURR) in advance. The LPC-Link2 debugger can calculate the voltage, current and power consumption information by collecting AD conversion values. 2.   Energy measurement test Taking LPCXpresso54628 development board as an example. Open the menu bar : Analysis->Energy Measurement. The Energy Measurement interface will appear in the lower right corner of the screen, which is divided into Plot drawing and Config configuration interface. It can be used in Debug state or in non-Debug state during measurement. Test the case of LED small light flickering and observe the changes of voltage, current and energy consumption. Note that the LPC-Link2 debugger version should be CMSIS-DAP probe version 5.147 and above. 2.1 Use in non-Debug state Click the button  in energy measurement interface and select the measured in the config interface. You can select the target voltage, target current and shielding current. The sampling rate can be selected as 50ksps, 62.5ksps or 100ksps. First select the model of the development board to be tested, and then continue to select the target resistance and shielding resistance. The target resistance value is selected according to the jumper cap description in Figure 1. The resistance value of the shielding resistance is the fixed resistance value of development board. As shown in the figure below: Fig.2 Select the target voltage to be measured, and click the button to run the Energy Measurement interface. You can see the slight fluctuation of voltage in the plot interface and view the average voltage through the delimited area of horizontal measurement, as follows: Fig.3 Select the target current to be measured. Before measuring the target current, click Read from target on the config interface to calculate the average value of the target voltage within 0.5s for subsequent power consumption calculation. Click the run button to see that the target current fluctuates slightly with the flashing of the small light in the plot interface. At the same time, check the average current, power consumption and energy consumption through the delimited area of horizontal measurement, as follows: Fig.4 2.2 Use in Debug state When used in the debug state, you can use MCUXpresso IDE or KEIL to enter the debugging state. Click the button on the energy measurement interface to read the power consumption in the debug state. The measurement process is the same as the non-Debug state, as follows: Fig.5 This is a general enablement document of how to use energy measurement feature in debug and non-debug mode. For more, please refer  MCUXpresso_IDE_Energy_Measurement. pdf under MCUXpresso IDE install folder.    
View full article
  Contents 1.Problem description      2.  Reason analysis      3. Solutions    3.1   SRAM power down problem solution    3.2   Alarm timer interrupt enable problem solution   3.3   Downcounter register write problem solution    4. Verification Considerations   1.     Problem description When LPC43xx series runs the LPCOpen low-power demo “misc_pmc_states”, the two modes of power down and deep power down cannot successfully wake up through the Alarm Timer. This paper analyzes the series of problems and provides corresponding solutions. The same problem and solution exists for waking up via RTC. 2.     Reason analysis The reasons for wake-up failure include the following three aspects. - SRAM power down problem: In the power down mode of LPC43xx series, only the 8K SRAM is not powered down, and other SRAMs are powered down. After waking up from power down mode, the program continues to execute backwards, not reset. Therefore, it should be ensured that when entering power down, the data is in the 8K SRAM that does not lose power, so after wake up, it can continue running. - Alarm timer interrupt enable problem: The LPC43xx  Alarm timer interrupt enable need a while to take effect. If it is not successfully enabled before entering low power, it cannot wake up from low power mode. - Downcounter register problem: In LPC43xx series, in order to ensure the wake-up at the specified time, it is necessary to judge that the set value is successfully written into the Downcounter register. The table of reasons for wake-up failures in power down and deep power down modes is summarized as follows:   3.     Solutions For power down wake-up failure, it needs to be solved according to three problems. There is no data loss problem for deep power down wakeup. Because after waking up from deep power down mode, the program is reset and executed again, and the previous data is not needed. So the solution skips the first and only needs 3.2 and 3.3. 3.1  SRAM power down problem solution As shown in the manual, only 8kB local SRAM will not lose power in LPC43xx series Power-down mode. Note: Chips with and without internal flash have different 8K SRAM address ranges.   For LPC4330/LPC4350/LPC4370 series products without internal flash, the 8K SRAM address range is 0x10090000– 0x10092000 (8KB). The address range of chips with internal flash such as LPC4337/LPC4367 is 0x10088000 – 0x1008A000 (8KB).   Placing data in this 8K SRAM area can solve the problem of lost data. Taking LPC4350 as an example, the setting method in MCUXpressoIDE is as follows: Find the following interface according to Project \ Properties \ C\C++ Build\MCU settings path, define this 8K SRAM separately, the address is 0x10090000, and the size is set to 0x2000. At this point, the setting of the power loss problem in the SRAM area is completed. 3.2  Alarm timer interrupt enable problem solution To ensure that the Alarm timer interrupt is enabled, add a while loop poll after it until it is successfully enabled. Enter the function in the src\pmc_states.c path. And add while((LPC_ATIMER->ENABLE& 0x01) != 0x01){} after the Chip_ATIMER_IntEnable(LPC_ATIMER); function statement in the corresponding case mode.   3.3  Downcounter register write problem solution The solution to this problem is similar to 3.2. Still enter the function with the src\pmc_states.c path, and find LPC_ATIMER->DOWNCOUNTER= RTC_ALARM_TIME*1000 in the case of the corresponding mode (consistent with the 3.2 position). Add a while statement after it: while(LPC_ATIMER->DOWNCOUNTER != RTC_ALARM_TIME*1000); As shown below.   4.     Verification Considerations When there is no internal flash development board for testing (eg: LPC4370, LPC4350…), such as the Hitex LPC4350Evaluation board, it is necessary to configure the startup as external flash startup. The reference picture is as follows.   When starting, you need to set the pins P2_9, P2_8, P1_2, P1-1 to the form of low, low and high, and start in the form of SPIFI. Jumper settings are shown in the figure.  
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 attach bulletin for more information.  
View full article
1. General Jointly developed by NXP and Embedded Artists, the MCU-Link Pro is a fully featured debug probe that can be used with MCUXpresso IDE and 3rd party IDEs that support CMSIS-DAP and/or J-Link protocols. MCU-Link Pro is based on NXP’s MCU-Link architecture, found in the  MCU-Link  low cost debug probe and on board evaluation boards, and runs the same firmware as all these implementations. In addition to SWD debug, SWO profiling and a USB to UART bridge features (VCOM) found in the base MCU-Link, the Pro model adds a J-Link LITE firmware option, energy measurement, analog signal monitor, USB to SPI and I2C bridging capability and an on-board LPC804 for peripheral emulation. MCU-Link Pro is based on the dual Arm® Cortex-M33® core LPC55S69 microcontroller, and features a high speed USB interface, providing high performance debug at low cost. The USB bridging feature is supported by the free  LIBUSBSIO host library  from NXP. MCU-Link Pro is compatible with Windows 10, MacOS and Linux. The product comes with the necessary firmware installed, with free utilities provided to enable future firmware updates from NXP to be installed. MCU-Link Pro kit provides all parts that need to be used. Kit Contains MCU-Link Pro debug probe 10 pin to 10 pin Cortex debug cable 10 pin to 20 pin Cortex debug cable Digital port / analog input adapter cable Spare jumpers 2. MCU-Link Pro Overview MCU-Link Pro has complete functions. This article mainly introduces the usage and precautions of several basic functions, including SWD debugging, UART (VCOM) and energy measurement. The following figure is the reference diagram of MCU Link Pro, covering all functions, and the highlighted part is the function used in this article.   2.1 SWD debug As a debugger, the most basic function of MCU Link Pro is debugging, and now commonly used is SWD debug. When you get the development board, you can see that there are three SWD interfaces on it. Only J7 is the SWD interface to debug target board. It is on the opposite side of the USB interface to facilitate the connection and debugging of the target board. The other two interfaces J3 and J11 are SWD interfaces of LPC55s69 and LPC804 respectively. Another important function of this debugger is that it can supply power to the target board. The use method is to connect J6 with jumper, and 1.8V and 3.3V power supply can be selected through J5. The specific connection is shown in the figure below: - Connect the SWD interface of J7 and target board with debug line. - J6 connecting jumper cap (supplying power to target board).  The USB cable connects J1 and the computer, so you can debug with MCUXpresso IDE or other IDEs. CMSIS-DAP and J-Link debugging protocols are supported. For how to update the debugger firmware, please refer to:https://www.nxp.com/document/guide/getting-started-with-the-mcu-link-pro:GS-MCU-LINK-PRO   2.2 UART (VCOM) Usage In the development and debug stage, users often need to print information through the serial port. Using MCU Link Pro, without additional hardware, directly connect the TX and Rx of target UART with the Rx / TX of UART of MCU Link Pro. Through the VCOM function, you can print information from the USB port to the serial port assistant at the PC end. The specific connection is shown in the figure below: - J19-8 (purple line) connects UART TX of target board - J19-9 (gray line) connects the UART RX of the target board - J19-1 (GND) connect GND of target board - J14 disconnected - J6 plug in the jumper cap (supply power to the target board)   2.3 Energy measurement The MCU Link Pro board contains a circuit that can measure the current or voltage of the target board, and it can be calibrated automatically every time it is powered on without manual intervention. There are two maximum measurement ranges for energy measurement. If the data is higher than the maximum range, the measurement result is inaccurate. The two maximum measurement ranges are as follows, which need to be configured with J16, J17 and J18.   Energy measurement needs to be used with MCUXpresso IDE, and the results are displayed in the IDE interface. Use J9 port on the board. The specific connection is shown in the figure below: - J9-1 connects the power supply end of the target board. - J9-3 connects the chip ends of the target board. - J9-2 connects the GND of the target board For details on how to use the MCU Xpress IDE interface, please refer to:<MCUXpresso_IDE_Energy_Measurement.pdf> 3. Test result The test results are as follows:          
View full article
Recently, customers reported that the number of PWM generated by SCTimer module was inconsistent between LPC55s06 user manual and data sheet. There are many kinds of PWM generation formats, so the maximum number of PWM generated by SCTimer is also different. I think the user manual and data sheet are not very clear, so this paper makes a specific analysis. It mainly depends on SCTimer resources, such as the number of events and output channels. For all LPC series, the mechanism of SCTimer generating PWM is the same. Therefore, this paper takes LPC55s6 as an example. LPC55s06 user manual: The SCTimer/PWM supports: – Eight inputs. – Ten outputs. – Sixteen match/capture registers. – Sixteen events. – Thirty two states. According to the different control modes of generating PWM wave, this paper is divided into single-edge PWM control, dual-edge PWM control and center-aligned PWM control. 1. Single-edge PWM control The figure below shows two single-edge control PWM waves with different duty cycles and the same PWM cycle length.   It can be seen from the above figure that the two PWM waves require three events: when the counter reaches 41, 65 and 100 respectively. Because of the same PWM cycle length, all PWM outputs need only one period event. Summary: The cycle length of all PWM waves are the same, so only one period event is required. The duty cycles of each PWM are different, and each PWM requires an event. The SCTimer of LPC55s06 has 16 events, one is used as PWM period event, and there are 15 left. Theoretically, 15 channels of PWM can be generated. However, LPC55s06 has only 10 outputs, so it can generate up to 10 single-edge control PWM waves. 2. Dual-edge PWM control The figure below shows three Dual-edge control PWM waves with different duty cycles and the same PWM cycle length.   It can be seen from the above figure that the three PWM waves require seven events: when the counter reaches 1, 27, 41, 53, 65, 78, 100.   Summary: PWM cycle length control needs one event, and each PWM duty cycle needs two events to trigger. The SCTimer of LPC55s06 has 16 events, one as PWM frequency event, and the remaining 15, so it can generate up to 7 dual-edge control PWM waves. 3. Center-aligned PWM control Center-aligned PWM control is a special case of dual-edge PWM control. The figure below shows two center-aligned PWM waves with different duty cycles and the same PWM duty length.   It can be seen from the above figure that the two center-aligned PWM waves need three events in total, which are the PWM cycle length and the duty cycle trigger of the two PWM waves. Because the left and right are symmetrical, only one event is needed to control the duty cycle of one PWM. Summary: All PWM have the same cycle length, so an event is required. The duty cycle of each PWM circuit is different, but the left and right are symmetrical, and an event trigger is required for each circuit. The SCTimer of LPC55s06 has 16 events, one is used as PWM cycle length, and there are 15 left. Theoretically, 15 channels of PWM can be generated, but LPC55s06 has only 10 outputs, so it can generate up to 10 channels of unilateral control PWM wave. Summary:   Maximum number of PWM generated by LPC55s6 SCTimer: Single-edge PWM control : 10 Dual-edge PWM control : 7 Center-aligned control: 10   The number of SCTimer events and output channels is different with different chips, but the analysis method is the same. Customers can analyze whether the SCTimer in a certain chip meets the requirements.
View full article
1.     Problem description When we debug a new designed LPC55 custom board through SWD, if IDE throws out error messages such as connection failure or no available device being found, normally we must check below two points: Whether the debug circuit design is correct.( https://community.nxp.com/t5/LPCXpresso-IDE-FAQs/Design-Considerations-for-Debug/m-p/469565#M44 ) Whether LPC55 power supply system is correct. Regarding to the second point of power supply system, we received many feedback from customers that even they read UM for times they still can’t well-understand LPC55xx DCDC power supply system. Therefore we prepare this article to analyze LPC55xx power supply circuit and introduce detection method. 2.     Problem Analysis The difference of power supply circuit between LPC55xx series and other LPCs is that LPC55xx uses DCDC circuit inside to provide core voltage. It lowers the input 1.8V-3.6V voltage to around 1.1V to supply LPC55xx internal system. The DCDC converter is efficient and reduces the internal power consumption. The disadvantage is that it generates a certain ripple. LPC55xx power supply circuit is as follows: In order to analyze, We divide LPC55xx power supply circuit into 4 regions and will introduce them one by one according to the different functions.   1)  Input voltage: In this part, VBAT_PMU provides input voltage to RTC and internal analog components. VBAT_DCDC provides input voltage to internal DCDC circuit. 2)  A set of filter capacitors: To filter out the burrs and glitch at the voltage input. 3)  DCDC circuit: Work with LPC55xx internal DCDC circuit together to generate 1.1V output voltage. 4)  VDD_PMU: Provides the 1.1V output voltage of the DCDC circuit to the LPC55xx core. Note: The design of region 3 is to work with the internal DCDC converter. The inductance L1 of 4μ7H and the capacitance C1 of 22μF are calculated by LPC55xx internal circuit. When designing, we must strictly follow the parameters recommended in the manual, otherwise DCDC circuit can’t work normally. 3.     DCDC Circuit Detection LPC55xx power supply system current direction is shown in the diagram below. See arrow in red. In order to ensure the normal operation of the DCDC circuit, the following two detection points are recommended. 1)  Detection point 1: External 1.8 to 3.6V voltage input, normally it’s 3.3V. 2)  Detection point 2: Output of the DCDC converter. If the DCDC works normally, we can get 1.1V voltage output here. The output voltage supplies power to the core components such as the central processing unit through the VDD_PMU. If DCDC convert input is correct but output wrong, we suggest checking inductor L1 and the capacitor C1 and related solder issue. If the voltage of two detection points are correct, the power supply circuit problem can be ruled out. 4.     summary: For custom designed LPC55xx board, if SWD design is correct and power supply system works well, IDE can connect, download and debug target without issue.  
View full article
Contents 1. Introduction 1 2. USB Demo based on MCUXpresso SDK 1     2.1 Update USB device demo: USB0->USB1 2     2.2 Update USB host demo: USB0->USB1 2     2.3 Update USB ROM demo: USB0-> USB1 3 3. USB Demo based on LPCOpen 3 4. Notes and Recap 4  1.     Introduction Most of LPC devices integrate USB module. NXP LPC currently integrates full-speed USB (FS, Full Speed, 12Mbps) and high-speed (HS, High Speed, 480Mbps) USB. Specifically, for the LPC series: - Some LPCs such as LPC55xx and LPC54xxx integrate both HS USB and FS USB. Usually USB0 is FS USB and USB1 is HS USB. - Some LPCs such as LPC43xx and LPC18xx integrate two HS USBs, so USB0 and USB1 are both HS USBs. The two most well-known NXP software packages for LPC series are MCUXpresso SDK and LPCOpen. MCUXpresso SDK is mainly for LPC products launched in recent years, while LPCOpen is used for earlier LPC derivatives. The USB demos included in these two packages run on USB0 by default. Most of NXP USB demos are for USB0 by default. This article is to introduce how to switch a USB0 demo to USB1 demo based on different software packages. 2.     USB Demo based on MCUXpresso SDK (e.g. LPC54XXX, LPC55XX) The MCUXpresso SDK USB demo codes are categorized as: - USB as Device: e.g. usb_device_cdc_vcom, usb_device_hid_generic, etc. - USB as Host: e.g. usb_host_hid_mouse, usb_host_msd_fatfs, etc. - USB demo based on USB ROM API: e.g. usb_rom_device_audio,usb_rom_device_cdc, etc. 2.1  Update USB device demo: USB0->USB1 Taking usb_device_cdc_vcom demo as an example. To switch to USB1, simply change the corresponding code in usb_device_config.h file as follows. /*! @brief LPC USB IP3511 FS instance count*/ #define USB_DEVICE_CONFIG_LPCIP3511FS (0U) /*! @brief LPC USB IP3511 HS instance count*/ #define USB_DEVICE_CONFIG_LPCIP3511HS (1U) After the change, recompile the program to run. The program was updated to USB1 device demo. 2.2   Update USB host demo: USB0->USB1 Taking usb_host_hid_mouse demo code as an example, to switch to USB1, modify the macro definition in usb_host_config.h as follows: #defineUSB_HOST_CONFIG_KHCI (0U) #defineUSB_HOST_CONFIG_EHCI (0U) #define USB_HOST_CONFIG_OHCI (0U) #define USB_HOST_CONFIG_IP3516HS (1U)   The program is recompiled and run. The program was updated to USB1 host demo. 2.3  Update USB ROM demo: USB0-> USB1 ( e.g. LPC54XXX Series) USB ROM demo calls the USB ROM API, there is no way to switch the default USB0 to USB1 by modifying macro definitions. In order to update code to USB1 demo, the recommended steps are as below: -USB HS DEVICE and USB PHY clock configuration -Change to use USB HS ISR -Locate the related buffer into USB RAM. -Set the USB ROM handle to be HS If user has difficulties in revising the code by self, user can apply demo code from NXP LPC online support team by creating a private case. 3.     USB Demo based on LPCOpen (e.g. LPC43XX, LPC18XX) Some legacy LPCs run on LPCOpen, such as LPC43xx series, LPC18xx series. Their USB0 and USB1 are both high-speed. The default USB demo is for USB0 as well. To switch to USB1, we can uncomment #define USE_USB1 and comment #define USE_USB0 in app_usbd_cfg.h. // #define USE_USB0  #define USE_USB1 Taking usbd_rom_cdc_uart demo as an example:   Recompile and run, the program is updated to USB1 demo. 4.     Notes and Recap The focus of this article is on software modification of converting USB0 to USB1 on NXP SW package. Regarding the hardware, customer needs to check the specific demo board user guide. For example, when we use HS USB, it may be necessary to provide an external power supply, and the jumper also needs to be adjusted to build a well hardware environment for HS USB operation. I will not dwell on them here. This article summarizes methods of switching USB0 to USB1 for several commonly used LPC series on MCUXpresso SDK and LPCOpen package. customers who need USB1 demo code can find the corresponding modification methods in this article for their own software and chips. Official routines are only used for demo board demos and chip learning. If for commercial usage, user needs to learn USB in depth and be responsible for own application.  
View full article
The article introduces the RSA theory, how to get the RSA parameter, how to encrypt/decrypt with the RSA algorithms. RSA is an asymmetric cryptographic algorithm and widely used in encryption/decryption application and signature application. It completes encryption and decryption operations by encrypting the message with the public key and decrypting with the private key. In order to support security requirements, it is also used in many places in the LPC55 series, such as: -  RSA digitally signs the application code with the private key, and verifies the authenticity of the code through RSA signature verification in secure boot . This is implemented in LPC55 secure boot. For the LPC family, the mbedtls library is used to implement the RSA algorithms with software.
View full article
Summary A software vulnerability CVE-2021-40154 has been identified in the USB enumeration packet handler, which could leak memory contents if a malformed enumeration request packet is sent to the device. This may occur if the device is configured in the in-system programming (ISP) or serial downloader protocol (SDP) mode or if unpatched USB example code is used in an application.   Mitigations Mitigations have been applied to: The boot ROM in the latest silicon revisions of i.MX RT 500 and 600 and LPC55XX parts USB examples in the MCUXpresso SDK 2.10 release and later For other devices, the ISP/SDP mode and/or the USB communication mode can be disabled.   Affected product list:                 NXP Device     Impacted Silicon Revisions LPC55S6x, LPC55S2x, LPC552x                      0A, 1B LPC55S1x, LPC551x    0A i.MX RT600                                       A0, B0 i.MX RT500                                         B1, B2 i.MX RT1010/20/50/60 i.MX RT1160/70 All K8x/KL8x K27/K28 K32L3/ K32W032 / K32LA/K32LB  KL27/KL28/KL43                                    All   The vulnerability also affects all MCUXpresso SDK USB device stack examples prior to 2.10.x release.  If the NXP device does not support USB or does not utilize the USB example code prior to version 2.10.x  in the application, then those would not be impacted. Additional Information Security bulletins with more details are available. For additional questions or support please contact your local NXP representative or submit a ticket at https://support.nxp.com/ Acknowledgments NXP PSIRT would also like to thank Sulthan Alaudeen Noor Mohamed from Digital14 – xen1thLabs, Hardware Labs for the responsible disclosure. _____________________________________________________________________________ Please note this information is preliminary and subject to change. To the best of NXP's knowledge, the information contained herein is accurate and reliable as of the date of publication; however, NXP does not assume any liability for the accuracy and completeness of the information.   Information in this document is provided solely to enable system and software implementers to use NXP products. There are no express or implied copyright licenses granted hereunder to design or fabricate any integrated circuits based on the information in this document. NXP reserves the right to make changes without further notice to any products herein. NXP makes no warranty, representation, or guarantee regarding the suitability of its products for any particular purpose, nor does NXP assume any liability arising out of the application or use of any product or circuit, and specifically disclaims any and all liability, including without limitation consequential or incidental damages. “Typical” parameters that may be provided in NXP data sheets and/or specifications can and do vary in different applications, and actual performance may vary over time. All operating parameters, including “typicals,” must be validated for each customer application by customerʼs technical experts. NXP does not convey any license under its patent rights nor the rights of others. NXP sells products pursuant to standard terms and conditions of sale, which can be found at the following address: nxp.com/SalesTermsandConditions. While NXP has implemented advanced security features, all products may be subject to unidentified vulnerabilities. Customers are responsible for the design and operation of their applications and products to reduce the effect of these vulnerabilities on customer's applications and products, and NXP accepts no liability for any vulnerability that is discovered. Customers should implement appropriate design and operating safeguards to minimize the risks associated with their applications and products.
View full article
  [LPC546xx] Understanding ECRP   Code protection is usually considered at the last step during developing stage. The purpose is to protect our code being hacked when the product is released to market. For example, using ECRP to disable SWD debug interface, disable ISP, disable mass erase, etc. 1.    ECRP vs Legacy CRP   ECRP (Enhanced Code Read Protection) is versus legacy CRP on early LPC devices. We can consider ECRP as an advanced version of CRP. Comparing with CRP, ECRP adds new protection features: − Block ISP via Pins − Block ISP using IAP − Block SWD − Mass Erase enable/disable − Sector protection This table lists the difference of ECRP vs. CRP from Anti-Tampering and Flexible view. 2.    Understand and implement ECRP ECRP allows user to tenable below features: − Protect FLASH from ISP Erase/Write − Protect FLASH from IAP Erase/Write − Enable/Disable ISP Entry from bootloader − Enable/Disable ISP Entry from IAP call − Enable/Disable SWD Enable/Disable It looks easy but it is important to know that ECRP feature is controlled by both FLASH and OTP configuration! The most restrictive combination in both setting is needed 2.1          Where is FLASH ECRP: ECRP is at 0x20 of vector table, it’s uint32_t type. We write to this address to set FLASH ECRP protection. The valid bits of FLASH_ECRP is 0-17bit, and the default value is 0xFFFF_FFFF. For detail, please see UM.   2.2          Where is OTP ECRP OPT is a non-volatile and write-once register. OTP is not FLASH and it can be ONLY written by IAP function. OPT ECRP configuration is at OPT bank 3. The default OTP ECRP value is 0.   2.3          FLASH ECRP + OTP ECRP Decides the Protection. See this table to show the combination. Here OTP ECRP is always set with higher priority than FLASH ECRP! Here is typical ECRP settings 2.4        Be Attention! The part is permanently disabled when On-chip Image(s) are ruined SWD access prohibited ISP entries prohibited Please be attention when testing ECRP feature, mis-operation may make the chip brick!
View full article
This article mainly introduces how to use CTIMER measuring pulse-width in LPC845, in fact, it can applies to all LPC products  including CTIMER modules. 1  CTIMER has below features: A 32-bit timer/counter with a programmable 32-bit prescaler. Four 32-bit match registers that allow interrupt generation on  match. The timer and prescaler may be configured to be cleared on a designated capture event. This feature permits easy pulse width measurement by clearing the timer on the leading edge of an input pulse and capturing the timer value on the trailing edge.(This article mainly use this feature.) Up to four match registers can be configured for PWM operation.   2 Introduction There is neither pulse-width measurement nor input capture demo under SDK, so write this article and related code for this topic. The principle is clearing the timer and prescaler on the leading edge of an input and capturing the timer valued on the trailing edge.   3  Main steps   Step1 Choose CAP input channel, capture edge, and enable interrupt if needed. Using “Capture control register”. The Capture control register is used to control whether one of the four capture registers is loaded with the value in the timer counter when the capture event occurs, and whether an interrupt is generated by the capture event. Setting both the rising and falling bits at the same time is a valid configuration, resulting in a capture event for both edges. In the description below, n represents the timer number, 0 or 1. In this example, choose capture channel 0 as input channel, falling edge as capture edge, and enable capture interrupt. SDK code: CTIMER_SetupCapture(CTIMER,CTIMER_CAP0_INT,  CTIMER_CAP_FALL,TRUE); Step2 Select which capture input edge will cause the timer and pre-scaler to be cleared. Using “Count control register”. The Count Control Register (CTCR) is used to select between timer and counter mode, and in counter mode to select the pin and edge(s) for counting. When counter mode is chosen as a mode of operation, the CAP input (selected by the CTCR bits 3:2) is sampled on every rising edge of the APB bus clock. After comparing two consecutive samples of this CAP input, one of the following four events is recognized: rising edge, falling edge, either of edges or no changes in the level of the selected CAP input. The timer counter register is incremented only if the identified event occurs and the event corresponds to the one selected by bits 1:0 in the CTCR register. Effective processing of the externally supplied clock to the counter has some limitations. Since two successive rising edges of the APB bus clock are used to identify only one edge on the CAP selected input, the frequency of the CAP input cannot exceed one half of the APB bus clock. Consequently, duration of the HIGH/LOWLOW levels on the same CAP input in this case cannot be shorter than 1/APB bus clock. Bits 7:4 of this register are also used to enable and configure the capture-clears-timer feature. This feature allows for a designated edge on a particular CAP input to reset the timer to all zeros. Using this mechanism to clear the timer on the leading edge of an input pulse and performing a capture on the trailing edge, permits direct pulse-width measurement using a single capture input without the need to perform a subtraction operation in software. In this example, we choose timer mode, configure Channel 0 rising edge clearing the timer, enable clearing of the timer and the pre-scaler. SDK code:   CTIMER->CTCR = CTIMER_CTCR_CTMODE(0)|CTIMER_CTCR_SELCC(1)   |CTIMER_CTCR_ENCC_MASK ; Step3 Read pulse-width value from “Capture register”. Each Capture register is associated with one capture channel and may be loaded with the counter/timer value when a specified event occurs on the signal defined for that capture channel. The signal could originate from an external pin or from an internal source.   SDK code: CTIMER_GetCAPCounter(HW_CTIMER0, HW_CTIMER_CH0); We can read capture value on capture interrupt. Detail code please refer to attached project, it based on MCUXpresso IDE v11.3, SDKv2.9, LPCxpresso845MAX board.   4  Test Result Input a signal as below into channel 0 (P1_0), pulse width is 10us. Print the measurement results on Console view of MUXpresso IDE:        
View full article
Recently I found some customers have a bit of problem when porting project from one MCU to another, so this article using simple steps demonstrates how to change MCU with MCUXpresso. There is also a video demonstrated the detail steps in attachment. Pay attention, as MCUXpresso User Guide says: All projects are associated with a particular MCU at creation time. The target MCU determines the project memory layout, startup code, LinkServer flash driver, libraries, supporting sources,launch configuration options etc. etc. so changing a project’s associated MCU should not be undertaken unless you have a total grasp of the consequence of this change. Therefore rather than changing a project’s associated MCU, it is strongly recommended that instead a new project is generated for the desired MCU and this new project is edited as required. However, on occasion it may be expedient to reset a project’s MCU (and associated SDK) and this can be achieved as follows. For example, changing lpc55s69 to lpc55s06, we need install SDKs for lpc55s69 and lpc55s06 before all the below steps. 1 - Change MCU & Package 1.1 – Change MCU Right click “MCU” under Project tree, choose “Edit MCU” Uncheck ”Preserve memory configuration”(it is checked by default)->choose LPC55S06->there is a warning, choose Yes. We can see the Memory details changed to lpc55s06, then click ”Apply and close”. 1.2 – Change Package 2 - Change Compiler Definitions In Properties view->Settings->MCU Compiler ->Preprocessor, change the definition for CPU from LPC55S69JBD100 to LPC55S06JBD64 as below: 3 – Change/add SDK driver for LPC55s06 Selected project, then click ”Manage SDK components”, choose the drivers our application used, for example, clock, power, usart. Click “OK”, then click “Yes” to update. Delete LPC55S69 device related files: Add “system_LPC55S06.c” and “system_LPC55S06.h” files: 4 - Change startup file. Delete LPC55s69 startup files, add “startup_lpc55s06.c”, we can find the startup file in any SDK demo. 5 - Change board related files. Refer to our own new board, change files under “board” folder, for example pins, uart number, here directly copy from SDK demo for LPCxpresso55s06 board. 6 - Test the project  function with new board Build project until no compile error, download and run it, result as below.        
View full article
This is an example of how to use the CTimer to trigger the LPADC conversion in the LPC55s28. I attached the example in MCUXpresso.    
View full article
LPC: Regarding to Internal Clock Calibration In MCU development, using the internal crystal oscillator as a clock source instead of the external crystal oscillator can save costs. But the clock frequency generated by the internal crystal oscillator is affected by temperature and MCU frequency more than external crystal oscillator. Many customers have questions about the internal clock accuracy, whether the internal clock can be used for USB transmission, and how to calibrate the internal clock. This article mainly explains this. 1. Calibrate internal clock by FREQTRIM Normally, we can only calibrate the internal clock by adjusting the FREQTRIM value. The internal clock frequency is affected by temperature, MCU frequency and other factors. The FRO control register can calibrate the internal clock, as follows:   The FREQTRIM register value ranges from 0 to 255, and each adjustment step is about 0.1% of the internal clock frequency. There is no precise formula to express the relationship between the FREQTRIM value and the FRO frequency. The ideal FREQTRIM value can only be determined by adjusting FREQTRIM in code and observing FRO output waveform with oscilloscope. Test and observation: The following is the test result. It shows how FRO frequency varies with FREQTRIM increasing from 0-255. Test result of first development board:     Test result of second development board:   The following two points can be seen from test results: - There is no linear relationship between the FRO clock frequency and the FREQTRIM register value, and there is no precise formula to express the relationship between them; - Even for chips of the same part number, the internal clock frequency changes are slightly different, with the FREQTRIM register value changing, but the trend is same. Therefore, there is no precise formula to guide internal clock frequency calibration. You can only adjust the FREQTRIM register value repeatedly, just like adjusting the focus of a projector. Use an oscilloscope to check the frequency of the internal clock pin to find the most suitable FREQTRIM register value. There is same solution for FRO clock frequency calibration about other LPC chips.   2. LPC51U68: Software calibration USB transmission when using internal clock source The Full Speed USB module of LPC51U68 has a unique FRO automatic calibration function, which automatically adjusts the FREQTRIM value to achieve FRO calibration by measuring the USB SOF bit. Once FRO is calibrated, the corresponding system clock and peripheral clock are calibrated. This solution is only applicable to LPC51U68, please refer to the user manual for other chips. The following is the FRO clock accuracy described in LPC51U68 User Manual, which is ± 1%:   For Full Speed USB, the USB data transmission accuracy requirement is ±0.25%, and the FRO clock accuracy is not satisfied. NXP provides a software solution to calibrate FRO by measuring the first packet of frame (SOF), which can meet the transmission accuracy in Full Speed mode.   The solution download link is as follows: https://www.nxp.com/docs/en/application-note/TN00035.zip  
View full article
After LPC54XXX enter ISP mode, there are two methods to upgrade the application through UART/I2C/SPI/USB. One method is to change the ISP pin state when power on, and the other method is to reinvoke ISP Boot ROM in source code during code running. The first method does not require user to write any code, and the operation is simple, but the disadvantage is that it is not flexible and is not suitable for on-site operation; The second method is more flexible and is widely used in Secondary Bootloader applications developed by yourself, but it requires users to write their own code. In actual development, because the USB port of personal computer is easy to use, the method of using the USB port for application upgrade is becoming more and more popular. Unfortunately, we currently do not have instructions for upgrading the application by the USB port in ISP mode. So we write this article to share the method here.   There are two methods to enter ISP mode: Method 1: Enter ISP mode to upgrade the application during power on On the hardware side, configure the ISP0~2 pins before power-on or reset, and the MCU enters ISP mode to upgrade the application. The pin configuration method is as follows: Figure 1.   Method 2: Activate Reinvoke ISP in source code to upgrade the application In ISP mode, the application is upgraded through UART/I2C/SPI/USB. This article focuses on the USB method. Here for USB, Both USB0 (Full Speed) and USB1 (High Speed) of LPC54XXX can be used for application upgrade. There are two USB upgrade modes: DFU (Device Firmware Updata) and MSC (Mass Storage Device Class), as follows: Figure 2.   Select the application upgrade mode by modifying byte 0 and byte 1 of the ISP parameter array. The key code is as follows Figure 3.   There are 3 key point we need to pay attention in Figure 3: -When isp_mode[0] is configured as 0xAA, it is DFU mode, otherwise it is MSC mode (for example, isp_mode[0] is configured as 0xFF). -When isp_mode[1] is configured as 8, USB FS is used, and when it is configured as 9, USB HS is used. -Enter the ISP mode through the Chip_IAP_ReinvokeISP function. 2.1 Use DFU for application upgrade Tool preperation: To work with DFU, dfu-util tool is needed to use DFU to upgrade the application, you can download the DFU tool on the DFU official website. The link is as follows: http://dfu-util.sourceforge.net/ NXP also includes the dfu-util tool in LPCScrypt. If you have downloaded LPCScrypt, you can use it directly in the bin directory.   DFU update application Steps: Take LPC54628 as an example, ISP is configured as DUF mode, and USB1 is used to upgrade the application. Modify the relevant code in Figure 3, as follows: isp_mode[0] = 0xAA; isp_mode[1] = SL_USBHS; Build and download the application to the MCU, power on again, and connect USB1 to the computer. Here Enter the dfu-util tool directory and copy the .bin file to the current directory. Use the command: ./dfu-util -l   Find the DFU devices. Use the command: ./dfu-util -D .\lpcxpresso54628_gpio_led_output.bin -a 0 Download the lpcxpresso54628_gpio_led_output.bin file to the device with alt number 0. Alt0 is "FLASH", alt1 is "RAM", and the specific operations are as follows:   Figure 4.   After downloading the application successfully, reset the MCU and observe the blinking phenomenon of the LED on the development board.   2.2 Use MSC for application upgrade Take LPC54628 as an example, ISP is configured as MSC mode, and USB1 is used to upgrade the application. Modify the relevant code in Figure 3, as follows: isp_mode[0] = 0xFF; isp_mode[1] = SL_USBHS; Build and download the application to the MCU, power on again, and connect USB1 to the computer. You will found another disk in my computer, as follows: Figure 5.   Then do the following to update firmware: -Remove the original firmware.bin in the CRP DISABLD disk. -Rename the application (for example, lpcxpresso54628_gpio_led_output.bin) to firmware.bin. -Copy the application firmware.bin to the CRP DISABLD disk. -Reset the MCU, if the LED is observed blinking, it proves that the application has been successfully upgraded. Note: The application must be renamed, and the rename cannot be performed in the CRP DISABLD disk.   Demo project: lpcxpresso54628_flashiap.zip Application upgrade file:lpcxpresso54628_gpio_led_output.bin (generated by SDK demo code)
View full article
I already have several customers met SB file loading error Inject command 'receive-sb-file' while working on LPC55S6xx 1B version. There is significant change of Secure Boot in LPC55S6xx 1B version and 0A version. To solve this problem, we need to understand it first.     1  SB2.1  vs. SB2.0 SB2 container is described in elftosb User’s Guide. SB file config file contains configuration commands that will be processed after SB2 file is loaded in the device. The image location is stated in the "sources" .bd file section. SB key in text file is used for encryption with elftosb command line tool.   The 0A version of the LPC55S6xx silicon supports version 2.0 of the SB image format. The 1B version of the LPC55S6xx silicon supports version 2.1 of the SB image format. The main difference between version 2.0 and version 2.1 is in the usage of the digital signature. SB 2.0 is encrypted and SB2.1 is encrypted + signed.     2. SB file Preparation and Usage   Example of use (Encrypted SB2):   elftosb -f lpc55xx -k "sbkek.txt" -c "commandFile.bd" -o "output.sb2" "input.bin"   where -f = family lpc55xx -k = path to KEK file (SBKEK) -c = path to command file to be processed:   options { flags = 0x4; // 0x8 encrypted + signed, 0x4 encrypted buildNumber = 0x1; productVersion = "1.00.00"; componentVersion = "1.00.00"; } sources { inputFile = extern(0); } section (0) {       erase 0x0..0x40000; load inputFile > 0x0; }   -o = path to output file   files... = path to files (usually image files), which will be replacing placeholders defined in command file, paths can be hardcoded in command file and then not inserted as input   Example of use (Encrypted + Signed SB):   1 root key   elftosb.exe -f lpc55xx -k "sbkek.txt" -c "commandFile.bd" -o "output.sb2" -s "selfsign_privatekey_rsa2048.pem" -S "selfsign_v3.der.crt" -R "selfsign_v3.der.crt" -h "RKTH.bin" "input.bin"   4 root keys   elftosb.exe  -f lpc55xx -k "sbkek.txt" -c "commandFile.bd" -o "output.sb2" -s private_key_1_2048.pem -S certificate_1_2048.der.crt -R certificate_1_2048.der.crt -R certificate_2_2048.der.crt -R certificate_3_2048.der.crt -R certificate_4_2048.der.crt -h "RHKT.bin" "input.bin"   where -f = family lpc55xx -k = path to KEK file (SBKEK) c = path to command file to be processed   options { flags = 0x8; // 0x8 encrypted + signed, 0x4 encrypted buildNumber = 0x1; productVersion = "1.00.00"; componentVersion = "1.00.00"; } sources { inputFile = extern(0); } section (0) {       erase 0x0..0x40000; load inputFile > 0x0; }   -o = path to output file -s = path to private key of certificate used for signing -S = path(s) to certificates in certificate chain, each certificate in chain must be specified with new -S switch in order of how was chain created (root certificate first) -R = path(s) to root certificate(s), 1-4 root certificates can be specified, each root certificate must be specified with new -R switch, one of the root certificates must be first certificate specified by -S switch -h = path and name of output binary file generated by elftosb, which contain hash of hashes of all root certificates (RKTH), which must be uploaded to the device register files... = path to files (usually image files), which will be replacing placeholders defined in command file, paths can be hardcoded in command file and then not inserted as input The SB2.0 file created with the updated binary image can be loaded into the device through ISP command handler with command “receive-sb-file“   blhost -p COMxx receive-sb-file <path to the secured binary(.sb2)>   The SB2.1 file created with the updated binary image can be loaded into the device through ISP command handler with command “receive-sb-file“ but keep in mind that before sending SB2.1 file into device has to be there already RKTH in CMPA (see AN12283 chapter 5.5 CMPA preparation) and enabled RoT keys in ROTKH_REVOKE field at CFPA page address 0x9DE18 (see chapter AN12283 5.4 CFPA preparation).   blhost -p COMxx receive-sb-file <path to the secured binary(.sb2)>   After successfully loading the SB2 file it is executed as configured in SB configuration file (.bd file). The above figure shows an example of SB configuration file. When the file is executed, the internal flash address from 0x0 to 0x40000 is erased. After flash erase operation, the image mentioned in the sources parameter is loaded to address 0x0. Reset the device after these operations. The updated image loaded into internal flash starts to execute.    English and Chinese versions of this article are both attached.
View full article
LPC55xx系列的MCUXpresso SDK使用FLASH API来实现FLASH驱动。 一些用户在执行如下FLASH写操作时可能会遇到如下的问题: status = FLASH_Program(&flashInstance, destAdrss, (uint8_t *)s_bufferFF, 8);       执行完上述代码后,对应的地址区间数据没有变化,写入失败,返回错误代码101,如下图所示, 错误代码101看上去有点陌生,这在之前的LPC产品中并不常见,我们在用户手册中搜索 FLASH driver status code ,可以查找到错误代码101为FLASH 对齐操作错误(Alignment Error)。   对齐操作错误是什么?我们先来看程序是如何对 FLASH_Program 函数进行定义的。 FLASH 写函数定义如下: status_t FLASH_Program(flash_config_t *config, uint32_t start, uint32_t *src, uint32_t lengthInBytes); 新用户经常会忽略掉用户手册中对于这个 API 的介绍“ the required start and the lengthInBytes must be page size aligned ”,这句话的意思是在执行 FLASH_Program 函数时,写入的起始地址和数据长度必须 512 字节对齐,所以如果我们把代码 status = FLASH_Program(&flashInstance, destAdrss, (uint8_t *)s_bufferFF, 8); 更正为 status = FLASH_Program(&flashInstance, destAdrss, (uint8_t *)s_bufferFF, 512); FLASH_Program 函数就可以运行成功。   请注意 :在 2.6.x 版本的 SDK 中, FLASH_Program 函数的注释将参数的起始地址和数据长度错误的表述为字对齐, 2.7.0 版本的 SDK 已经对注释进行了修正。即使你想要操作一个字节, lengthInBytes 也是512字节对齐。   最后 :建议用户在遇到关于 FLASH API 操作失败 的相关问题,一定要查看用户手册中的 FLASH 驱动状态码,我们可以从 UM11126 中的第九章节 FLASH API 部分找到它,如下图所示。  
View full article
经常有客户在使用LPC55S69的过程中遇到读 Flash进入异常HardFault中断的现象。如果在Flash Mass Erase之后从未对Flash扇区进行过写操作,直接用指针通过AHB读Flash地址会导致程序跳入HardFault 中断而无法继续正常运行。 原因    刚出厂的 LPC55Sxx FLASH 处于全零的全擦除状态,没有设置 ECC 。当芯片通过 LinkServer 和 MCUXpresso IDE 建立连接时,先擦除要下载代码用到的扇区,再把代码下载到对应位置,并对相应存储区的 ECC 值同时进行更新。代码以外的区域仍然是无 ECC 设置的擦除状态。 当 LPC55Sxx 通过 AHB 总线直接读取 Flash 内存区域时(例如,mytemp = *(uint32_t*)0x4000)要对 Flash ECC 进行校验。这一指令对于读有效代码区是没有问题的, 因为这一区域的 ECC 在下载代码时早已设置好。但是一旦读取没有代码的扇区,由于没有检测到正确的 ECC ,导致 Flash 读取失败,并跳转到下图中的 HardFault_Handler() 异常中断:   我们在 Sector Erase 后通过 AHB 读取 Flash 内存内容,也会遇到同样的 HardFault 异常跳转,出问题的原因都是一样的。 解决方法 针对这一问题我们有如下两种解决方法: 先执行 Flash 写操作,再读取 Flash 与 Flash 擦除操作不同,执行 Flash 写操作后对应的 ECC 值也同步更新。这样, ECC 校验通过后,通过下面的代码就可以对 Flash 直接进行 AHB 读取。 volatile uint32_t mytemp; …… mytemp = *(uint32_t*)0x1000;//read memory content 0x1000 to mytemp 请注意: 0x1000 必须是一个已经写过的地址。 如果 Flash 的某个扇区处于被擦除的状态,我们只需要在通过 AHB 总线读取内存区域之前对该区域执行写操作,这样 ECC 校验位更新正确后,就可以正常读 Flash 。 Flash 的写操作可以参考 MCUXpresso SDK 自带的 flashiap 例程,函数 FLASH_Program 。   使用 Flash 控制指令读取 Flash 区内容 使用Flash控制指令进行读操作不会导致硬件错误(请参阅 UM11126 “Command listing (CMD)” 章节)。这是用户手册中推荐的读Flash正确打开方式。 请注意: CPU 只有在频率低于 100MHz 时,才能进行 Flash 操作(读,写,擦除,校验,等等),当 CPU 频率超过 100MHz 时是不能实现上述操作的。 目前,官方没有提供上用控制指令读取 Flash 内容的例程,因此需要您根据下面步骤创建自己的读 Flash 程序。 开发环境: IDE: MCUXpresso IDE v11.1.0 SDK MCUXpresso SDK v2.7.0 步骤: 在 MCUXpresso IDE 中导入一个基础例程,如 led_blinky 在下图所述选项中添加 iap 组件   选择 iap1, 点击 OK   点击完 OK 之后,fsl_iap_ffr.h, fsl_iap.c, fsl_iap.h文件将自动添加到工程中   在 source 文件夹中添加附件中的 memory.h 和 memory.c 文件   4) 使用 Flash 控制指令时,需要在源文件中添加memory.h, fsl_iap.h   5) 调用 memory 初始化和 memory 读取函数   6)调试,单步执行( step over )到memory_read(),查看结果  
View full article