0

I don't understand why the formatted string is displaying ?? instead of float values. My code:

#include <Arduino.h>
#include <Wire.h>
#include "SparkFunCCS811.h"
#include <DFRobot_SHT3x.h>

DFRobot_SHT3x sht3x(&Wire, /*address=*/0x44, /*RST=*/4);

//* Get SHT31 readings

void readSHT(float &temp, float &humid)
{

    DFRobot_SHT3x::sRHAndTemp_t data = sht3x.readTemperatureAndHumidity(sht3x.eRepeatability_High);

    char shtVal[50];

    if (data.ERR == 0)
    {
        temp = data.TemperatureC;
        humid = data.Humidity;

        Serial.println(data.TemperatureC);
        Serial.println(data.Humidity);
    }

    snprintf(shtVal, 50, "Temp = %f  Humidity = %f", temp, humid);
    Serial.println(shtVal);
}

void setup()
{

    Serial.begin(115200);

    //*Initialize the chip
    while (sht3x.begin() != 0)
    {
        Serial.println("SHT31 Initialization Failed");
        delay(1000);

        Serial.print("Chip serial number");
        Serial.println(sht3x.readSerialNumber());

        if (!sht3x.softReset())
        {

            Serial.println("Failed to Initialize the chip....");
        }
    }
}

void loop()
{

    unsigned long newTime = millis();
    static unsigned long oldTime = 0;

    if (newTime - oldTime >= 5000)
    {

        float temp = 0.0;
        float humid = 0.0;

        oldTime = newTime;

        readSHT(temp, humid);
    }
}

& here is the output: Here is what I get as output:

21.23
41.06
Temp = ?  Humidity = ?

The function readSHT()has no problem displaying the actual values but why the formatted string shows ???. Am I doing something wrong?

1 Answer 1

0

The standard avr-libc does not have float support enabled in the printf family of functions. This is because float support would bloat your code massively, and most people don't need it.

It is possible to enable it through some black magic (I don't know what, but someone else may), but in general you don't want to since there are better ways.

Typically you would use dtostrf() to format your float into a char array separately. Or if all you are doing is printing to serial then you wouldn't even format it into a string in the first place.

Serial.print(F("Temp = "));
Serial.print(temp);
Serial.print(F("  Humidity = "));
Serial.println(humid);
1
  • Ah Ok. I will use dtostrf () as I need to pass these values to another function as well. This way I can store the value with suitable no. of decimal places.
    – Zaffresky
    Dec 28, 2020 at 14:35

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.