If you don’t learn sprintf(), your code will hate you later

preview_player
Показать описание
🤩 FREE Arduino Crash Course 👇👇

Want to learn more? Check out our courses!

We designed this circuit board for beginners!

FOLLOW US ELSEWHERE
---------------------------------------------------

***Get the code, transcript, challenges, etc for this lesson on our website***

SPRINTF() WITH ARDUINO | PRINT MULTIPLE VARIABLES TO THE SERIAL MONITOR
Are you trying to figure out sprintf() with Arduino?

If so, you’re in the right place. In this lesson you’ll learn exactly how to use sprintf().

JUST USING SERIAL.PRINT()
Let’s say you want to print this line of text to the serial monitor:

“The 3 burritos are 147.7 degrees F”

In fact, for every variable you add to the output, you add two more serial prints in the code. What if you wanted to print a line with 4 variables inserted into a string like this:

“The 3 burritos are 147.7 degrees F, weigh 14oz, and were finished 3 minutes ago.”

It would take 9 lines of code!

SPRINTF() TO THE RESCUE
This is where sprintf() comes in handy. We can print out as many variables into our string as we want, and the amount of code required stays at 3 lines.

Here the three lines of code you’ll need:

char buffer[40];
sprintf(buffer, "The %d burritos are %s degrees F", numBurritos, tempStr);
First you need a character array to save the output string into.
Then you need the sprintf() function, which will combine our text and variables into a string.
Let’s take a closer look at each line of code.

char buffer[40];
The character array needs to be as large, or larger than the final output string.
So count the characters you plan to store in that string, and make sure the buffer is at least that large.

The next line of code is the actual sprintf() function. sprintf() stands for “string print format(ted)”.

sprintf(buffer, "The %d burritos are %s degrees F", numBurritos, tempStr);
sprintf() takes a minimum of 2 arguments. The first argument is where you plan to store the string that sprintf() will be making for you. This is where you use the character buffer that you created on the previous line.

show buffer argument in sprintf()
The next argument is the string you want to create, filled in with format specifiers where you want to insert your variables. The format specifier is the % sign. The letter following the format specifier is called the format character, and it tells sprintf() what datatype will be used for that variable.

show the second string argument for sprintf(), with format specifiers labeled
"The 3 burritos are 147.7 degrees F"
In this example we have 2 format specifiers (%) – this means we want 2 variables inserted into the output string. The character specifiers are a little weird at first. They are simply letters that stand for the kind of data type that will be inserted – once you learn what each letter means it starts to make more sense.
Рекомендации по теме
Комментарии
Автор

This is so much clearer than the online Arduino reference that is obviously written by well seasoned programmers and assume that you have solid grasp of the C language.

johnnz
Автор

It is convenient and tidy but keep in mind this method is (a lot) slower than using a bunch of Serial.print commands, as I found out recently when I tried to clean up my new VU meter project code.

ericBcreator
Автор

Everything said in this video is correct. However, a couple of things to bear in mind: sprintf is a LOT slower than Serial.print. Also, sprintf uses a lot of memory. On things like an Arduino Uno, Nano, or ATTINY85 you may struggle. What I do, to keep my code tidy, is write a function to display the things I want to display using Serial.print. You don't save on lines of code, but you can move those pesky Serial.print lines - which tend to clutter up the code - into their own functions. Which is much neater. It's also easier to remove them when you don't need them any more. So, using the burritos example from the video:

void displayBurritosInfo(int numberOfBurritos, float temperature)
{
Serial.print("The temperature of the ");

Serial.print(" is ");
Serial.println(temperature);
}

NotMarkKnopfler
Автор

a good explanation...but thats still cumbersome. I prefer using the "Streaming.h" library. this allows for c++ style prints:

Serial << "hello world, I am " << intVar1 << " years old" << endl;

you can add as many as you like. my test indicated in requires no additional clock cyles to the native print.
"endl" is a new line, if you dont want it, just leave it off.

mtraven
Автор

The sub-specifiers are super handy and there isn't very many good explanations of them. A video detailing them would be super helpful.

jon_raymond
Автор

The best explanation that u ever seen on YouTube. Loved it!!

GaboG
Автор

Cheers Fella,
you are an amazing teacher. Love your channel. I am starting to understand things I thought were beyond my intelect!
Keep 'em coming!

iamsparkicus
Автор

itoa(), and dtostrf(), function detail explain.please

KashifKhan-kwez
Автор

Sir, actually no need to use sprintf rather we can directly use the string concatenation property in serial.print() function

PraveenChintha-jt
Автор

Brilliant! Great info. I have been struggling with why it wouldn't print %.2f for a large majority of the day and now I know :D, thanks. You mention you have another vid explaining 'dtostrf' but I can't seem to find it. Can you point me in the right direction please? Thanks for your time and effort with your videos, they're super clear!

_GB
Автор

please make very detailed videos series on sprintf and sub-specifiers

MN-besx
Автор

Nice explanation just what I hope will work with my microchip pic18f and C language. I'm doing a weather station

susqibi
Автор

Want know how to read from sd card and print on tft display using arduino uno

dalwinderssi
Автор

This is potentially creating a buffer overrun. As it depends on how long the inserted numbers/strings are. When inserting strings you can never make the buffer big enough since you don't know the length of the dynamic strings at compile time.
Meaning you would need to allocate the buffer on the heap wasting already limited heap memory on an arduino.

Also this whole thing is just unnecessary. There is nothing wrong with multiple Serial print statements. In fact it's more efficient.
There are cases where sprintf makes sense to use. But this isn't one.

redcrafterlppa
Автор

great man. Really good explanation.. please do a follow up. Thx

MrShanmunir
Автор

congratulations for the class, very explanatory. I'm doing a project using a panel of leds-dot matrix to print texts read by the SD card. How can I include the temperature value read by a sensor (DB1820), in the text sent by reading the SD card? thank you if you can clarify this doubt for me

DavidRisnik
Автор

Very nicely explained, please continue with the additional functions.

John-qeky
Автор

You have the best Arduino function tutorials. Thank you so much for this content.

steventhehistorian
Автор

thank you sir, very good tutorial. plz make such wonderful tutorial.

vikky
Автор

Is it possible to use this to send multiple variable data to another arduino? If so how would you separate it on that side and plug the data into the correct variable on the recieving arduino?

JPN