Serial monitor usage

I often use a series of Serial.print() function calls, and it's a bit tedious to "build" the line.

I'm sure I've seen a way to combine several elements into one statement, such as ....

  Serial.println(" : Tariff", eeData.tariff_sw+1, " ", tariff, "p/min : Cost £", cost/100);

This throws up a compile error ....

no matching function for call to 'HardwareSerial::println(const char [10], int, const char [2], float&, const char [16], float)'

Have I imagined this is possible?
Have I got the syntax wrong?

Any help appreciated, TIA

The methods available depend on which Arduino you are using. All of them support the use of sprintf() to build a string in a buffer ready for printing but most don't support printing floats so you have to convert them to strings

Which Arduino board are you using and what data types are those in your example ?

I'm using a Wemos D1 mini

uint8_t   eeData.tariff_sw;  // 0-2 : 0=tariff1
float       tariff;  // in p/min
float       cost;   // in p

Thanks Bob

PS, if I have all the items in separate Serial.print() statements it's fine, but I think it looks ugly, just trying to tidy up, so it's not a big deal, but would be nice to know ...

Think I've found my answer in "Related Topics" - separate statements it is then ....

An example. Note that I have deliberately ignored your actual data types for this example


void setup()
{
    Serial.begin(115200);
    char buffer[30];  //space for 29 characters and terminating zero

    int tariff = 12;  //an integer
    float cost = 0.351;
    char costStr[10];  //string to hold the cost
    dtostrf(cost, 4, 2, costStr);

    sprintf(buffer, "Tariff: %d cost: %s\n", tariff, costStr);
    Serial.println(buffer);
}

void loop()
{
}

Using the D1 mini makes things much easier because you can print formatted text directly, including floats


void setup()
{
    Serial.begin(115200);
     int tariff = 12;  //an integer
    float cost = 0.351;
    Serial.println();
    Serial.printf("Tariff: %d cost: %f\n", tariff, cost);
}

void loop()
{
}

See https://cplusplus.com/reference/cstdio/printf/ for the gory details of formatting

I'll read up when I get chance, although I'm trying to avoid having different methods for different boards (I use Nanos as well). Since it'll never be seen by the end user, I'll stick with the separate lines for now.

Thanks for your time ...

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.