float to string in C++ using NRF MCU and Zephyr

598 views Asked by At

I simply want to convert a float to string. Normally this is done using C++ standard library with the command to_string(float). However when I program this on my MCU nrf52840 I got garbage.

This is the code

#include <zephyr/kernel.h>
#include <zephyr/logging/log.h>
#include<float.h>
#include<string>


LOG_MODULE_REGISTER(main);
using namespace std;


int main(void){

float myFloat=3.3;

string str;

str=to_string(myFloat);

char buffer[64];
int ret = snprintf(buffer, sizeof buffer, "%f", myFloat);

if (ret < 0) {
    return EXIT_FAILURE;
}
if (ret >= sizeof buffer) {
    // / Result was truncated - resize the buffer and retry.
}

LOG_INF("end");
}

The project file has the standard C++ library enabled:

CONFIG_LOG=y

CONFIG_STD_CPP20=y
CONFIG_CPP_MAIN=y

CONFIG_CPLUSPLUS=y
CONFIG_LIB_CPLUSPLUS=y

During debugger I got following garbage:

enter image description here

The length is completely wrong and also the value. Trying to do the same task and convert to chars also fails.

Converting integers with to_string works. And logging floats using printk and LOG_INF also works. Therefore, I have to miss something.

1

There are 1 answers

0
Yann On BEST ANSWER

Add CONFIG_NEWLIB_LIBC=y CONFIG_NEWLIB_LIBC_NANO=n to the project config file, even if zephyr tells it is obsolete. It fixes the string error and sprintf error.