What am I missing with printf

Every Serial.println() returns -1.
What have I missed?

float num1 = 0.0;
float num2 = 1.234567;
float num3 = -23.45679;
float num4 = 123.456789;
float num5 = -234.567;
void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  while (!Serial);
  Serial.println(printf( "%+8.5", num1));
  Serial.println(printf( "%+8.5", num2));
  Serial.println(printf( "%+8.5", num3));
  Serial.println(printf( "%+8.5", num4));
  Serial.println(printf( "%+8.5", num5));
}
void loop() {
  // put your main code here, to run repeatedly:
}

What MCU are you using? As far as I know, printf() is not implemented on any genuine Arduino.

Do you actually need it?

What's wrong with the following?

  Serial.println(num1, 5);
  Serial.println(num2, 5);
  Serial.println(num3, 5);
  Serial.println(num4, 5);
  Serial.println(num5, 5);

That does not make sense. printf, if enabled, prints to Serial. So the enclosing println is printing the return value returned by printf, which is the number of characters printf printed. Is that really what you intended?

And your printf format strings are not value, as they do not specify and format. For floating point, the format should be "f". This this instead:

printf( "%8.5f", num1);

Nano

Yes I do. I'm outputting a latitude and longitude and I need leading + and other formatting.

On the Arduino Nano, use Serial.print(), or dtostrf() then Serial.print().

Floating point format is by default not implemented for s(n)printf() on the Arduino Nano.

OK, I see where you're coming from. I'll have to rethink it. Ta

Would Libprintf.h work on a Nano?

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