How to convert a string from the serial input in float ?

27 Nov 2016

hello guys,

my program reads via an interrupt a string, which contains a float number. Then I convert it and save it into a float variable. The problem is that this happens only once and then the float does not change any more. How can I change this?

I think it has something to do with the atof() function!?

Code

#include "mbed.h"
#include <string>
#include <cstdlib>

Serial pc(SERIAL_TX, SERIAL_RX);

DigitalOut myled(LED1);

char a;
std::string b;
std::string str;
float in_freq1;
char * c;
const char * d;

void callback() {
    myled = !myled;
    //b.clear(); //if i put this to my code, the float variable will change but display only whole numbers note float numbers
    int i = 0;
    while(pc.readable()) {
    a = pc.getc();
    b += a;
    i++;
    }
    d = b.c_str();
    in_freq1 = atof(d); 
    }

int main() {
    pc.attach(&callback);
    
    int i = 1;
    pc.printf("Hello World !\n");
    while(1) {
        wait(1);
        pc.printf("Float: %f\n", in_freq1);
    }
}
27 Nov 2016

Hi David,

I don't have the means to quickly test my theory - if you apply the "volatile" keyword to the float, does that help?

27 Nov 2016

thanks for the reply. it helps kind of. but it attaches the next float variable to the string like this: first iteration: String:1.377551 second iteration String:1.377551-0.765306

Is there a possibility to clear the string before insert the new value to it? b.clear(); doesn't work

27 Nov 2016

b.clear(); or b=""; only work if i put it in the while loop, how can i manage to get it in the interrupt routine?