#71 How to create an Arduino Library - easy!

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
and welcome back now today is going to be a rather special video because we're not going to talk about hardware like this today what we're going to talk about is how we manage our code whilst we're writing stuff for this can you guess what the topic is a bit of a clue I suppose isn't it right let's talk about libraries and how it can really really help you once you've got a decent bit of code under your belt and you're you're drowning in lines of code so the first question to answer really is why would you even want to create another library if you're quite happy creating a sketch like the one shown on the screen you think this is fine I'm just going to put all my stuff in this in this one file I'll even separate it of course into separate functions and so forth but I'll keep my code here and yes you can do that and I do it all the time so don't create life isn't everything not by any means but a library can be useful if you've got some complicated or both methods or functions and you possibly want to use them again or even if you don't want to use them again frankly just get them out the way you want to put them into a different file that you can then use within your main one so for example if you've got a sketch that might monitor your beer fermentation process I'll use as an example because I know somebody worked I was just that now there's going to be many many functions that are going to be used in that sketch now you're going to be looking at temperature you're going to be looking at time you're going to be looking at different kegs all sorts of different things and you can imagine that the sketch could become become quite verbose and unwieldy and fail so that when you're looking for a particular method that you're trying to change you've got to scroll up and down a lot in your file you don't good not quite all it is you might end up collapsing a few sections if you notice on there you might for example collapse your code to try and get it out of the way of the code you're actually trying to write so I'm here for example this simple little sketch if you click that little - you'll collapse it and keep it out of the way I will do that with a setup because once you've got the set and they don't want it constantly at the top of your door am i ve getting in a way that's one way to do that of course but it'd be so much nicer if you could create your sketch get to a point where it's stable II think right they want to touch this min or my temperature monitoring function for example is quite long it it reads from various senses and it gives me something back and that's it is done and I want to continue writing the main sketch now but without that constantly getting in the way so this is how we're going to put some of that code into a library out the way that you can include in your sketch and indeed included into other sketches if you've got a more generic function then you can include that in as many sketches as you want let's start with the basics and save right here we have your brand new open file but in fact I have saved as a library example number one and I'm just going to create a very simple made-up function now what I don't want is for you to watch me type in rather painful leaves and coding in these sections here so I'm going to put a little tiny nonsense sketch in here that basically doesn't really do anything is that printer numbers say but we're going to pretend that the methods or the function that it calls is quite long and verbose and complicated and you've done it and you don't want to do it again so let me just paste in that code first and then we'll talk through the rest well Benny look Benny is going to come and supervise in the sound with it right so here we have some very very simple code that we're going to pretend it's not so simple and then we're going to pretend it's a bit longer more for both and generally complex than what it is here so what we've got here is basically a main loop the calls an underlying clever function that you've written it's taking a long time and it might call many other functions within it and then you're just going to print a number one script so proud demo purposes it's particularly simple for that that's good because then you can see the wood for the trees so here is this complex function that we design is probably you know 20 50 a hundred lines long maybe and it returns a special number meaningful to you as part of your be a monitoring process or whatever it has to be so having got that ready now and you think right now want to write another function under that now this one's all in the way bit my oh yes as I said before you can collapse it like that you still get something there so what we're actually going to do is take this single function here and put that in a library and then see how you have to change this to include that in your program now of course if you've written any sketches at all or notes you probably have used the include statement with a library it's just that if you've ever looked at a library behind the scenes it can seem quite daunting and complex so let's unravel that and make it really simple so the first thing to do is of course create what is the the stub of your library now library has two files in it well more may actually but we'll discuss those going forward two main files there's the dot H which is a header and dot CPP which stands the code programs another what is the code it's effectively the CPP stuff is going to contain all this and your header is it going to take contain a description of what this is and allow you to create something so you can get hold of it so let's do that only odd we know IDE and I'm deliberately using Arduino IDE here because it is what most people use and it's just a simple to create library in here as it is using any other ibe okay right the first thing to do is what let the cat out alright okay so what we do we click on the little triangle there and you can see the little pop-up comes up and we want to say new term then what this is actually going to do is create a file in the same place that you created your sketch originally now that's no good for a library going forward but it will certainly be good while we're testing it because it'll be local to your sketch so we're going to create two tabs and the name now let's let's assume that we're going to call create a test library so let's call it test library and and another one which is the test library dot cpp these will be saved in the same place as your original file as I said to that that's good there is a small tiny tiny caveat that when you include it it's very easy to find files in the same folder not so easy to find Thailand in the libraries folder so you have to use angle brackets not the quotes around your library so let's have a look at how we might do it right first of all we want to take this long process here and put it into the CPP because that's where your code is going to result so that's the first thing we can do so we can take all this simply cut it out of there and put it into here okay we're going to do a bit more to that in a minute but least you've got rid of the stuff out of your standard sketch now the next thing is to update the header now you're nuts trust me on this one the little backs is a few things in there that just are the way they are because they are the way now and now assume that you write your test library and it's a great success musing great I can include this nor my programs an unknown to you you've actually tried to include it more than once you've got exclusive files and you've included in one sketch and then you included perhaps in another library even you what you don't want to do is include it twice that will give you compilation errors because you get duplicate references everywhere so the first thing you need to do is to say if I've already got a copy of this file somewhere don't include it again and the way you do that is to have an if not defined if in this and then whatever you want to call it so we're saying test library left key this short tl so if we haven't defined that then we will define it and then lie on the bottom all this we're going to end if so everything in here that you're going to declare is part of your header will be subject to this if statement have I already got this somewhere in other words can I find a reference to TL no I can't create I'll include it now if you were to include it twice then the second time it hits a test library reference maybe you'll go it's not defined TL o but it is to find I can see in a reference that they'll skip to the end this mapping it no compilation errors cool okay now there's a standard thing that goes at the top of every header and basically it says if my Arduino version is greater than 100 which is basically 1.0 then I need the Arduino header so we're using a library already within our library so if you want to use Arduino functions and names and stuff within your library which you will then you need to include the Arduino header specifically your sketch does that behind the scenes you'd have to do that you may have noticed when I use my Eclipse IDE and I have to include it explicitly because it's not specifically for do we know uses lots of languages so let me just paste that in and I'm gonna come back to that okay so that's pretty standard so here I've pasted in the rather simple class definition but let's just go through this line by line what we're saying is here we are creating a new class now class can visited a blueprint okay it's not the actual object you'll be working with in your sketch you're gonna have to instantiate that that means create an object from this blueprint that's what class is the same right let's create this test Lib I've called it test lid normally I think you tend to probably call it the same name as the file as in so like test library looks a bit long isn't it press at the moment so I'm calling our test clip them if they write which functions that we want available publicly that is that you can call from another program now here the only two public methods we've defined is one is the constructor that is this is called when you declare this use we'll go through that in just a second so here we're saying here's the constructor when you create this title object this is the thing to run and I'm declaring it here but not telling you exactly what I'm doing with it yet and we've got a method called get random number which is a bit of code of course with half hinged from the main sketch and we're going to put that into the CPP now you can also declare here some private methods what are private methods well they are methods that you can use in your CPP buy the CPP itself and are which a part of this library but which cannot be cooled from your main sketch and nobody else can call them their main sketch either if you were to share this library for example so they're private to the class the class itself can call them but they're not exposed to the wider public that makes sense ok hence public and private now within private you can't just have message you could have variables for example so if you wanted to count or suddenly you want to keep track up you could declare it there okay well that's all we're going to do for the class and as you can see it's very simple oh one warning here please please end it as you can see here with a semicolon after mainly an hour trying to figure out why this thing wasn't compile that England can pop because you've forgotten the semicolon and guess what the component doesn't tell you it just gives you a zillion errors about are they something wrong with a name or something so don't forget that semicolon at the end of your class constructor right let's move over to the cpp library then right this is the CPP and all of them including the here at the moment is this rather weird construct now if you remember in the constructor of the header so this flip back here is saying look here's the constructor test lib and we have a boolean and whether or not to display a message well I'll just put this in there just to show you how you can pass messages in in fact let's enhance that because you might want to do when you create this object you might not want to always say display message so what you can do there in fact is put a a default parameter so do we want to display the message always no we don't we might want to do it when we're debugging something but not always so we can say no don't display it by default unless you include the parameter that says yet display message sonar and this is where you do it in the header don't do it in the CPP bit so in the CPP file we're saying right off the test link class here's my test lib constructor look at the colon colon bit in the middle do you know I'm sure they do it just to make it look complicated anyway so this the class is the constructor here's our little parameter that we're expecting to come in but if you don't supply it you'll get the default value of false right and as it happens we're actually doing anything yet with it but you could easily here do a series of prints assuming that the serial port was open anyway it's just show you how to supply message and or a parameter I should say now here's your pretend long complex procedure that we pinched from the sketch now here you can't just leave it like this because this get random number doesn't stay as part of the class so once again there's a little bit here test colon colon we're going to have to put in there as well so let's them let's just put that in yep so now it knows that this get random number is part of this class has is a constructor part of this class brilliant it's all hanging together so if we look at the header again with them here's my constructor called cache Lib which is the same name of the class that has to be and here's my single function I've got and though I haven't got any primer functions yet okay so back in our library example now we now include a reference to the test library now a here you notice is in quotes now if you move your library files to the libraries subfolder then you're going to change that to angle brackets because it's in the same folder or leave it as quotes colors if I don't find it close means same folder angle bracket means the wider scope okay now we're declaring test Lib now you have where's where's this test Lib come from well that's what we call it when we declared it look class testlet I could about any name in there Fred John super complex ma'am keep it simple okay so that's what we need to use as the type now the name of it come out so anything like Fred John anything but just for demo purposes which is calling it the same in lower case now remember we said we had a parameter all right now we've made it optional so if we don't specify anything here you won't get message coming out well if we'd written the data code that put the message out but we're saying yet in this instance I'd like that message to come out because they'll tell you as a developer all it's actually called the constructor of my class okay so when this bit of code runs this bit here so it is actually instantiating the object creating the object from the blueprint you could put a serial dot print in here just to say I've run or the test live object has now been created okay now okay that's fine so all the rest of the code is as it was until it gets down to get random number because that's now a function of this object which is here okay another function of this object is dot get random number and I said so simple so we've taken this get random number quite complex well pretending it's quite complex piece of code maybe several methods but it might be calling yourself we've taken it out of your main sketch stuffed it into CPP file and said yes now it is actually part of this library test Lib library and the header has declared it here and it's made this sketch very very clean and easy just like it is when you use other people's libraries your sketch is now nice and lean however don't get carried away here don't think are so I've now got more space to put more code in and stuff it into my Arduino doesn't no-no-no your code size is this sketch here Plus this library it all gets compiles now I'm pretty sure the compiler isn't smart enough to dispense with methods I knew that I get all gets compiled an optimizing compiler for example would come to your your library and same thing and what you haven't actually called this routine anywhere I won't even compile it I'll discard it I'll compile all the ones you have used but the ones you haven't Auto Scott I don't think the GCC one does that so the size will remain the same it won't be any bigger though because although we've written three files now more text if you like the actual underlying codes notice oh right that's all it is to do lets them well let's compile it and see what happens well I took a few seconds longer than I expected that there is if come back and it says the sketch is 2 for 18 for nuns aunt larlie block so it said it's run or compiled so let's upload it into the Nano that I've got attached on my desk of course the actual Nano itself isn't going to show anything I think I do think other than spit out a number the number that we created is part of the cpp part this one here okay so let's just upload that and then see what comes out on the debug window anyway up right so there's the debug window let me move up here and there it is spitting out the number so what we're doing of course can I make this any smallness of a look yes right so this is saying go and get me my random number generator function from this library and if somebody else won't if they're friends rather live and get is you to use you might have any idea how this works and frankly you might not be that bothered it's a black box isn't it but work it does so you're getting this random number back from the test library which this object here the test lid has been declared here and it's off type test lid with the Capitals okay and that is all declared in the header here's the test Lib constructor there's a method that's actually doing the work so let's see then if we can actually put in a message in the constructor so that up here basically so when we instantiate this line we actually get a message back to the serial port saying ah yes I have actually run and in the meantime while I'm doing that I'm going to clear up whatever is causing this it's probably some old reliably some ways trying to find anyway I'll do that and come back in just a jiffy now interestingly enough I remember that there's a little gotcha if you can see the screen at the moment is supposed to be outputting the message here's part of the constructor and in fact if we just flip over to the construction of this what it's basically saying is test level constructions don't shave landed like a bar and we've done a serial begin here because of is we can need that we can output the message and we've taken it out hold here however there's a little gotcha here if you start putting zero beginning constructors it doesn't like it don't know why the forums aren't any help in saying why what they do say is though put this into a different method so we create another method or function on our test library called begin or something and put any messages like this in there so let me just change this out a bit I'll have to change the test libraries out so there is a begin function now that we can use and see how that comes along okay very simply then all we've done now it said that as part of this test lid we're going to give you another method called begin and we'll wrap it because we are going to do a serial don't be get in there let's give it the board rate that we want so you'll begin to start that and here's the default value 9600 I use 9600 all the time but I have to put 0 dot begin now six-hundred everywhere because that particular library hasn't got a default value but we're going to be kind to I use and say well the board rate which is a parameter to the begin method as 9600 as a default value so if you don't specify that's what you're going to get so now our CPP library has to actually create that method properly and I've squeezed it in here lit so tesla'd remember it's got a pilot s leave you can't just have a begin because it could be a begin for any class and lots of classes have got begins so we're going to say Tesla begin here's my board rate okay remember we don't put any default parameter in the CPP so with an adder so cereals are begin whatever you've said and then we can print out our line and we've taken it out of here we'll come on to this display message in just a minute I want to get this pics here first so now in our sketch we're going to say create the object as we always did up here and then instead of doing a series I became I'm going to say tesla'd got begins that'll do effectively a serial I begin 9600 and display a message so let's see if that works let's upload that and see what happens here we are it's running nicely got the message coming out and the pseudo-random numbers are coming out as well this is a whole tree long complex procedure you remember doing all this calculate the number of stars and the galaxy or something so that's that's all pretty good isn't it but one it'll fly in the ointment this message that comes out we might not want that coming out every time so only when we want to debug something do we want that message coming out so how do we stop it well remember that when we do a test clip up here when we create the object here we're saying true yes we do want to help if we don't put something in the output false then it shouldn't come out so I just change that to false and upload that and have a look at the output monitor serial monitor I still it and oh dear it's still coming out why is that so remember when we change the way that the serial dot begin was being invoked by our little object called test Lib we didn't change anything in here is this is where it's saying do you want the message coming out or not but we've not done anything with it so of course here it's going to print Li regardless because there's no if statement down there now this is a very good example now I can show you of how to use private and variables this display message when we instantiate the tesla'd is the one that controls whether a message will be help us or not but how are we going to keep track of what that value is we don't start putting Global's in here so in the class Lib definition as a private parable now we can put in whether or not whether or not we want that message shown so we have a private that you notice it starts with an underscore that's convention for private variables for the in your code we know you're dealing with a private variable not exposed to the real world by that I mean in your sketch so in here there's no way you can get hold of that underscore message boolean it just isn't available to you none of this can read it it's only available to this here so what we're going to say here then is we're going to say underscore message equals display message so we're capturing the value of this when it's instantiated storing it our private variable and then here we can say here underscore message now we don't actually need the curly braces because it's a single lift up to the cornice so many people get things wrong when they don't put in I think we will end it right format that ctrl T all right so what it's saying is if we set it here true or false we'll read it here so this is acting like a sort of a global variable but it's in our class definition of the private variable so now without changing our sketch let's compile that upload it and see what happens and there we are it started to print out the numbers without that message and just to prove the point if we change it now to true and re-upload that and bring this we go to the for uploading it's done it and we are back again so now we control whether that message is available and effectively by creating that library in such a way that we can supply this parameter here it's the beginning method down here that will eventually keep this or capture that to determine what we're going to do with it and that's it you've created now a library so just fixing this up we're going to take out that line next we don't need X are testimo because that for us now look at that nice clean code or the complexity of the actual bit that generates this special number down here and we're just doing some clever things here for controlling where the messages are displayed or not and the header is the definition remember that the definition in the header does unless you do anything it just says what is expected that's your CPP must match what's in the header but your sketch would look at the header to determine what's available and what isn't for your particular class okay I think that's some very simple and yes it is a slightly artificial example but even this one has probably given you a good idea of how to create a library and in fact I do urge you and encourage you to download this test scripts test sketch and just run it and then you can play about it and make it go wrong and find out why okay so so the things to remember is you must always be Claire all methods any method that you want available you're sketching must declare here within your public constructor and of course your actual test library CPP file must include that method obviously it's got to do something here okay and in your sketch we just consume you like that Tesla dot whatever that's the method coming only further with this example well let's think from it right so there's one thing we can do here just to prove the point once again it's an artificial construct but let's assume now that our public method the one we get our random number has to go and call another method that you've constructed and it's quite a complex thing got lots of lines of code in it and we're going to call that we're going to call that a float get PI ok so it's a method that doesn't have any parameters but it returns a float and it does in fact get pi okay so in our CVP now we've got to create that one so let's create it underneath this one so we're going to say float get PI no parameters but we are going to say return 3.1415926 they'll do okay close enough isn't it two pi so instead of having PI here now we're going to say get point so that this method is a private method only available to this home class here you couldn't call get PI here we try to say test Lib dot get PI the compiler is real world inside I can't find the public method called get PI because we've defined it in the header as a private method and only available to your class so this one here private method this class now if already spotted the deliberate error that wouldn't have compiled have you done it this is test lib right otherwise it'd just be a general get toilet in the loud right let's compile that upload it see what happens well that's not loading now let's go back to the window see what comes out and there we are so the message is still come actually said yes we want it and it's generating these random numbers including points that somebody called our float get PI quite happily so your public this is this because this our public method get random is calling its own special private method of get poems is down here and yes we still have to say as part of the test library because it is alright so that's how it knows where it is but nothing else can get out of it see so your sketch cannot use no matter how much it wants to test lead what get pine to prove the point will say what was it a float wasn't it float test equals test slip stops get PI will try and compile that let me move this this bit up here to be a bit more room for the error messages which will doubtless get now I'll just compile it and then we are look it says error within this context is that it's not only a bit more floats titik is private it most certainly is let's go to the top which starts at here smooth it's not unpleasant big right saying in the loop we're trying to call basically this method and its product float to get PI error within this context can't do it simple as that and that's good because it means you can write lots of private methods within your library and only expose the ones that you want the user to keep consume and get a value from this stuff like that okay so there we are that sort of proves the point on that one didn't it that cannot be done that's coming out I'll leave that you know actually and leave it some in the sketch my son is right we're going to leave it now I think um if you were to follow this video start to finish download the code have a little play you know that the code that's coming down the line will work when you get it if you play with it and break it you know download it again we'll just restore it from your copy but I think it hopefully gives you a flavor of how useful even your libraries could be never mind all these big ones learn about the internet your own personal codes can be made pretty much simpler and tidier by creating libraries of functions that you know have done and dusted and you just want to get them out the way rather than just collapsing stuff up by clicking that - but then of course does get expanded I think it was only compile all the mingle and tell me open the sketch up again put them into a library now you know how to do it I think you'll see that you can move stuff over into library and it will really benefit those more complex programs great stuff and then leave you with a couple of links actually because if we go to the browser let me bring my browser up now the library specification is on this one here and I'll put a link into that and there's some another one my else's that is keywords keywords is not a little ultimately they explained it but let me show you what that means when we were creating our function here all well and good but when we try to consume it you see that test lab tests lib nothing shows you color wise that it's anything special how do we get around that where you create another file in the same place and I'm actually going to do this in notepad just to make it a bit easy so let me just bring that up and I'll show you exactly NEADS so on screen now you'll see that Tesla is nice and orange and up here and get random number is also nice nor ensuring that these are recognized names if you like how did this happen well it is that a slight dot chair didn't work the first time I did it because well it would appear I didn't know this but it would appear that you can't do this if the library is local it's got to be in the actual libraries folder so what I've done is move them over to the libraries folder so let me just bring this up alright so this is just the File Explorer in Windows so created a file called keywords dot text along with these two that we had previously but I've moved them now into the libraries subfolder okay within the arduino sketches called it tests are basically the same name of course as your sketches for the test library folder can change these two files Plus now keywords does that look like so here we have keywords the text now the bits an important hash at the front means is a comment and here we have our keywords one which are orange keyword once a test Lib for example you see in the back here is orange and both begin and get random number of keyword twos so they are here and here and if you notice they're well they're still orange on political speech I believe it they're not bold so this is a subtle difference those colors and they are controlled by part of your preferences and yes look at the Preferences file but don't do it when your IDE is open because when you're close your IDE writes back over the top of it but that's for another day okay so that's that that's that we get nicer on these numbers remember I had to move them into the libraries subfolder they like to work that's just wondering here whether it really is like that okay also I changed them the quotes here now to Chevron's to make it treat it more like a library rather than something local by touched of course the underlying files if you notice the the two tabs here now have gone because those files don't exist anymore okay that's it well that was a very short well I say short let say a brief introduction to libraries it's quite simple once you've got your head around it once you've got a working example in front of you I think it's really good and then you'll suddenly hopefully see the benefit of moving your code into library okay great hope your code improves dramatically result of this video thanks for watching and see you in the next video I hope you're finding these videos useful and interesting that are plenty more videos to choose and a couple of 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: 131,267
Rating: 4.9066401 out of 5
Keywords: Arduino, electronics, C++, microcontrollers, programming, gadgets, library, .cpp, .h, header file, keywords.txt, class, type, object, blueprint
Id: fE3Dw0slhIc
Channel Id: undefined
Length: 38min 13sec (2293 seconds)
Published: Sat Jan 21 2017
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.