#BB5 Moving your Arduino to a multi-tasking State Machine - Easy Intro

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
and welcome to my series of short videos in which we discuss how the arduino interacts with various electronic components yes in less than 15 minutes we'll go over the basics how they can be used hints tips tricks and traps and this week it's all about doing more than one thing with the arduino just look at the board down here my workbench i can see we've got two leds right one's flashing quite slowly the red one and the green one on the left is flashing at a frantic rate yeah now we're doing two things there aren't we and how do we do that if you think you know how to do this if you can do this on your arduino no fancy coding no bit manipulation to standard arduino speak c plus plus pause the video have a go if it takes you more than about 10 minutes you obviously don't know how to do it and you can come back all right so i'm going to say goodbye now and see you in 10 minutes well that wasn't 10 minutes was it okay let's just carry on now the goal then is to flash these leds at independent rates so let's wind the clock back and go really back to basics because that's where this video is of course intended it's intended for those programmers those arduino people who've got limited exposure to coding and possibly even the electronics that runs this right so let's go back to what everybody starts with the blink sketch i want to give a big shout out to pcb way pcb prototype the easy way now we're all familiar with their special pcbs five dollars for 10 pieces but you can also have flex pcbs advanced pcbs and of course you can order custom parts let's have a look at the cnc and 3d printing options they have so it's 3d printing first you upload your cad files as you would normally for a pcb but then you select your materials and submit a quote request cnc machining is pretty similar in the way you submit your files upload your cad files select one of these many many different types of material you can use and of course there are also 27 different options for the surface finishing just look at a few of those there from anodized brush bead blast spray painting and there's more under that list as well and finally the sheet metal laser cutting and bending so let's have a look at that once again you upload your cad files select the products you want to make it from and specify a few of the parameters here about whether you want threads for example and you can always submit your request for a quote and it's about seven to nine business days to get it done okay that's pcb way excellent service good quality why don't you check them out now so this is where everybody starts from yeah me included umpteen years ago when i started with pick programming that's exactly what i did and it's and it's a good step to take isn't it you think i finally understood the connection between my computer the arduino board or pick board as it was then and a bit of electronics and the code and it's it's a good milestone unfortunately the coding techniques in getting that uh single led to blink are not the best let's have a look at the code so this is um well i made this up but it's exactly the same as the blink sketch in the arduino examples right which everybody tells you to start with to make sure you know roughly what you're doing to upload a sketch to the arduino so what we do then let's just whiz through this we're defining one single pin pin 10 here for our red led doing a bit of startup where we are saying the red led is an output pin we're setting it low initially because i don't want the led to come on do we and that's all there is in the setup apart from this serial output so you could if you wanted to trace it through the blink sketch is simple enough we don't need to trace anything with serial output so we can just ignore that in here let's just close that up and have a look at the the main loop then so what we're doing in the main loop we're saying for that digital right on the red led pin set it high in other words set the pin to 5 volts and let the current flow and we hang about for a bit half a second in this case and then we say now switch it off and then hang about for a bit again so it's an equal on off situation we have here you could change them but that's basically it now you might say well what's the problem with that i can do lots of stuff in my loop and stick delays in all over the place yes you can but your code will be well let's just call it sub optimal because what's happening while this is going on so the led is on you've just switched it on up here you're now waiting for half a second what else can happen in that half a second what if a user presses a button for example a screen needs updating anything basically and the answer is tough luck this is busy whizzing around doing absolutely nothing so it's not the best way of doing multiple things on your arduino but not talking about multitasking here not really it's all one big task because the arduino is not sophisticated enough to have any kind of operating system with true tasks but we can certainly emulate that and it's the way your code should be written so let's just move on to how we can get two leds blinking using the same sort of code structure as what we have here so okay we've got two leds now connected up this arduino and we've said blink the red one and blink the green one and i want the red one to be slow and the green one to be fast or it might be the other way around um oh that's not what's happening though is it look we get a red blink and then a very quick green blink and another red wing and then a very quick green blink but hang on the point here is we want them independently to flash we don't want one to work and then another one to work yeah we want them to run independently at different rates so what's going on well let's have a look at the code and see what the problem is so as before we define the led pins in this case we've got them on pins 10 and 8. yeah we do the setup exactly the same as before we set the output bins to output mode and set them low initially and that's all there is in this setup so let's just collapse that let's have a look at the loop now so we've taken the code from the previous single led sketch we said well here's the red flash and that worked well so we'll stick in here and then we'll have the green led flash underneath except yeah i know you're ahead of me you can see the problem whilst this is running and well not doing anything in these delays for example this green led hasn't even got a look in has it so it flashes the led on the red side once and then it comes down and says oh now i've got to flash the green led only a bit quicker and then it goes round the loop again it goes now i've got a flashlight red led for a bit longer time and the green one a little bit shorter but they're not independent are they one is waiting on the other the green bit of code here cannot run whilst this is running because it's all sequential and we've got these these big delays in where nothing can run isn't there a better way we where we can say don't delay just do a bit and then when you need to do a bit more do a bit more but don't wait yes and this is this is what um is called a state machine well it's the first steps towards a state machine let's not get ahead of ourselves you've heard the expression walk before you can run well we're going to crawl before we can walk yeah because you need to understand the fundamentals here before we start walking so we've understood that this is never going to work because one bit of code is waiting on the previous bit of code to finish before it can work and just to reinforce that message let's have a look at that workbench again so the red flashes and the green and the red flashes then the green that's not what we want okay lesson one then how we can make that better code a bit more responsive and more to the point independent red independent from the green and vice versa ah now this is looking a bit more like it the led on the right the red one is flashing at a modest pace but the one on the left the green one is flashing like a thing berserk and they're not interfering with each other that's the whole point yeah however slow the red one goes it's not going to slow down the green one and the green one is not waiting on the red one to do something and finish before it can get a look in so how do we do this let's walk through the code okay let's start at the top then so as before we define what the output pins are they haven't changed it's still ten and eight um you don't this is called forward declarations of our functions you don't need to do that do that in the arduino ide because the arduino ide is caring and it's it's for beginners to say look under normal circumstances you would have to declare what functions that are on your program but the arduino preprocessor has a quick look for you and sticks them all in the front behind the scenes so you don't have to good that's for beginners that's very useful but you don't have to do this if you're running this in the arduino ide this is in fact a different one so i do have to put these up here the setup is exactly the same as it was last time we're setting the output pins here for green and red and setting them low initially that's all we need to say about that let's have a look at the loop then now the loop here is only two lines and i'm saying blink the red led and then bring the blink the green led now does that mean go and blink the led let it blink and then go and blink the green led well it can't do can it because that's what we had in the previous example where the green led was waiting on the red one to finish blinking before it got a look in but here as you saw on that desktop we'll prove it again nothing's waiting for anything here so the loop is saying go red go green and they're doing their things independently how do we get to that stage let's have a look at the code after the loop in a bit more detail so the code that the loop is now invoking to say go and blink the red led is this bit here now let's talk about this in a little bit more detail the very first thing we do when we come into the blink red led function is to say take a snapshot of what the current milliseconds are since this whole arduino turned itself on all right remember the arduino can run for 49 days before that counter goes back to zero so what we're saying is this variable here red millies is being set initially to the number of millies as it is right now and then we're saying if the number of millies minus the red millis is greater than 500 do something well it can't be greater than 500 the very first time because we've only just taken the millis into this variable so it goes well no that if statement is false i'll just skip all that go back to here and back to the loop off it goes so it's done nothing i think hmm okay so back to the loop it goes the loop says oi ready go so back it comes into blink led now this time this variable is not affected that is only done a first time because you've got this magic word at the front called static what that does is ensure that this declaration unsigned long red millies is basically moved somewhere like here in front of line 26 at compile time but it also means that nothing else can update red millies this red the scope as it's called where you can get red millies into your code is only in this function now i know that some people put things like this they declare them like that up here in the main code and they make them what's known as global that's a very bad programming practice after a few decades in their programming world because that's my day job i know about these things and global variables are the satan's spawn believe me why are they global unless they are global for a reason they most certainly should not be and this red millies is only ever accessed here and here nowhere else so why are we making it global we're not we're going to keep it within the scope of this one function but by putting that magic static word at the front the compiler says ah you want me to execute that statement the first time and then basically move this as i said in front of line 26 and keep it there as a sort of pseudo global but not really and that's the way to do it and there's no if butts or maybes this is the way to do it now static the keyword static in c plus plus does a multitude of things depending on where it's used this is one use of it so don't think this is the only use of it or where you read it again that's what it's doing it can have a lot of different types of meanings which is a bit unfortunate isn't it but in this case it just means only execute this line once when you first come across it and then move the variable outside of this function great so the second time it comes in then it's not going to execute this line here because it's already done it once so we'll come into the if statement and say well is the number of millis minus the value we previously extracted from millies greater than 500. now remember we were just here probably less than a millisecond ago if that loop is whizzing around a few thousand times a second it could go no i haven't been running for more than a millisecond yet go away so it skips all the rest of the code and goes back to the loop yeah i think you sort of start to grasp now what's going to happen yeah because eventually it will keep going around the loop and none of this coding is executed and then suddenly yes for half a second 500 milliseconds has indeed passed since we took this snapshot up here of millies the very first time he goes yes we have gone beyond the 500 milliseconds so now it says we're going to do something with that red led we're either going to turn it on or off depending on what the current state of it is so it says digital read red led go and have a look to see what it is now and that exclamation mark at the front of it says not i make this value the opposite of that value so if this digital read was a low it's going to make it a high and if it was a high it will make it a low and that's what we're going to put into this statement here so we're going to toggle it flip flop if it was high we'll make it low if it was low we make it high it's a nice little construct for flipping a gpio pin and then of course we must re-update that red millies value from the current value of the milliseconds because remember 500 milliseconds at least has passed since we took the very first one up here so we now update it and off it goes out of this thing back to the loop on the loop then eventually calls it again to say okay blink red led you're on this line is not executed remember it's first time only so it says okay is the millies minus the red millies that we updated down here is it more now than 500 well of course it isn't we've only just come from here less than a millisecond ago so no we skip so the red led is still on and will stay on however many times we come into here until 500 milliseconds has passed at which point we do this whole thing again and go okay let's set the red led the gpio pin for the red led to whatever it isn't at the moment so we have a read and goes oh it's on it was high and we're saying not with the exclamation mark which is a low so we're going to say digital right red led low that's what that will do the second time around it comes in we then capture the millies again into a local variable and that's it back it goes to the loop the loop will then say oi blank red led you're on go it'll come down here it will not execute that line it will come straight into the if statement and go have has it been 500 milliseconds since i was last year and of course the answer is no we've you've only just turned the led off a million seconds ago so it'll whiz around keep getting called keep getting cool keep getting called from the loop for half a second until eventually this condition is true at which point it says ah right my turn to do something again so it says i'm going to set the red led gpio pin to well what are we going to read on the digital read red led well at the moment it's low so it says not low which is high so i'll set it to high again ready red led goes back on and we snapshot the millis again in order to us so that we can have this 500 millisecond gap between each invocation of this bit of code so as you can see a lot of the time it's just spent going from the loop to this function the function says no this condition is not met on your bike and it'll go back to the loop at which point it gets immediately called again saying blink red led go and he goes no this condition still isn't met it's only been two milliseconds back to the loop and it will keep going backwards and forwards backwards and falls back and forwards until it's met and half a second has gone past okay so while it's doing all that what else is it doing let's have a look at the next function down which will look funny enough very similar to this one so the blink green led function is identical to the blink red led except for one little feature this one it said and the red led it says has it been half a second since we did anything in which case we either switch the red led on or off we switch it to whatever it isn't at the moment but the green led is only a hundred milliseconds so it's much quicker well five times as quick for in effect and you can tell that difference on the breadboard on you it's flashing at a very fast rate indeed so the loop let's expand the loop again now here the loop says blink the red led blink the green led and as we've just explained when it calls this most of the time it it just exits immediately because this condition of has half a second passed is false it goes no back at which point the green led function is invoked by the loop and go well green led have you got anything to do the green led goes no i've got nothing to do either it hasn't been 100 milliseconds because the arduino is after all running at 16 megahertz which means it's going to go around that loop several thousands of times a second depending on what code it's running in there it's pretty fast it can do a lot but every 100 milliseconds it's going to flip whatever the green led state is to either on or off by virtue of this statement and every 500 milliseconds is going to flip the red led on or off but the beauty is they're both being called and both being run several hundred times a second and therefore the green led and the red led are no longer interfering with each other so you think you've cracked the state machine now yay we've done it we've got a state machine and things can run concur no it's not quite that easy yes on this particular bit of code now as we saw from the desktop those two leds are indeed running independently but that's only the very first step towards a true state machine mainly because in that bit of code that you saw there isn't actually a reference to a state is there we're just calling route two functions here to say go go and the function itself says do i actually want to do anything right now no i don't go back or yes i do it's time for me to flip that led on or off but within the machine itself now within this bit of code there is no state we don't know what the state of any of the leds are at any particular point in time yeah we have no idea which is why this is only the very first step towards a state machine now the fact of the matter remains is that you might not need to go to a full state machine and in fact i'd say initially don't why make it more complex than what you have to we've got two leds running here you could have three or four or five yes any number of functions that are called from the loop so say do this do that do the other and each of those functions independently go is it actually time for me to do something look at the millies has enough time passed no it hasn't immediately exit to give another routine the chance and if it is time fine then we'll action the code in that big if statement and go yeah i'll do this and i'll do that i would say if you don't use this technique now's your chance download the code all the examples all the stages of this particular demo or in the code and you can copy one in after the other and just see how we progress from a blocking function that stops anything else running so this particular piece of code that allows this and many many other things to run i use this sort of technique all the time cool i think we're done here if you've got questions still on how this affects what your particular project's doing or how you can improve it i might do a more advanced one into the state machine mechanism where we do have proper states within the machine to say if it's this state do this if it's this state do that but it's still going to be based on this coding mechanism so i do highly recommend you take it down and have a look and play with it become familiar with it because this is most definitely the way to go cool we're done here questions down below as i've said and uh if you think this was interesting and you've learned something maybe give it a good thumbs up and remember there's plenty of other videos to choose i'll see you in the next video 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: 47,209
Rating: undefined out of 5
Keywords: Arduino, Beginners, electronics, C++, microcontrollers, programming, gadgets, ardiuno
Id: hwEo49yyU88
Channel Id: undefined
Length: 24min 10sec (1450 seconds)
Published: Fri Mar 25 2022
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.