I2C LCD causes problems

The Serial.begin(115200); is used to initialize and open the serial port. Since this code does not really use serial, that line is unnecessary. I just put that line in all the code that I write, by default, because I almost always use the serial port. The serial port is the best debugging tool that one has when working with the Arduino. Serial.begin() and sprintf() have nothing to do with each other.

Those 2 lines are pretty much equivalent. The 4 in sprintf line is 4 characters for the number and %d is a place holder for an int data type number. In the dtostrf the 4 is minimum 4 characters wide and 0 places after the decimal point, which is, effectively, an integer. The dtostrf() function, like @bperrybap explained in reply #31, is used to format float data types to ASCII text because sprintf() in the AVR processors does not support the float data type (%f). So if you want to convert float data and print decimal places use dtostrf, if you don't want decimal places (integer) you can use sprintf.

Now, if you change the width in the sprintf() function (the 4 or 5) you also must be sure that the buffer that you are writing to (rpmStr) has enough room to hold that width + 1 for the (invisible) terminating null character that terminates all strings. Fortunately, in this case, it does. But if you increase the width to 6 rpmStr will no longer be wide enough and you will write beyond the bounds of the rpmStr array and interesting (usually BAD) things are likely to happen.

1 Like