Understanding Zero Division Operations in STM32 Microcontrollers

This issue’s topic:

As is well known, in C language, dividing a number by 0 will lead to a division operation exception, causing the program to crash.

To avoid program crashes, we need to include checks for 0 in the code.

However, when running C program code that performs division by zero on STM32 microcontrollers, the program does not crash. Why is that?

Today, let’s briefly discuss this issue.

Discussion:

According to conventional understanding, if a division by zero operation appears in C program code, it will enter exception handling, leading to program exceptions.

Some friends have encountered a scenario where the code following a division by zero operation can execute normally on an STM32 microcontroller.

By consulting the Cortex-M3 guide, we can see that a division by zero operation leads to a Usage Fault.

Understanding Zero Division Operations in STM32 Microcontrollers

From this, we can understand that entering a Usage Fault has prerequisites: it only occurs when DIV_0_TRP is set.

By configuring DIV_0_TRP, we can enable division by zero exception interrupt capture. This bit register is located in the SCB->CCR register.

Understanding Zero Division Operations in STM32 Microcontrollers

By default, DIV_0_TRP is 0, and division by zero operations will not produce exceptions, and the result will always be 0; when DIV_0_TRP is set to 1, it will trigger a division by zero exception interrupt.
Understanding Zero Division Operations in STM32 Microcontrollers

Now, we can explain why STM32 microcontrollers do not crash during division by zero operations under default conditions.

Additionally, division by zero triggers a Usage Fault, but by default, the Usage Fault is disabled. In this case, the division by zero exception will enter the Hard Fault exception interrupt.

If you want it to enter the Usage Fault, you need to configure it through the SHCSR register bit 18.

Understanding Zero Division Operations in STM32 Microcontrollers

That’s all for today, thank you for reading!

Understanding Zero Division Operations in STM32 Microcontrollers

END

Source: Learn Embedded Together
Copyright belongs to the original author. If there is any infringement, please contact for deletion.
Recommended Reading
I used this technique to eliminate thousands of lines of if-else!
Kirin 9000s is not from SMIC, but…
The words programmers are most likely to misread; hearing ‘status’ made me explode

→ Follow for more updates ←

Leave a Comment

×