Arduino sprintf float not formatting

前端 未结 4 844
离开以前
离开以前 2020-12-02 16:50

I have this arduino sketch,

char temperature[10];
float temp = 10.55;
sprintf(temperature,\"%f F\", temp);
Serial.println(temperature);

tem

4条回答
  •  温柔的废话
    2020-12-02 17:09

    I've struggled for a few hours on getting this right, but I did finally. And this uses modern Espressif C++ provided by Platformio, and my target MCU is an ESP32.

    I wanted to display a prefix label, the float/int value, then the unit, all inline.

    I can't relay on seperate Serial.print() statements, as I am using an OLED display.

    Here's my code example:

      int strLenLight = sizeof("Light ADC: 0000");
      int strLenTemp = sizeof("Temp: 000.0 °C");
      int strLenHumd = sizeof("Humd: 00.0 %");
    
      char displayLight[strLenLight] = "Light ADC: ";
      char displayTemp[strLenTemp] = "Temp: ";
      char displayHumd[strLenHumd] = "Humd: ";
    
      snprintf(strchr(displayLight, '\0'), sizeof(displayLight), "%d", light_value);
      snprintf(strchr(displayTemp, '\0'), sizeof(displayTemp), "%.1f °C", temperature); 
      snprintf(strchr(displayHumd, '\0'), sizeof(displayHumd), "%.1f %%", humidity); 
    
      Serial.println(displayLight);
      Serial.println(displayTemp);
      Serial.println(displayHumd);
    

    Which displays:

    Light ADC: 1777
    Temp: 25.4 °C
    Humd: 55.0 %
    

提交回复
热议问题