Hi, the function abs has an unexpected behavior when work with uint32_t. Run example:
void setup() {
Serial.begin(9600);
uint32_t oldTs = 100;
uint32_t newTs = 50;
int32_t diffTs = abs(newTs - oldTs);
Serial.print("La diferencia es: ");
Serial.println(diffTs);
diffTs = abs(diffTs);
Serial.print("La diferencia es: ");
Serial.println(diffTs);
}
void loop() {
// put your main code here, to run repeatedly:
delay(10);
}
The output is:
La diferencia es: -50
La diferencia es: 50
pert
#2
abs() is working fine, the unexpected value results from your conversion from uint32_t to int32_t.
This should make things clear:
void setup() {
Serial.begin(9600);
uint32_t oldTs = 100;
uint32_t newTs = 50;
uint32_t diffTs = abs(newTs - oldTs);
Serial.print("La diferencia (uint32_t) es: ");
Serial.println(diffTs);
Serial.print("La diferencia (int32_t) es: ");
Serial.println((int32_t)diffTs);
diffTs = abs(diffTs);
Serial.print("La diferencia es: ");
Serial.println(diffTs);
}
void loop() {
// put your main code here, to run repeatedly:
delay(10);
}
noiasca
#3
Notes and Warnings
Because of the way the abs() function is implemented, avoid using other functions inside the brackets, it may lead to incorrect results.
source abs() - Arduino Reference
Koepel
#4
The abs() function is a standard (abs - C++ Reference) and it is in the compiler. So everything should be fine.
Then Arduino destroys the standard by adding a abs() macro for no good reason.
They don't want to fix this mistake because the wrong use of abs() might be used in a library.
The same for round(): round() macro in Arduino.h · Issue #76 · arduino/ArduinoCore-API · GitHub.
By the way, pert is right. You should make it signed before calling abs().