Strange sprintf problem

Hello,

I wrote a sketch for testing LCD 2004 and 1602 displays and came over a strange problem:

loop()
{
  static unsigned long int varA = 0, varB = 0;
  static char buffer[32];

  ... 

  sprintf(buffer, "A=%ld, B=%ld", varA, varB);
  lcd.setCursor(0, 0);
  lcd.print(buffer);
  ...
}

But the second variable was always 0 on the display. If I changed the last part to:

  sprintf(buffer, "A=%ld", varA),
  lcd.setCursor(0, 0);
  lcd.print(buffer);
  sprintf(buffer, "B=%ld", varB);
  lcd.setCursor(10, 0);
  lcd.print(buffer);

I got the correct output. Both variables are within the range 0 to 100000. Cannot see that the buffer variable is too small or any other reason.

Any explanation?

Test with this code, it works for me...

#include <LiquidCrystal_I2C.h> // https://github.com/fdebrabander/Arduino-LiquidCrystal-I2C-library
LiquidCrystal_I2C lcd(0x3F, 20, 4); // 20 cols, 4 lines at address 0x3F

void setup() {
  Serial.begin(115200);
  lcd.begin();
  lcd.backlight();
}

void loop() {
  static unsigned long int varA = 0, varB = 0;
  static char buffer[32] = "";

  varA = random(0, 100000UL);
  varB = random(0, 100000UL);
  sprintf(buffer, "A=%lu, B=%lu", varA, varB);
  lcd.clear();
  lcd.print(buffer);
  delay(1000);
}

Note I used %lu to denote unsigned long in the sprintf() function

in practice, you'd be better off not using sprintf which takes lots of memory and just do

lcd.setCursor(0, 0);
lcd.print(F("A="));
lcd.print(varA);
lcd.print(F(", B="));
lcd.print(varB);

and not use the buffer at all

(of course need to worry about erasing the line as well or you might get overlapping numbers)

Thanks. that was useful. :slight_smile:

Did you find your issue?

I change my code as suggested (avoiding sprintf). It worked fine.

the easy way ;D
would have been interesting to figure it out though

It would have been interesting to see a complete program as a starting point