on 2026-03-23 5:34 AM
This article provides a step-by-step guide to enable the memory protection unit (MPU) and configure a memory region in STM32CubeMX2. The example uses the NUCLEO-C562RE board.
The memory protection unit (MPU) is a microcontroller feature that allows developers to configure access and execution permissions for memory regions. The MPU can make an embedded system more robust and secure by, for example, defining a SRAM region as non-executable to prevent code injection attacks.
This article demonstrates how to configure a memory region as read-only and shows the error triggered when attempting to write to this region.
Follow the steps below to create an application project for the NUCLEO-C562RE board.
The MPU configuration is available under the Peripherals tab. To facilitate the workflow, observe the image below with the numberings for a quick identification:
For this example, configure a region from 0x20010000 to 0x20010100 as non-cacheable and read-only. Any write operation within this region should fail. For more information about MPU memory types and attributes, see Managing memory protection unit in STM32 MCUs - Application note.
To generate the code:
1. Open Visual Studio Code and open the project folder.
2. You are prompted with a selection. In case you miss click or that does not appear, press Ctrl+Shift+P, type CMake: Select Configure Preset, and choose your debug configuration.
After opening the generated project in Visual Studio Code, verify the MPU configuration by attempting to write data inside the protected region.
*(volatile uint32_t*) 0x20000050 = 0x12345678; // Writing outside read-only region.
*(volatile uint32_t*) 0x20010000 = 0x12345678; // Writing inside the read-only region. Error expected
void MemManage_Handler(void)
{
// User code if required
while (1);
}
This article demonstrates how to enable and configure the MPU in STM32CubeMX2 using the NUCLEO-C562RE board. By setting up a memory region as read-only, the example shows how the MPU enforces access permissions and protects against unauthorized writes. Proper MPU configuration is essential for preventing memory-related errors and safeguarding microcontroller operation.
We’re moving the ST Community to a new platform to give you a better and more reliable community experience.