0

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.

2
  • During debugging, what line are you on in the source code when your debugger displayed that state? Commented Jun 24, 2023 at 14:16
  • at the the end put the breakpoint at ´LOG_INF("end");´ Commented Jun 24, 2023 at 16:14

1 Answer 1

0

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.