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

  Переглядів 48,449

Programming Electronics Academy

Programming Electronics Academy

2 роки тому

🤩 Check out this Free Arduino Course 👇
bit.ly/get_Arduino_skills
Want to learn more? Check out our courses!
bit.ly/2SMqxWC
We designed this circuit board for beginners!
Kit-On-A-Shield: amzn.to/3lfWClU
SHOP OUR FAVORITE STUFF! (affiliate links)
---------------------------------------------------
Get your Free Trial of Altium PCB design Software
www.altium.com/yt/programming...
We use Rev Captions for our subtitles
bit.ly/39trLeB
Arduino UNO R3:
Amazon: amzn.to/37eP4ra
Newegg: bit.ly/3fahas8
Budget Arduino Kits:
Amazon:amzn.to/3C0VqsH
Newegg:bit.ly/3j4tISX
Multimeter Options:
Amazon: amzn.to/3rRo3E0
Newegg: bit.ly/3rJoekA
Helping Hands:
Amazon: amzn.to/3C8IYXZ
Newegg: bit.ly/3fb03X1
Soldering Stations:
Amazon: amzn.to/2VawmP4
Newegg: bit.ly/3BZ6oio
AFFILIATES & REFERRALS
---------------------------------------------------
►Audible Plus Free trial: amzn.to/3j5IGrV
►Join Honey- Save Money bit.ly/3xmj7rH
►Download Glasswire for Free:bit.ly/3iv1fql
►Download Glasswire for Free:bit.ly/3iv1fql
FOLLOW US ELSEWHERE
---------------------------------------------------
Facebook: / programmingelectronics...
Twitter: / progelecacademy
Website: www.programmingelectronics.com/
**Get the code, transcript, challenges, etc for this lesson on our website**
bit.ly/2Ra5zAy
SPRINTF() WITH ARDUINO | PRINT MULTIPLE VARIABLES TO THE SERIAL MONITOR
Are you trying to figure out sprintf() with Arduino?
Or maybe you want to display multiple variables on the serial monitor without having to use a bunch of separate Serial.print() statements.
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”
Where the number of burritos and the temperature value are both variables. Using Serial.print() would take 5 lines of code to print out just this single line of text.
Serial.print("The ");
Serial.print(numBurritos);
Serial.print(" burritos are ");
Serial.print(tempStr);
Serial.println(" 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);
Serial.println(buffer);
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.
Finally, you use Serial.print() to display the formatted 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.

КОМЕНТАРІ: 93
@ericBcreator
@ericBcreator Рік тому
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.
@kriscurkovic9265
@kriscurkovic9265 3 місяці тому
Yeah arrays in general are always quite slow. You have to create 40 bytes on the stack now, then sprintf the new string characters into each slot. If you deconstruct everything into machine instructions it comes out as a lot more processor cycles. Streaming bits onto the serial isn't that computationally heavy.
@jon_raymond
@jon_raymond 2 роки тому
The sub-specifiers are super handy and there isn't very many good explanations of them. A video detailing them would be super helpful.
@programmingelectronics
@programmingelectronics 2 роки тому
Thanks for this Jon!
@NotMarkKnopfler
@NotMarkKnopfler 11 місяців тому
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(numberOfBurritos); Serial.print(" is "); Serial.println(temperature); }
@shadamethyst1258
@shadamethyst1258 11 місяців тому
Also note that using sprintf is *very strongly* discouraged on non-embedded platforms, because of the risk of overflowing the buffer. The examples in the video could trivially be weaponized if the user had control on the `tempStr` variable
@mtraven23
@mtraven23 Рік тому
a good explanation...but thats still cumbersome. I prefer using the "Streaming.h" library. this allows for c++ style prints: Serial
@programmingelectronics
@programmingelectronics Рік тому
Thanks for adding this Matt! I'll definitely check it out - I do wish the native Serial library just "made it easy" with out having to use the String class. If I could just do... Serial.print("I would like " + numTacos + " please"); Would that be great or what!
@iamsparkicus
@iamsparkicus 2 роки тому
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!
@programmingelectronics
@programmingelectronics 2 роки тому
Thanks for watching!
@KashifKhan-kw3ez
@KashifKhan-kw3ez 2 роки тому
itoa(), and dtostrf(), function detail explain.please
@programmingelectronics
@programmingelectronics 2 роки тому
Thanks for the recommendation and thanks for watching!
@_GB84
@_GB84 2 роки тому
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!
@GaboG85
@GaboG85 3 місяці тому
The best explanation that u ever seen on UKposts. Loved it!!
@programmingelectronics
@programmingelectronics 3 місяці тому
Thanks!
@alejandrom72
@alejandrom72 2 роки тому
Nicely explained. Thank you.
@programmingelectronics
@programmingelectronics 2 роки тому
Glad you liked it! Thanks so much for the note and for watching!
@MN-be7sx
@MN-be7sx 2 роки тому
please make very detailed videos series on sprintf and sub-specifiers
@DavidRisnik
@DavidRisnik Рік тому
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
@sombatmuenphan1555
@sombatmuenphan1555 2 роки тому
Many thank.Excellent explain.
@programmingelectronics
@programmingelectronics 2 роки тому
Thanks so much for watching!
@vikky452
@vikky452 2 роки тому
thank you sir, very good tutorial. plz make such wonderful tutorial.
@programmingelectronics
@programmingelectronics 2 роки тому
Glad it helped!
@fernandosimonetti6595
@fernandosimonetti6595 Рік тому
Excelente explicación! Muchas gracias!!!
@programmingelectronics
@programmingelectronics Рік тому
Thank you!
@rossli8621
@rossli8621 Рік тому
Very nice video!!!
@programmingelectronics
@programmingelectronics Рік тому
Thank you Ross!
@JPN76
@JPN76 2 роки тому
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?
@redcrafterlppa303
@redcrafterlppa303 11 місяців тому
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.
@banditboy6444
@banditboy6444 2 роки тому
As always, great vid
@programmingelectronics
@programmingelectronics 2 роки тому
Appreciate that!
@MrShanmunir
@MrShanmunir 2 роки тому
great man. Really good explanation.. please do a follow up. Thx
@programmingelectronics
@programmingelectronics 2 роки тому
Thanks for the note!
@ED99LAM
@ED99LAM Рік тому
very useful n informative
@programmingelectronics
@programmingelectronics Рік тому
Thanks!
@John-qe3ky
@John-qe3ky 2 роки тому
Very nicely explained, please continue with the additional functions.
@programmingelectronics
@programmingelectronics 2 роки тому
Thank you!
@joshuapitong899
@joshuapitong899 Рік тому
Really great.✔️ Thanks.🙌
@programmingelectronics
@programmingelectronics Рік тому
Thanks!
@giorgito3313
@giorgito3313 Рік тому
Excellent!!
@programmingelectronics
@programmingelectronics Рік тому
Thanks so much! I hope it helped.
@user-su5sq5ib3i
@user-su5sq5ib3i 2 роки тому
Nice explanation just what I hope will work with my microchip pic18f and C language. I'm doing a weather station
@programmingelectronics
@programmingelectronics 2 роки тому
Thanks - best of luck in your project!
@user-su5sq5ib3i
@user-su5sq5ib3i 2 роки тому
@@programmingelectronics just wanted to give you an update this piece of code that I wrote worked perfect thanks again
@programmingelectronics
@programmingelectronics 2 роки тому
@@user-su5sq5ib3i So glad it helped!
@dalwinderssi4094
@dalwinderssi4094 2 роки тому
Yes , I want to buy ,lessions
@ingenierocristian
@ingenierocristian 2 роки тому
Love it, thanks
@programmingelectronics
@programmingelectronics 2 роки тому
Thank you!
@bobowen7861
@bobowen7861 2 роки тому
Very excellent tutorial. You made this simple. Would be very interested in seeing an additional tutorial on using optional sub-specifiers.
@programmingelectronics
@programmingelectronics 2 роки тому
Thanks!
@markadyash
@markadyash 2 роки тому
thanks lot helpful
@programmingelectronics
@programmingelectronics 2 роки тому
Thanks for the note! Glad it helped!
@steventhehistorian
@steventhehistorian 2 роки тому
You have the best Arduino function tutorials. Thank you so much for this content.
@programmingelectronics
@programmingelectronics 2 роки тому
Thanks so much Steven!
@12DGJB21
@12DGJB21 Рік тому
Thank you, sprintf looks very useful. Would there be any benefit of using sprintf over the following single line command to print a simple string of text with a variable (i)? For example: Serial.println((String)"Relay"+(i+1)+" OFF"); Where the variable i is a numerical value starting at 0.
@yo90bosses
@yo90bosses 11 місяців тому
I know that comment is old but Ill go ahead and reply. Using the string class is never a good idea, in short it has issues due to dynamic memory on memory constrained systems like arduino unos etc. Go ahead and search for "Why not to use string in arduino". Many good videos.
@christiaansteyn4088
@christiaansteyn4088 Рік тому
Please do the additional tutorials
@TOMTOM-nh3nl
@TOMTOM-nh3nl 2 роки тому
Thank You
@programmingelectronics
@programmingelectronics 2 роки тому
Thanks for watching!
@dalwinderssi4094
@dalwinderssi4094 2 роки тому
Want know how to read from sd card and print on tft display using arduino uno
@programmingelectronics
@programmingelectronics 2 роки тому
Thanks for the recommendation!
@yugalkishor3131
@yugalkishor3131 2 роки тому
Superb
@programmingelectronics
@programmingelectronics 2 роки тому
Thanks!
@berndeckenfels
@berndeckenfels 11 місяців тому
The function is called snprintf
@electronics5449
@electronics5449 2 роки тому
Awesome
@programmingelectronics
@programmingelectronics 2 роки тому
Thanks for watching!
@bibel2k
@bibel2k 2 роки тому
I'm ‏speechless! One of the most annoying things on arduino is to print a long message like you have shown. Mind blowing!
@chrisspencer6502
@chrisspencer6502 2 роки тому
I got caught out by the same thing in Matlab
@Clip7heApex
@Clip7heApex 2 роки тому
Would this work for LCD print?
@programmingelectronics
@programmingelectronics 2 роки тому
I believe LCD print just takes in a string, so that should work. Best of luck!
@user-yg4nl2tf4z
@user-yg4nl2tf4z 2 роки тому
thanks. I dont found a good explanation of this function in Russia UKposts. Good reason to learn English)
@programmingelectronics
@programmingelectronics 2 роки тому
Glad it was helpful!
@ElIngLopez
@ElIngLopez 2 роки тому
Great! ... I'd like to print the % sign, how i do this?
@mtraven23
@mtraven23 Рік тому
Serial.print("%")
@berndeckenfels
@berndeckenfels 11 місяців тому
Inside printf with "%%"
@thunderbolt997
@thunderbolt997 2 роки тому
super!
@programmingelectronics
@programmingelectronics 2 роки тому
Thanks for watching!
@lesatkins42
@lesatkins42 3 місяці тому
or you could use Serial.printf(" .... ", var1, var2, ... varn);
@jslonisch
@jslonisch Рік тому
Isn’t it easier just to do it all in one line with Serial.println(String(variable1 + variable2 + ...)). No messing around with a buffer or worrying about if you got the right character specifier to suit your variable.
@programmingelectronics
@programmingelectronics Рік тому
Yes, it is way easier using the built in String class... www.arduino.cc/reference/en/language/variables/data-types/stringobject/ There is a fun "controversy" to read up about on whether to use/avoid the String class with Arduino... forum.arduino.cc/t/optimizing-memory-without-strings/341158 I guess I landed on the not side of this but probably not for the right reasons though... A mentor programmer of mine told me to avoid them, so I just took his word for it! I should probably do some more of my own research :)
@berndeckenfels
@berndeckenfels 11 місяців тому
This will however be slow as heck as it allocates the string buffer multiple times with the potential to fail at runtime, not good for embedded projects where you need speed and reliability. Much better with a static or stack allocated buffer.
@jason_man
@jason_man 3 місяці тому
just use String() and + this point
@DodgyBrothersEngineering
@DodgyBrothersEngineering 2 роки тому
This video would have come in real handy just the other day, but better late than never... Would have been nice if you covered the use of the \ as in \"%s\".
@programmingelectronics
@programmingelectronics 2 роки тому
Thanks for the note! Great points!
@xroppa5290
@xroppa5290 2 роки тому
Top
@crissd8283
@crissd8283 11 місяців тому
This seems inefficient. While the first example may have more lines of code, the second code certainly uses more resources. Using a character array requires the same data to be stored twice. Once in the program and variables and a second time in the character array. Then you are spending time sending that data into that memory location then sending that new memory location to print(). The first example is certainly faster and more efficient. I understand that neat looking code is desired but the second example is harder to understand and less efficient. Seems like a bad idea.
@semibiotic
@semibiotic Рік тому
It should be snprintf().
@livetohash6152
@livetohash6152 12 днів тому
Can we use $"The taco is {tempTaco} degrees" ?
Arduino Sketch with millis() instead of delay()
14:27
Programming Electronics Academy
Переглядів 220 тис.
#227 ✨printf for Arduino✨(and ESP32, ESP8266) easy, formatted output
23:02
1 класс vs 11 класс (рисунок)
00:37
БЕРТ
Переглядів 2,6 млн
Using Serial.parseInt() with Arduino
15:39
Programming Electronics Academy
Переглядів 44 тис.
Arduino MASTERCLASS | Full Programming Workshop in 90 Minutes!
1:25:31
Programming Electronics Academy
Переглядів 2,2 млн
#224 🛑 STOP using Serial.print in your Arduino code! THIS is better.
26:39
Using Serial.read() with Arduino | Part 1
10:30
Programming Electronics Academy
Переглядів 124 тис.
Using Arrays with For Loops
17:24
Programming Electronics Academy
Переглядів 29 тис.
What is the ? code!?  Learn about the ternary operator!
12:30
Programming Electronics Academy
Переглядів 12 тис.
Which Arduino IDE should I use?
13:43
Programming Electronics Academy
Переглядів 82 тис.
Top Fifteen Mistakes People Make When Designing Prototype PCBs
12:26
Cosplay Light and Sound
Переглядів 119 тис.
String In Char Array VS. Pointer To String Literal | C Programming Tutorial
9:58