I am getting division by zero error at this line:
if (tim2_st_ovf < T2_PREK_250)
These values are defines like this:
volatile uint8_t tim2_st_ovf = 0;
#define T2_PREK_250 ((250 * (F_CPU / 1000)) / ((UINT8_MAX + 1) * 1024))
#define F_CPU 16000000UL
And UINT8_MAX
equals to 255.
Why am I getting this? I calculated it several times on calculator and am getting ~15. Also, if I change 1024 to 1023 it doesnt show any error.
In languages like C, C++ etc. division by zero invokes undefined behaviour. So according to the language definition, anything can happen.
Handling the Divide by Zero Exception in C++Dividing a number by Zero is a mathematical error (not defined) and we can use exception handling to gracefully overcome such operations.
Dividing a floating-point value by zero doesn't throw an exception; it results in positive infinity, negative infinity, or not a number (NaN), according to the rules of IEEE 754 arithmetic.
((UINT8_MAX + 1) * 1024)
may become 0, because UINT8_MAX + 1
is usually 256, and 256 * 1024
is 0 modulo 216. So if sizeof(int) == 2
on your achitecture, then you get 0.
On the typical modern desktop architectures with GCC, sizeof(int) == 4
, and you wouldn't get the division by 0.
To fix it, replace 1024
with 1024UL
. That will work, because unsigned long
is guaranteed to go up to 4294967295. (Thanks to Pascal Cuoq for explaining it.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With