Search code examples
c++arduinoarduino-c++

Arduino Reading floating point numbers with sscanf


am trying to read numbers with sscanf() but i have no success with double vars but can read int

example of double

//double var reading not working 
    const char KBuffer[80] = "0x3:2.1:2.1:2.1";

    int rt;
    double p,i,d;
    int n = sscanf(KBuffer, "%x:%lf:%lf:%lf", &rt, &p, &i, &d);

    Serial.println();
    Serial.print("rt "); Serial.print(rt);
    Serial.print(" P ");Serial.print(p);
    Serial.print(" i ");Serial.print(i);
    Serial.print(" d ");Serial.print(d);

// output rt 3 P 0.00 i ovf d 0.00

example of int

// int reading working ok
    const char KBuffer[80] = "0x3:2:2:2";

    int rt;
    int p,i,d;
    int n = sscanf(KBuffer, "%x:%d:%d:%d", &rt, &p, &i, &d);

    Serial.println();
    Serial.print("rt "); Serial.print(rt);
    Serial.print(" P ");Serial.print(p);
    Serial.print(" i ");Serial.print(i);
    Serial.print(" d ");Serial.print(d);
 // output
rt 3 P 2 i 2 i 2 

so any idea what am doing wrong

the same code when i run on c++ online compiler like : https://onlinegdb.com/ryS8zfE3r

am getting correct results


Solution

  • Even if the first conversion goes well arduino scanf will not read the float numbers and printf will not print them as well. scanf and printf family functions do not support float numbers by default.

    the fist problem is easily sortable: int n = sscanf(KBuffer, "0x%x:%d:%d:%d", &rt, &p, &i, &d); the second requires changing the compiler (or linker) oprions by adding -Wl,-u,vfscanf -lscanf_flt -lm But irt will increase the image size by about 15kb.

    Read more in hardware/tools/avr/doc/avr-libc/group__avr__stdio.html in the directory where your board libraries are installed