#224 🛑 STOP using Serial.print in your Arduino code! THIS is better.

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
and welcome back now the title of this video as you can see is a plea to stop leaving your serial.print statement scattered about your code because it's just not good for the code why well first of all let's think about it a serial.print statement that you're using for debugging it's data coming out the serial port right basically the tx pin on your arduino whatever microcontroller you're using normally as in this case coming down the usb port right so you can debug it nice and easily or if you're using one of these sort of ftdi type things those two wires go to ground and the tx pin directly on your chip same thing right and i do that all the time in my things but serial.print statements yeah what's so bad about them i want to have a quick shout out for pcbway sponsors for this video now as well as giving you 10 pieces of pcb for five dollars and assembly options and all sorts of different things like custom parts i want you to look at the top of this web page here look you can see there's the pcb way fourth annual pcb design contest let's see what that's about now this page contains everything you need to know about the pcb design contest from pcb way if you think you've got a pcb and a project that's worthy of attention look at the overview on here you can watch the video and it gives you all the information you need remember though the timeline is from august 2021 to november the last day in november 2021 so get your skates on this year the themes are iot robotics and whatever theme you think you might fall into if those two don't meet your needs and of course the competition has some rules here they are all specified for you don't forget to read them before you submit now the prizes are definitely worth having as you can see here first prize fifteen hundred dollars in cash plus 200 dollars worth of coupons and you can see the second and third prizes and in fact there's even more if we scroll down a little bit more there are various other prizes available for those who have submitted the project now here are some of the entries for the iot theme and as you can see there's a robotic theme people have submitted stuff and whatever topic you think your project might drop into if it's not one of these two and believe me even if you're not going to submit something yourself you should really go and have a look at this some of these projects are outstanding so don't forget have a look at the pcb way fourth pcb design contest and at the same time look at their wonderful pcb way website where you can get ten pieces for five dollars well worth looking at but serial.print statements yeah what's so bad about them then well first of all let's think about this you need serial.print statements what's that not me you're not using them well to debug a program to find out where you are and what you're doing at any stage put in serial.print statements the trouble is you put a few in you go okay got that but that bit there isn't quite working i'll just put another couple around that to find out why this value isn't quite what i expected it to be and before you know it you've got 50 serial.print status in and then finally the eureka moment arrives yay my program works great switch it all off put in a box ta-da except that's the problem as i found out during my esp32 web radio project you start leaving zero.print status everywhere and there's two things that happen one the program is bloated significantly so in some cases okay because all those serial.print statements take up room don't they or first of all if you just use serial.print string that's your sram that's your runtime memory that it's using for that now yes you can put the the f macro in front of that to put it into program memory but then you're using up program memory aren't you as well so in a big processor like the sp 32 lots of memory not a big deal one way or the other really little tiny processor like this though you know you only got 2k memory there easy to fill up you really don't want that cluttering up your memory what at run time or indeed at storage time and secondly all those serial.print statements take time significantly so in some cases going back to my esp32 web radio project even outputting at 115 200 bits per second it slowed down the processing enough so that i was getting terrible terrible jitter on that radio you couldn't really quite hear it properly anymore and that's with a fast process or anything else because at the end of the day your uart that's your universal asynchronous received transmitter that's built into here as part of like a c8 340 g or um an ftdi something like that that transmits all this stuff it's relatively slow compared to what your processor is well not just relatively slow it's hugely slow and that takes time so if you've got your program now working that eureka moment's arriving and you just leave all those serial.print line statements in there it means not only have you bloated the program significantly secondly you're slowing it down now forever more because every time it hits that serial.print it chucks it over the wall to the uart and go here i've got this debugging statement for you except that you're no longer interested in it it just takes forever and it slows the whole thing down so what can we do about it well there's a couple of things i'll come on to the most sophisticated solution which i'll put at the end of the video because it's i don't think it's really suitable to be quite honest for something like a little tiny arduino yeah you can try it out by all means and for smaller programs it might work just great but we are limited to our memory aren't we on that we know so it might not be the best solution but you can have a look if you look see this bar that's running across the bottom of your video if you put your mouse on the video that's split up into various chapters now and each chapter has got a title and right at the end probably around about this position i'll put the solution that i'm using on my esp32 web radio um and it's it's a full-blown library not written by me by any means though and it's it does everything you'd ever want from a sort of debugging monitoring type solution but i'm looking more focusing at things like arduino simple things that we can do even if you only take the very first suggestion that i'm going to propose you'll save yourself program space and program speed okay now obviously i'm going to put a really silly program on here something really simple just to sort of emulate what you might do in real life of course we're probably looking at something like this you know a real project that's running all various bits on it much more complex and you know one part of it isn't working quite the way you want and you're trying to debug it so okay in real life it's like this for the demo we're gonna use this okay let's let's cobble together a simple program that can illustrate this right here we are then so this is a do nothing program but it illustrates the point okay now if we have a look at this code forget the fact this isn't written in the arduino ide it works just the same exactly the same in case you're interested this is platform io basically visual studio code with platform io added onto that and very good is too but i'm not going into that right so this is a noddy program right here we've defined a little function that just adds one to the value you've given to it and it's got various serial.print stamp isn't it just the sort of thing you would have if this were a real program so you you're saying oh i've received this and i'm now coming back out of this routine here's your setup and it says yeah i've done my setup and it's complete incidentally as an aside i would always recommend you put a serial.print in your setup because otherwise you might not realize that there's something in the setup that's causing a problem i've had that before where you're trying to set up spi um where you say go and it just hangs it's waiting for something in the deep dark bowels of spi code and it never comes back and you think what's going on why isn't my code running well never mind your code running it hasn't even got out of setup yet so i always put one at the end of the setup just to say yeah i'm running but we'll come on to how we can change this to make it more efficient and then of course we have a loop here and all this loop is doing is saying look i've got a counter here i'm adding one to it by calling this routine at the top and coming back again and then delaying for five seconds emulating some other processing that's going on but as you can see it's liberally scattered with serial.print and serial.print line statements okay brilliant pretty typical i'd say and i do this all the time except i've moved away from serial.print now and turned it into something else because i don't like leaving all these serial.preference statements in there okay what's that commenting them out comment oh i see yes i see what you mean you can comment them out of course you can yes i mean to get rid of you know that serial that's that serial principle i mean you can just put two two hashes in front now okay won't be compiled it's just a comment now the end surely and then you discover you know 10 minutes down the line oh i need these comments back again now because i've done something else and you have to go through and uncomment them come on human nature being what it is you get to the point you think i can't be bothered anymore i'm just leave them in there done yeah and that's the problem isn't it which if you could do it with just one line isn't that so much better and just before we do that let's just see this running so you see the actual debugging lines coming out which is no magic at all just just works so i'll bring up the cool term window because i like using that there is blank it's not connected yet so if we connect it will restart that arduino because i've got it set to do that there we go there we are right so that is now a typical sort of output that you might get from you know your serial prints it just does this now there's a few things not quite right with this is it one is that um you can't really tell at what point anything's been returned here you know it's just a whole list of things now cool term will allow you to put date and time on the front which i use all the time so that if you're monitoring something long term and something comes out you know 10 minutes time you can come back to this window and go ah there it is that's that thing that happened at 10 minutes ago when i tried to receive the temperature say from an outside sensor yes a very topical topic for me okay anyway but apart from that yeah this is all pretty much what it's doing isn't it yeah okay nothing special now let's go and change this code here to something that does it differently now what i've done here is changed all the serial.print and serial.printlines name is to debug and debug line now needless to say as that little pop-up has just proven to you it goes what on earth are you doing ralph what is debug line what is debug i've no idea what that is i'm not gonna compile it quite right too but with the um simple addition of a define line which you've used many times i would imagine we can we can make this work can't we we can make this work so it requires a small understanding of what define does let's get rid of that comment up there we can use that space so if we put in hash define now normally you might say something like hash define led pin 13 right so you've defined a meaningful name like led pin and you've given it a textual substitution value of 1 3 13. so if we were to do that led pin 13 you must have done this before it's probably in the examples that even arduino give you you're using a meaningful name here and what it represents is this here now what the processor does is say right you've asked me to compile this code i'm going to look for all these textual substitutions that you put in with the use of define so wherever i see the letters l-e-d-p-i-n which is just a little string to it means nothing to it it goes i will substitute that verbatim with whatever you've typed after it one three so no semicolon don't need that it isn't code we're doing here this is textual substitution so whiz through the code and substitute wherever you've you've put led pin with one three behind the scenes the very thing you as a developer or coder are not supposed to do you're not supposed to use magic numbers like 1 3 what does 1 3 mean what does 48 mean 42 well all right 42 means the meaning of life universe and everything but apart from that one number magic numbers have no meanings right and in a in a commercial environment you just would not be allowed to use these magic numbers you must use a meaningful name so somebody reading a digital write would see led pin and goes ah you're writing to the led pin not digital right 13 comma high and you go what's that doing then what's 13 is that some special thing i should be aware of okay so that's fine and i'm sure we're all using that and have used it in the past to find but we can go a step further than that if we can substitute text like 1 3 for led pin why can't we substitute other text for other things so what i'm proposing is this right so if we look at these two lines at the top here we've defined a debug and a debug line with a parameter we say brackets x which is like a placeholder for a parameter and we say i want to change debug x into serial print x and ditto debug line as a serial print line x whatever is the whatever's in those brackets and the preprocessor doesn't care it goes well whatever you've typed in those brackets quotes some character characters end quotes it doesn't even know that that is a string as such right it just takes the entire contents and wraps it in there so now if we hover over debug received value look at that it says define debug serial.print expands to serial.print received value amazing what's that so what have you achieved here what have we achieved well actually we've achieved nothing so far because instead of writing serial.print receive value we're writing debug receive value but it's still coming out all the time isn't it we haven't actually got to the number the problem of being able to switch this on and off at a stroke but that's very easy what we can do is put an if condition above this now this is not a c plus if this is a pre-processor if so let's have a look how that might look so here we are then the first thing we do is define whether or not we want debugging on i mean have you finished your your sketch now and it's all done and dusted you want to put it around the cupboard in which case you can say define debug and you can change that one to a zero and it'll switch everything off but let's keep it at one at the moment because you're developing and you want to see what happens so what we've now said is hash yeah so preprocessor derivative if debug equals one which is so therefore it will do the next two statements which are these two here the two we've just seen great now yeah i know you're ahead of me so by changing this to something else but we'll make it zero because that's logical for us isn't it so we're saying debug zero now so this statement here if debug equals one did you see those two statements they're dim that's because they're no longer going to be compiled the compiler said that statement here is false therefore until i hit an end if i'm not going to even look at that code so it it pretends that these two lines are not even in there does that mean then all the debug statements now are not going to come out not yet we need another couple of lines yet because look what's happened the compiler now has gone squiggly under debug it goes i don't know what you mean by debug we're back to the old problem we had a few minutes ago because we haven't defined it the compiler doesn't know what to do with this and all we need is to put an else in watch this so what i've done is added in this hash preprocessor directive remember hash else define debug x which is what we're putting down here debug with something in brackets as well well nothing nothing at all we've said defined debug x is nothing ditto for debug lion x nothing but i'll keep saying x you can put anything you like in there it's a placeholder for a variable you can have a b c whatever you want we'll stick to x now the compiler has said okay the squiggles are gone now so what exactly is debug doing now so it says define debug x and nothingness so when we compile this now this statement will not be there because the preprocessor will come down and go oh look i've got a name to to expand upon and do some textual substitution wherever i find debug with a parameter in it i'm going to substitute um nothingness so come down here finds debug bracket something in the middle there and substitute nothing that statement effectively disappears will not get compiled and because we've done it all at the top here with and it's all controlled by that one statement up here all these debug statements will suddenly not be compiled i don't believe you what you don't believe me okay let's have some proof then okay let's compile this little tiny program both with debugging on and turning it off and just see what the program size is and how much space we've taken up in the sram yeah so i'll um expand this window here so we can see what's going on a little bit right so i'm going to compile this yes all right this isn't the way i'm going to compile it for the arduino but it's pretty much the same we've got the old things down here yeah so first of all let's switch debugging back on by setting the debug variable that you'd have to do in your program somewhere on one which means these two lines see that just become highlighted again it's going to yes it says i'll compile those in now i'll make sure that the debug does expand to serial.print yeah so let's compile that and see how big is so there it is so it's saying i've compiled it yeah amazing arno uh and we've used so ram which is basically sram your runtime memory is 11.7 so it's using 240 bytes and the flash memory where your program resides is 6.1 percent and it's using 1966 bytes hmm okay that's one thing so if we go back to the top here and say now i do not want debugging on i've finished my program i did not want all this serial stuff coming out the uart slowing everything down and increasing the program size so we'll turn it off and we'll just recompile it and compare the two let me make this window even bigger so that we can actually compare the two outputs right let's compile and see what it says we'll come back to that in a minute now it says we're using nine percent of ram 184 what did the previous one say it says 240 bytes so we've saved all those bytes basically it's all the characters in your serial.print statement okay and down here it says the flash the memory is now 4.9 so 1586 bytes and previously it was 1966. that's all those statements because the serial.print statement you know in c terms compiles to quite a little bit well obviously it shows it here so that is proof indeed that compiling with and without debugging um makes a difference um so what about that warning oh that warning yeah okay now there are some side effects of course by turning off your serial.print statement nothing to worry about but look at what it's saying here it says look in your loop the void loop statement function it says you've got an unsigned long called b i know terrible name isn't it add one counter and it goes unused variable b it means you're not using this value b anymore in the code what does that mean let's just go back to the code and have a look so i'll expand all that down so in the loop we're saying unsigned long b here it is even got a little squiggle under it look add one to counter but where are we using b well the only place we're using it is in the debug statement debug line b and what is debug line at the moment because we've switched off debugging well it's it's nothingness so these two statements are effectively gone they do not exist as fast and compile is concerned so we've said unsigned long b equals add one counter and um we're not using that anywhere so you get a compiler warning so sometimes you have to adjust your code a little bit but it's it's pretty rare to take a value that you're only then going to output on the serial port you might do in which case be prepared for the occasional warning doesn't stop it compiling it's just it's just a oily tap on the shoulder to say do you know you're not actually using this variable i think you might have done something wrong because you've got a variable now you've declared it you've done something with it but you're not using it anywhere that can't be your intention surely but in this case it was because we've switched off the debugging cool okay that's that's good as far as it goes of course right so what about a logging or debugging system for larger processors where you got more space to do stuff well this is my esp32 web radio and as you can see in this code it's got things like log e log i log d yeah i know pretty much what we just covered wasn't it for the arduino type processors except this uses a much more sophisticated way of doing it and if i expand my include libraries we can see here arduino log as the c plus and the arduino log header these two libraries are the ones that make up the full-blown logging system that i'm using on my esp32 projects because we don't have to worry about space as such yeah now these are proper i'll say proper you know in quotes um code um examples where they have you know it's a class if you look at all this it uses templates and stuff and it's it's brilliant and i love it and i use it all the time and there's lots of information on it on here and i'll let if you're already coding on the esp32 and larger processors like that i think you'll get to grips of this in about five seconds flat mainly because if you just implement those two libraries you can start using the logging as i've just showed you there's just something in one of these files you have to set the the log level that you want but that'll be pretty obvious as well and basically you don't have to look at this ever again if you don't want to you can just have it as a black box but within your code which is what was showing you just up here you can use all these log d's and look you can see it says there that expands now that's using as you can see there log print f previously we said if we wanted an output of counter we'd say serial print counter in quotes and then under that we say serial print line the value of the counter two lines for one thing with a serial print f you can put all that on one line and i won't go into it now but there is a library which i'm going to show you that allows the printf functionality to come into any microcontroller right very quickly then just to summarize this if you go to this webpage links down below and in the github this is the arduino printf library and it gives you that printf functionality where you can put variables in the same line as your standard print statement and it all comes out nicely formatted now i won't go into it but you can see examples and all that in here how to use it but more to the point this is the actual repository you'd need to download so this arduino printf is specifically designed to allow it to run on an arduino so you might want to download this and give this a whirl as well if what i've done is a little bit too simplistic for you but obviously the the more um sophisticated the solution the the steeper the learning curve so you're on your own with this i'm on the right i'm i'm not using this particular one i'm using that one i showed you for the esp32 the logging library but there's there's everybody wants printf i mean when i have to go back to code where i can't use printf it's a real pain you think why didn't arduino implement that it's very odd that they couldn't or wouldn't do that but i guess other third parties now have okay well your comments will be greatly received down there um what else have you got to do don't forget to share and like this video if you think it's worthwhile especially you beginners who haven't done this sort of thing before and um oh yeah if you want to subscribe don't forget to tick the bell because i keep telling me to tell you that so i'm doing it i'm doing it okay and um yeah i think we think we're done really great next week we'll do something completely different again um this is sort of a beginner's video and i hope it was useful for you so until next week keep tuned in i hope you're finding these videos useful and interesting there are plenty more videos to choose and a couple are shown below and if you'd like to subscribe to this channel just click on my picture below and enjoy the rest of the videos thanks for watching
Info
Channel: Ralph S Bacon
Views: 62,115
Rating: 4.7523479 out of 5
Keywords: Arduino, Beginners, electronics, C++, microcontrollers, programming, gadgets, ardiuno
Id: --KxxMaiwSE
Channel Id: undefined
Length: 26min 38sec (1598 seconds)
Published: Fri Sep 03 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.