-
-
Notifications
You must be signed in to change notification settings - Fork 4
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Bug: Unexpected values when using Arduino Leonardo #3
Comments
Just tried the same code on a ESP32. This resulted in the expected outcome:
truncated for readability |
Hi Satoer, The explanation is probably quite simple, the size of an int is 16 bit on a Leonardo and 32 bit on an ESP32 you can verify my hypothesis with the sketch below. void setup()
{
Serial.begin(115200);
Serial.println(sizeof(int));
}
void loop()
{} Solution for your sketch #include "MultiMap.h"
int32 In[] = { 0 , 512};
int32 Out[] = { 0 , 255};
void setup() {
Serial.begin(9600);
}
void loop() {
for (int i = 0; i <= 512; i++) {
int mapValue = multiMap<int32>(i, In, Out, 2); // <<<<<<<<<<< make it explicit 32 bits integers.
Serial.println(String(i) + ": " + String (mapValue));
}
delay(10000);
} |
We can try to check the input value of 129 (which was the first to fail int In[] = { 0 , 512}; As there is only one segment, the output = outmin + (input * (outmax - outmin)) / (inmax - in min) output = 0 + (129 * ( 255 - 0)) / (512- 0) 32895 flips to - (65535 - 32685) = -32640 output = -32640 /512 So always check intermediate math results if unexpected values pop up (even when most look OK). |
First code had output: 2 Second code received an error: Changed every 'int32' to 'long' and it fixed the problem! The outcome is as suspected. Thank you, this was driving me crazy. |
should been long is 32 bit on Leonardo and I expect too on ESP. These 'intermediate overflows' happen sometimes when porting code or when mixing unsigned and signed math. |
Similar things can happen when e.g. a time variable overflows, most famous is millis() after some 49.7 days. or micros() after ~70 minutes. If you math is not prepared to handle the overflows correctly strange values may pop up. Recently I read about a bug that occurred every ~25 days, which was almost in sync with the moon cycle so people were quite amazed. In the end it was a mix of millis() overflow combined with signed/unsigned math mixture. |
Thanks Rob, You've been really helpful, and got my program working. Didn't suspected a overflow because the values are well below a 16 bit integer. I didn't took intermediate results in consideration though. |
I don't get it. Used Multimap several times before with great success, but now with an Arduino Leonardo I get unexpected results.
I've made an example to the bear minimum:
And this is the result:
Any idea why the output does not met the expectation?
added cpp in the code block markup for syntax highlighting
The text was updated successfully, but these errors were encountered: