lancaster-university / codal-microbit-v2

CODAL target for the micro:bit v2.x series of devices
MIT License
43 stars 52 forks source link

`uBit.serial.printf(%d)` with float value triggers wrong output for other arguments #341

Open microbit-carlos opened 1 year ago

microbit-carlos commented 1 year ago

Floats are not supported in uBit.serial.printf(): https://github.com/lancaster-university/codal-core/blob/master/source/driver-models/Serial.cpp#L393-L473

If we accidentally try to print a float as an integer uBit.serial.printf("%d\n", 1.234); that serial output printed is an integer interpretation of the value, and that's expected đź‘Ť.

However, if there are more arguments, it affects their conversion as well and produces erroneous data. In this example, the second %d of the second printf produces 1072938614 instead of 1:

#include "MicroBit.h"

MicroBit uBit;

int main() {
    uBit.init();

    while (true) {
        uBit.serial.printf("%d, %d\n", 1, 1.234);    // <- the first value, an integer is converted correctly
        uBit.serial.printf("%d, %d\n\n", 1.234, 1);  // <- the second value, same integer, gets converted incorrectly
        uBit.sleep(10);
    }
}

The float-as-an-int conversion is also inconsistent, but it only happens sometimes, it's hard to catch. A small extract of the output of this example:

1, 0
-927712936, 1072938614

1, 16380
-927712936, 1072938614

1, 0
-927712936, 1072938614

1, 16380
-927712936, 1072938614

1, 0
-927712936, 1072938614

MICROBIT.hex.zip