I'm a former college computer science instructor and I found your explanation of finite state machines right on the mark. Well done. Keep up the good work.
You have to be the best tech hobbyist oriented teacher on KZbin. Really enjoy all your videos!
@RalphBacon Жыл бұрын
Glad you like them!
@Sydney268 Жыл бұрын
Great explanation, you won't get very far programming microcontrollers without understanding this!
@RalphBacon Жыл бұрын
Indeed. Getting it drawn out on paper makes you (and me) think about all conditions and states too!
@jlr3636 Жыл бұрын
Ralph, excellent, I applaud you for showing in real time what the end product will be or do and then explaining the process to achieve the end goal. For me, knowing where you are headed helps me to better process the steps, helps me to organize as the steps build to the final goal. So often (even good) instructions show the steps then 💥 the finished product, and the entire time I’m wondering where we’re heading.
@RalphBacon Жыл бұрын
Good point you make there, I shall bear it in mind for future videos too.
@Worldwarrior01 Жыл бұрын
Ralph, much appreciated. Been watching KZbins to get answers for a number of things I’m doing for a project. Your simple outlook helped me change my methodology on what I’m going to do. Now I’m going to watch more of your videos to give me possible more ideas.
@RalphBacon Жыл бұрын
Glad to help! Yes, I had to modify one of my projects this week that used a finite state-machine structure. It made it much easier to change things (without introducing any weird side-effects).
@ferguscampbell24852 жыл бұрын
Back in the mid 1980's I did an Armed Forces Computer Maintenance Course. Everything was coded in binary, using "If, And, Or, Go To, Return" commands. After having a stroke, I finally have time to try and learn to program modern computers. These two lessons have finally opened up modern computer programing to me. Thank-you.
@RalphBacon2 жыл бұрын
You're most welcome, Fergus. It can definitely make your programs much cleaner and more likely to work!
@amazagx2 жыл бұрын
Excellent!! Please continue with more videos related to state machines. Thank you!
@RalphBacon2 жыл бұрын
Thanks, will do!
@renelefebvre532 жыл бұрын
I use the library "metro" with arduino devices. It's à good code for little states machines. It's a minimal scheduler for Attmega368.
@RalphBacon2 жыл бұрын
I'll check that out too, thanks for the heads-up. 👍🏻
@TheUnofficialMaker2 жыл бұрын
Not only a great teacher but a great producer too. How long did it take to make this 30 min of pure gold? I think we all agree that we appreciate your effort, time and skill! You did not miss your calling.
@RalphBacon2 жыл бұрын
Thanks Vic. I do try and make my "productions" watchable as well as useful 😜
@keitholiver39812 жыл бұрын
A good explanation of a state machine, we used similar process when programming a real time PBX. Using ON HOOK, OFF HOOK, decode DTMF tones etc. many thanks brings back old memories.
@RalphBacon2 жыл бұрын
Thanks for sharing, just goes to show this is not a new approach.
@pjforde1978 Жыл бұрын
Thanks so much for the state machine implementation, Ralph. I was able to completely refactor my timing-intensive project so that it runs without any delay() calls at all. One bit of advice I'd pass to your viewers is that for many use cases, you can get a huge amount of utility even with two states; I was able to solve a tricky long-press duplication just by relying on the state machine to bounce any unwanted events that don't conform to the current state.
@RalphBacon Жыл бұрын
Fantastic! I'm very happy that your coding has "improved" by using a finite state machine.
@chucklearnslithics37512 жыл бұрын
Time management in Arduino is one of the most important topics, but I often find that when people, in the colonies at least, say they need "time management" in their program, they really mean state management and they're using some time (millis()) component to move through states. This is the best demonstration I've found on this topic. Thanks for building and sharing this!
@RalphBacon2 жыл бұрын
I'm glad you found it useful!
@michaelbreslin91162 жыл бұрын
This really helps me to aspire to coding at another level. Love the logical flow. Not sure, for me, the "self descriptive" statements. I was always bad at languages. I've always felt a bit uncomfortable with, repetitive outputs "Light the 'elevator called' LED", and "Extinguish the LED", now I'm asking myself, why, I guess it's ok. At least, I think they are repeating, if I've read it right. Thanks Ralph for these videos. Not sure I'll ever get to this level, but they are great to watch, and learn from.
@RalphBacon2 жыл бұрын
Practice makes perfect, Michael. 😜
@BILLYSHED Жыл бұрын
Thanks Ralph - I definitely caught a few more things watching your videos on FSMs that other videos glossed-over.
@RalphBacon Жыл бұрын
Glad you like them!
@1_HighDuke2 жыл бұрын
Excellent explanation. Thank you, Ralph. You're a great teacher and your lessons have been invaluable in helping this amateur to bring little projects to life.
@RalphBacon2 жыл бұрын
Glad it was helpful!
@Dav41222 жыл бұрын
Loved that displayState method - not really shown in the video, but a neat way of not spamming your serial monitor
@RalphBacon2 жыл бұрын
Nothing worse than a gazillion messages spewing out onto the serial monitor. This keeps it nice and clean. 🫧
@johnmarshall26602 жыл бұрын
Hi Ralph, Yet another great video, it reminds me of the Switch Case I did for my Model Railway which has 10 switch case statements for routes, which are triggered by Reed Swotches under tracks so Loco has a magnet, the Mega I use has most of the Data and Analog pins used, the Case statements switch points and Aspect signals, at the Exit of the route an IR Sensor will hold till last carraige as passed, code is about 1000 lines and the main part I was helped by a member of MERG ...John
@RalphBacon2 жыл бұрын
That's impressive, John. The advantage of using a State Machine is that if your State Diagram is correct then your code will be too. In your case, pretty essential. 🚂
@MrAlFuture2 жыл бұрын
G'day Ralph. This has been an excellent mini-series, thank you! I think you found a good balance of simplicity/clarity of scenario without being trivial or getting bogged down. Just thought I'd mention the idea (and you kind of implied this in passing) that the indicators (yellow LED and buzzer) could each be encapsulated in their own state machine to handle turning on and off and timing etc and have the main Elevator state machine interact with those. Thanks again for the awesome videos :)
@RalphBacon2 жыл бұрын
Glad you enjoyed it! The thing about FSMs is that they can 'explode' quite quickly - yes, that's the official, technical term for when the number of states just gets out of hand and becomes unmanageable. The answer to this is an HSM (Hierarchical State Machine) where State Machines are embedded inside a parent State Machine. This ensures that one FSM doesn't try to do _everything_ by itself. But that's a whole level that hobbyist Arduinites are unlikely to (want to) get to, IMHO. I don't use FSMs regularly (but would you Adam & Eve it, the project I'm working on now _does_ use one) as the simple approach of calling multiple functions in a time-slicing way that I showed in Part 1 works very well indeed. My ESP32 Web Radio works this way, and that can be very time critical if I don't want the streaming music to stutter (it doesn't).
@2ndmileproductions2 жыл бұрын
Great lesson Ralph. Opens up all kind of possibilities!!
@RalphBacon2 жыл бұрын
I hope so! My most recent project was also written using this method and it all works just fine!
@TBoy58_4052 жыл бұрын
Yours was the right video at the right time for the project I’m currently on, so many thanks. My way of state machines worked, but yours is a lot neater. Also I’m greatly cutting down on global variables because of you, so thanks again. I’m trying to cut out ‘else’ in ‘if’ statements, which might be a good idea for a video, if not already done 👍🏾🤓
@RalphBacon2 жыл бұрын
You're really taking all this on-board, well done Peter and I'm happy it's helping you.
@SnackPack91311 ай бұрын
I’m using a state machine to build an automatic dog feeder. I like it because I can continually add complexity pretty easily. I will start with the food already staged in a tube and open it with a servo after a time delay, later I can add a dc motor driven auger to take food out of a hopper and then a pressure sensor as feedback to switch states and turn off the auger once the correct amount of food is in the tube, etc. pretty cool thanks for the explanation
@RalphBacon11 ай бұрын
Sounds great! My latest project used a Finite State Machine too, works just fine!
@ikkejick Жыл бұрын
Thanks so much, I needed a simple introduction to state machines and this video is just that. Cheers!
@RalphBacon Жыл бұрын
Glad you liked it!
@ChrisWilliams-pu8pjАй бұрын
Considering using Arduino as gate opener. Great content for that application. Thank you.
@RalphBacon25 күн бұрын
Glad it was helpful!
@InscrutableObjects Жыл бұрын
Your tutorials are some of the best out there that I've seen! Thank you for the time and effort you put into these. You have a new subscriber! :)
@RalphBacon Жыл бұрын
You're very welcome!
@veedonfleece36942 жыл бұрын
Well done, Ralph, it is a pleasure to learn in such a friendly, pleasant manner.
@RalphBacon2 жыл бұрын
Thank you, glad you liked it!
@TheEmbeddedHobbyist2 жыл бұрын
Nice to see you changed to a switch statement for the FSM. I often leave out the break in the switch statements as it can allow several switch states to perform the same action, some states do something different. The default state mops up the rest. Very easy to read. Next some UML ;-)
@RalphBacon2 жыл бұрын
UML? Oh, I was going onto Hierarchical State Machines first... 😲😂🤦♂️
@TheEmbeddedHobbyist2 жыл бұрын
@@RalphBacon did the first designs in the new Yourdon structured method (YSM), am i showing my age.
@47mattie472 жыл бұрын
This is great! Would love to see a follow up video on more useful things you can do with State Machines. And perhaps other oddities and quirks to be aware of :-)
@RalphBacon2 жыл бұрын
"...other oddities and quirks..." That's no way to refer to me 😡 how rude 😁
@paulodagraca34692 жыл бұрын
This is great information, to any 'new' programmer. With Multitask, State machine, and use of Switch statement... and keep it all nice in a flow. Cheers mate.
@RalphBacon2 жыл бұрын
Glad it was helpful!
@automation_jeff2 жыл бұрын
Ralph, another well done and informative video. One thing, I understand this is just a video on the basics, in a true state machine you should verify that the state has truly changed before moving to the next state. In a case like this, using a timer in an elevator application is not telling you if the state has truly changed and could come down to a safety issue in the real world
@RalphBacon2 жыл бұрын
Yes, point taken, but I think a Real World elevator program would be considerably more complex than this demo version, including umpteen safety checks!
@automation_jeff2 жыл бұрын
@@RalphBacon Oh absolutely, there's more safety checks in the real world. Still all those safety fault conditions would have to be satisfied before signaling for a state change.
@imstubby6844 Жыл бұрын
Thanks it has made so much sense and i feel excited to go and move forward with my code.
@RalphBacon Жыл бұрын
Great stuff! I hope it helps you greatly in your future coding.
@richardkussin3206 Жыл бұрын
Thank You! Another key buiiding-block in my programming education. (I now understand why there are no goto statements).
@RalphBacon Жыл бұрын
OMG you mentioned the unmentionable! I remember GOTO statements from about 40 years ago in the BASIC language. A pity it was ever invented!
@richardkussin3206 Жыл бұрын
@@RalphBacon For me, it was 50 years ago (in Fortran). RIP 'goto'
@VilleWitt Жыл бұрын
Predictability is based on conventions/rules. C and C++ kept the “no goto” a convention, rather than a rule. This allows us to reason about scope and entry/exit of language statements and functions. In the video, the author also added a “no blocking/no waiting convention”. This is the concept of (voluntary) time sharing, giving an element if multitasking. Between these conventions, here are the consequences: * goto breaks the expectations of function entry and exit, control statements. The abstraction breaks down. Some languages removes the jump/goto statement. * Blocking breaks everyones expectations of time, that execution returns swiftly. The time “precision” is lost and things start to lag/skip events etc, bugs in time. The timing becomes unpredictable, the multitasking abstraction fails. “Preemptive” task switching prevents exclusive access to CPU time. There are still goto statements, but it is a tool that requires extraordinarily discipline. Such discipline is best handled over to lower levels of abstraction ie the compiler. Some say time sharing is best left to the scheduler. But note, if you do timeshareing - do not cheat by blocking! Blocking (bugs in the time domain) will bite as the complexity grows.
@stspringer20032 жыл бұрын
Great video, you explain it well, very articulate, can you explain how the random statement works random (3,8) * 1000 Thanks
@RalphBacon2 жыл бұрын
To use the random number generator, you first need to _seed_ the generator, otherwise you get the same sequence of numbers each time you run the sketch (no true random numbers from a computer). So, randomSeed(analogRead(A0)) will get some random value from the A0 pin (or other analog pin if you are actually using A0) and "seed" the generator. Then you specify that you want a number by random(lowest, highest) and you get a number out. The lowest _includes_ the value you specify, the highest _excludes_ it, so random (3,10) means any number from 3 to 9 but not 10. What do you mean, someone screwed up that function? 😂 Multiply by whatever factor (if any) you want, so multiplying by 1000 gets you (in the above example) any an exact multiple of thousands number from 3000 to 9000.
@davemorgan4524 Жыл бұрын
Excellent video. I was having some difficulty with an esp32 battery powered project. Mapping out the possible states would have been a good idea in the beginning! But now I have fsm in my toolkit I have some fresh ideas. Thanks!
@RalphBacon Жыл бұрын
Glad it helped!
@aymanmiri22362 жыл бұрын
Hi, Thank you very much. you've just saved my life. Your video helped me so much, I was struggling with a Stepper motor that I had to control without using any library and this motor is a bipolar one, my problem was just that my code works fine because I use millis() function to update the menu on the screen to give how many steps and how much time should this motor run etc... But when I press the button the motor starts running and my display stops updating, but now it's work completely fine after i used your method with enum class and switch case. Thank you again.
@RalphBacon2 жыл бұрын
Thanks for the feedback, Ayman MIRI, I'm very glad you got it working.
@leec2106 Жыл бұрын
I like your teaching, I did something similar using interrupts, the way you do it is easier to follow the interrupts will ever be. Lee (fyi, I did not know comments help)
@RalphBacon Жыл бұрын
Glad you like the content of this channel, Lee, great to have you on-board. Yes, comments show YT that viewers were engaged and therefore they will offer it to other YT viewers as one of their "suggested" videos. Who knew?
@Roy_Tellason2 жыл бұрын
Some years back I ran a BBS. In its idle state there was a program looking at what the modem might have to say, and which would hand off to the bbs software if a human caller connected, or perform various other actions if it were another system calling with mail, a request, or whatever. Many different protocols were implemented. I took a brief look at the source code one time, and what I found was a whole slew of different state machines, sometimes nested one within another, before I gave up on trying to understand how things worked to any level of detail. It can really get quite complicated! :-) But it really did work well, handling all sorts of stuff...
@RalphBacon2 жыл бұрын
State Machine do work but can get out of hand too, if there are too many states. It's called State Explosion and is usually handled by a Hierarchical State Machine (sounds like that's what you had, nested State Machines).
@romancharak36752 жыл бұрын
Fabulous explanation, Ralph ! Thank you so much.
@RalphBacon2 жыл бұрын
Glad you liked it!
@andymouse2 жыл бұрын
Great tutorial Ralph !...cheers.
@RalphBacon2 жыл бұрын
Thanks for watching!
@lewishamilton9941 Жыл бұрын
Excellent Demonstration
@RalphBacon Жыл бұрын
Glad it was helpful!
@jjab992 жыл бұрын
Great video as always, many thanks for sharing.
@RalphBacon2 жыл бұрын
Glad you enjoyed it!
@amosfalcon6190 Жыл бұрын
Thanks for your kindly sharing in precious programming skills🫡
@RalphBacon Жыл бұрын
You are most welcome, Amos.
@IanSlothieRolfe2 жыл бұрын
The easiest way to drop into the "default" case is to add in a state to your diagram, add the transitions to your existing states, then forget to implement the actual state. It sounds unlikely, but when you get state machines with dozens (or even hundreds) of states its surprisingly easy!
@RalphBacon2 жыл бұрын
Yes, I can believe it. Additionally, in an Hierarchical State Machine the default case can be used to cater for the "next level up" actions in the same way that Windows or JavaScript bubbles up events until they are captured by something (or discarded).
@colormaker5070 Жыл бұрын
I found your channel and its been a great as I learn esp32 in platformio.
@RalphBacon Жыл бұрын
Welcome aboard! Yes, I use ESP32s and PlatformIO all the time now. A good combination!
@mr.bianchirider81262 жыл бұрын
I remember in a Fortran class doing diagrams like yours using diamonds and boxes. I also remember those darn punchcards and waiting in the basement (all computers were in the basement, right ?) for the program to run. There was always some poor guy who would trip on the stairs and the punch cards would go flying in the air.
@RalphBacon2 жыл бұрын
Those diamonds and boxes were not State Diagrams, they were flowcharts. It's how things were done in the Bad Old Days (probably before electricity ⚡ was invented to run the darn computer). Oh, and don't mention punch cards to me. Having had to punch a few using a hand punch (with nothing printed on the card to show you whether you had done it right or not) I still have recurring nightmares about them. 😲
@salc95932 жыл бұрын
Hello Ralph. Thank you again for a very informative and educational video, you have a great way of explaining coding in a way this neophyte can follow :-D I am looking forward to using your diagram for a project I'm working on and hope I may ask questions of you in the future to point me in the right direction as I continue my journey in coding. Thank you again for a excellent presentation. Be Healthy and Be Safe.
@RalphBacon2 жыл бұрын
Glad you found it useful, Sal, and good luck with your project 🤞🏻
@OsoPolarClone2 жыл бұрын
Another great and interesting video. It gives me ideas on programming that will eliminate the use of the delay operation. Thanks
@RalphBacon2 жыл бұрын
Glad it was helpful! I'm even more glad that you are going to ditch the delay() statement 👍🏻
@gregwmanning2 жыл бұрын
Enjoying your coding lessons with theory and examples
@RalphBacon2 жыл бұрын
Glad you like them!
@jeffbluejets26262 жыл бұрын
Great stuff.....I need to watch this a couple of more times, then possibly create some other arrangement and see if I can get that to work. Thanks again. Jeff
@RalphBacon2 жыл бұрын
Go for it!
@Potts19662 жыл бұрын
Might be more correct to say concurrently rather than simultaneously.. Nice video, I understand finite state machines but always nice to get a refresher and it's a really good video on the subject.
@RalphBacon2 жыл бұрын
Fair enough! Concurrently it is! Well, it isn't, but close enough 😁
@TheEmbeddedHobbyist2 жыл бұрын
Well to be concise the Arduino cannot do concurrent processing, it only has a single thread of code execution. You can time slice this to try and make it appear to be concurrent which a Real Time Operating System does (RTOS).
@Potts19662 жыл бұрын
@@TheEmbeddedHobbyist I have done a lot of RTOS programming on various micros, so concurrent is the term I tend to use. It's not 100% accurate in this context but I feel it's more correct than simultaneously. Not to take anything away from the video, which I found interesting and informative and very helpful to people not only learning about Arduino's and embedded programming but more advanced programmers expanding and consolidating their knowledge.
@TheEmbeddedHobbyist2 жыл бұрын
@@Potts1966 According to the Oxford dictionary: Concurrently Adverb at the same time; simultaneously. According to Lexico, the word simultaneously means "At the same time". And the word concurrently means "Existing, happening, or done at the same time". So both are not 100% correct for the describing the action of the state machine or anything performed on a single core microprocessor. I would rest my case if it was on an ESP32, which with some carful programming can run programs concurrently. I say careful as one core still has to perform all the Wifi, Bluetooth operations. Don’t get me wrong I watch all of Ralph’s videos and find them great. And I think they are great at giving the old grey cell a bit of exercise. But I was just pointing out that with a single execution core nothing can be performed simultaneously or concurrently.
@Potts19662 жыл бұрын
@@TheEmbeddedHobbyist Oh wow! A simple comment gets blown out of proportion! .. LOL. Relax, I think we're all on the same side here. I was associating Ralph's state machines as being similar to multiple threads of execution in an RTOS and while obviously on a single threaded processor they can't execute at the exact same time, they can execute "concurrently" and appear to run simultaneously to an observer. (concurrently being a term I learned from my OU course on operating systems that I still use to this day) I think we're going to have to agree to disagree here. If you want to post more of your more correct explanation then go for it, I'm out.
@stub11162 жыл бұрын
I really enjoyed this video.
@RalphBacon2 жыл бұрын
Thanks Stu, glad you enjoyed it.
@StigBSivertsen2 жыл бұрын
Literally tons of use cases I can use this coding technique on. Thanks for the video and happy easter 🙂
@RalphBacon2 жыл бұрын
Glad it was helpful! Happy Easter 🐣
@shush13297 ай бұрын
Awesome video, you help me with a school project, keep it up with these good videos!
@RalphBacon7 ай бұрын
Thanks, will do!
@hucobo6 ай бұрын
Thanks for the explanation, I think I understand it. I like to program an Arduino for more then just 2 leds which flash. I have written a simple skecth for two photographers who are waiting for a train to enter a platform and then shoot each two pictures with a random pause between the flashes. But watching your explanation for state machine, I like to use more outputs of the Arduino... ;-)) I will give it a go and will try to write these flashes as (finite) states.
@RalphBacon6 ай бұрын
Flashing LEDs are all well and good for a visual demo, but most users like yourself will want to do something more useful. Start small, and expand. It's too easy to not spend enough time on drawing out all the possible states and start coding before you're ready! Don't ask how I know this. 🤦♂️
@Wilksey372 жыл бұрын
You should always add a "default" to the switch block in case something modifies the memory that the state pointer / variable is at. You can also just "return" from the state machine or switch block adding a break under a return can cause some compilers to moan. The industrial way of doing the "call" function would be a debounced interrupt if they are available. A switch block is also useful if you have a lot of checking and the "if" statements are getting out of control. Very well conveyed information on FSMs, have a like.
@RalphBacon2 жыл бұрын
Thanks Aaron. You have raised a good reason for always having a "default" case (to be honest I thought they were mandatory but apparently they are optional).
@Wilksey372 жыл бұрын
@@RalphBacon Yes they are optional, but any good compiler will raise a red flag, I think it is good to get in the habit of adding a default, I think in BASIC it is "case else".
@peircedan Жыл бұрын
Dropped in here to check out what method you are using to implement a state machine. I have been using PIC MCUs for years but only recently started using the Arduino IDE for ESP32s. When programming PICs in C I usually use a function pointer as a state variable. That way I can change states by setting the state variable to a different function. Each state is represented by a function. Then a switch statement is not needed as the state variable points to the correct function to call. In my opinion the function pointer implementation is simpler to maintain.
@RalphBacon Жыл бұрын
You carry on using your function pointer if that works for you, Dan, by all means.😁 But you won't convince me that's the best approach for newbies to the concept (and subsequent programming). Once a developer understands the concepts they may well graduate to your preferred method!
@12dodo37 Жыл бұрын
Do you have a code example to show me? I'm interested to learn what you just explain! Thank!
@peircedan Жыл бұрын
@@12dodo37 I'm not going to post my code here. I respect the response from @RalphBacon . Perhpas some day I will have an example specific to the Arduino IDE amongst my Github repositories. My current code is written in C for a PIC Xpress board and as such would likely only cause confusion here which I don't want to do.
@TYGAMatt2 жыл бұрын
Great vid as always Ralph. I need to use switch case more often. Spent today writing if, else if, etc. Many times. Changing the subject...... "enum" ..... How about a series on enum, typedef, struct, class. I know I'd be interested. I've used all except enum, but very rarely as I'm far from proficient at using them. I'm pretty sure that just a short vid from you would have us all understanding them clearly. Just a thought. Cheers. Matt.
@RalphBacon2 жыл бұрын
It's certainly an idea for the Bacon Bytes series, Matt. I shall bear it in mind. 👍🏻
@TYGAMatt2 жыл бұрын
@@RalphBacon Cheers Ralph. You've saved my bacon (pun intended) more than a few times with your clear and consice approach.
@andreaswolfesberger61402 жыл бұрын
waiting so long for part 2 - thank you
@RalphBacon2 жыл бұрын
So long, Andreas? It's only been a few weeks! But thanks for hanging on 👍🏻
@jimbarchuk2 жыл бұрын
*Pro Tip:* I saw the title for #1 that said 2 parts, so I waited till #2 came out and then watched both. Very well done.
@vectorsigma99032 жыл бұрын
Great video. My code readability just went up ten points!
@RalphBacon2 жыл бұрын
Nice work!
@meicharries22492 ай бұрын
An excellent tutorial on this subject Ralph - so clear - many thanks indeed. I am a relative novice to programming the Arduino, certainly at this level and have spent so many hours toiling with timer issues within the Switch-Case. My only workable solution was using counters and flags! So, could you enlighten me why the timer delay counters are not reset in your solution. Also, could you run 'For Loops' within a Switch - case construct to say cycle through the elements of an array or would you need to call a declared function for purposes like this. Again many thanks for sharing your skills.
@RalphBacon2 ай бұрын
I'm very happy you found it useful 👍
@haroldfinz486311 ай бұрын
A finite state diagram is just the equivalent of a "flowchart" that programmers use when the chains of "if"s get too long, and the "ifs" have too many "else"s. Some programmers code these into a "(current state x input) --> next state" table of functions, and use a "controller" to manage the jumps.
@RalphBacon11 ай бұрын
I love the way you say "just the equivalent of..." - as though any Arduino-level coder is going to agree with this statement 🤣 (not because it is wrong but because they will not understand your comment). As I've said many times before, this channel and its contents are all aimed at newbies and intermediate Arduino coders at best. And that's not to denigrate "bedroom coders" at all, we can't all be pro developers!
@haroldfinz486311 ай бұрын
@@RalphBacon On the one hand, you have honored me by your comment! Sorry it wrong-way-rubbed you. I honestly thought I was adding constructively to the discourse -- I was not keying in a cheap smart-a$$ retort. Seriously, as I re-read my comment, the only thing I can see that may have been (albeit unintentionalbly) objectionable was my use of the word. "just." Having said that, YOU owe me an apology. I denigrerate NO-ONE. I am myself a comp-sci teacher. I am NOT a "pro developer." I do NOT post to criticise your content. YOU invoked the idea of a FSM -- not me -- and all I said that that a FSM was nothing esoteric, it was just a way of organizing a flowchart.
@RalphBacon11 ай бұрын
😲The trouble with comments is that tone-of-voice and nuances get lost in translation! As you inferred, I thought your comment was a dig at using an FSM as a glorified flowchart (and maybe, in some ways, it is, as it does control the flow of code execution, after all) but I obviously mistook the intention and tone - *unreserved apologies* to you, Harold. As one of the "pro developers" I mentioned, I've seen (and been subjected to) many an ivory tower coding methodology; sometimes the current way of thinking, sometimes demanded by my employer as "that's the way we do it here"! But FSMs can be understood pretty well by most people, including bedroom (aka hobby) coders and can make a huge improvement to not just their code, but the way they have had to _think_ about possible states when drawing the diagram - including, as I have just done with a project, to realise that what I thought was TWO states was, in fact, a SINGLE state! Anyway, thanks for your contribution; now that I've re-read it in the proper way it most certainly does add to the discussion. 👍
@CTCTraining12 жыл бұрын
Excellent work Ralph, and yes you could add lots of extra states into the model but the only I’d argue for strongly would probably be ‘BROKEN’ ... not just because of its ubiquity in daily life but because it introduces a route to the admin-state-machine or ‘Fireman’s key’ world of additional behaviour which, most likely will be being hacked together somewhere else and the protection afforded by FSM’s can be valuable. Keep up the great work 😀👍
@RalphBacon2 жыл бұрын
I had to chuckle at the thought of a BROKEN state. What you really want is a Hierarchical State Machine where the "default" case (ie not handled) bubbles up to a higher level and is dealt with there - that would handle the BROKEN state (or any other forgotten state).
@salc9593 Жыл бұрын
Hello Ralph thank you for posting this informative and educational (for me) video. Using the enum class as shown in your example I have the Yellow LED on to show power is applied to the Arduino. When the button is press the Yellow LED goes off and begins Blinking the Red LED 6 times using the statement: void blink6times(){ for (int i=0; i
@RalphBacon Жыл бұрын
You need to draw a Finite State Machine diagram. That way you will have various circles representing the different states. The loop then has, for example, a SWITCH statement and executes the code _just for the current state_ . When the state changes (eg a timeout in your case, so the current state code will change the state to the new one), the loop will execute a different bit of code the next time around. Make sense or too brief?
@gregorymccoy67972 жыл бұрын
Well done, Sir. Endlessly applicable, too.
@RalphBacon2 жыл бұрын
Thanks, Greg(ory) 😜
@marcobucci Жыл бұрын
Thanks for these lectures :)
@RalphBacon Жыл бұрын
Glad you like them!
@robertobrenes52832 жыл бұрын
Thanks for this video! Many uC applications i've made I've design like a state machine and it has work great to catch bugs and user interaction
@RalphBacon2 жыл бұрын
Great to hear, Roberto, thanks for posting.
@robertobrenes52832 жыл бұрын
@@RalphBacon thanks to you for doing such informative videos!
@tomheeks2830 Жыл бұрын
Great video, thanks. This may well be useful for my arduino project. Although I think just what was in part 1 would suffice, I'm not the best programmer so might try and implement it this way. Who knows, I might learn something!
@RalphBacon Жыл бұрын
Glad it was helpful! Yes, part 1 is certainly a good step forward, although this video describes a true Finite State Machine (which my latest project also employs).
@flemmingchristiansen24622 жыл бұрын
Of course you get i "LIKE" and a comment.😊😊 Well explained, yet another friday I learn something new.👍👍👍👍
@RalphBacon2 жыл бұрын
Awesome, thank you! As it happens I'm coding my Container Bin Lid project using the same sort of model. All working as it should, of course. 😁
@flemmingchristiansen24622 жыл бұрын
@@RalphBacon Of course 🤣🤣
@grahamwise57192 жыл бұрын
Hi Ralph, did you mention displayState that only prints the state once, otherwise each loop would print out the current state! Good example thanks.
@j1952d2 жыл бұрын
Just removed my comment to that effect, having seen yours.
@RalphBacon2 жыл бұрын
I didn't actually go through the code as it was not relevant to the State Machine logic; but yes, it just compares the current state to the previously reported state and just prints it out if there is a difference. Stops the Serial Monitor getting flooded.
@bhushansurve35039 ай бұрын
Great Tutorial. Thank you for getting this out to us. Just got confused about where to use the ; or : after the state name ie. IDLE: or IDLE;..
@RalphBacon9 ай бұрын
In a SWITCH statement, the CASE parts are followed by a colon after the value. Example: switch (myVar) { case 1: //do stuff here break; case 2: //as above including the break statement otherwise: What to do if none of the case statements above match }
@kingearwig Жыл бұрын
I just gave this video the 1000th like
@RalphBacon Жыл бұрын
Wow! thank you so much, Bill! 👍
@bob-ny6kn2 жыл бұрын
Sorry to clutter State Machine comments with this question... i did give a look, but soooooo many videos... Which video introduces installation and setup of your IDE and Serial Monitor? Also... how do you get "Manage Libraries," "Port Select" and "Board Select" to work in your IDE? Your videos are on my PizzaVideoFriday list. Thanks.
@RalphBacon2 жыл бұрын
Nice to be on that list, Bob, but I don't remember any Pizza being delivered here 🍕 Now, if you look in my video description, Bob, there is always a link to a PDF file of all my videos. That way you can search it for a useful phrase. But to save you the bother this time, and going back to 2016, there are a couple of older videos you might like to watch (WARNING: not the same quality as the current ones, especially in sound quality 😲). Video #3, kzbin.info/www/bejne/q2O8dneGfMZ-Y9U Video #4 kzbin.info/www/bejne/aoqcq2qchrJrmck Video #16 kzbin.info/www/bejne/bX3GZIOqebKcoLs (for COM port stuff). Try them first. If you have specific questions feel free to email me (my email is on my ABOUT page).
@nb6175 Жыл бұрын
Thank you so much. You are an excellent teacher.
@RalphBacon Жыл бұрын
You're very welcome!
@theScottishAlien2 жыл бұрын
Would you be able to give a part 3 to this series looking at FreeRTOS and their xTaskCreate() ? I've only recently discovered this in the ESP32 and its kind of blown my mind for creating async tasks within a microcontroller (like checking internet and NTP connection)
@RalphBacon2 жыл бұрын
I want to cover FreeRTOS _for the Arduino_ would you believe in a future video? I've already done the ESP32 (quite simply) in video #149 kzbin.info/www/bejne/oKG5lHajnZ2mn8k but I think an update is probably due. Keep tuned...
@theScottishAlien2 жыл бұрын
@@RalphBacon sounds good! I'm using an esp32-s2 at the moment and FreeRTOS still works with the single core. Would definitely be interested to see it on an Arduino too. Have been itching to try build a state management system like Redux or Bloc (I'm a web/mobile developer for my day job) and have mostly been blocked on the synchronous nature of cpp
@mihaiaragon2 жыл бұрын
Hi, this is a very interesting set of videos for beginners, like myself. Thank you. I am struggling to understand how to apply this knowledge to a project that I am trying to finish. I was wondering if you could help me? I want to run on an Arduino Mega a stepper motor and a couple of digital sensors. I am trying to spin the stepper continuously and in the same time check the sensors and somehow it is too slow between the steps of the stepper and don't know how to make the stepper spin without big breaks between the steps. Do you think you could help, please?
@RalphBacon2 жыл бұрын
You will have to determine how often you must tell the stepper motor "Go!" to turn it continuously, without any stuttering or pausing. The gap is all the time you have to run other code like sensor reading. If reading sensors is a "blocking" activity, that is, you request, say, a temperature reading but that takes 100mS, well - that's a 1/10th of a second that the stepper motor is not getting any signal from your sketch. Part 1 of this video showed a way to split your time between various functions using millis(), but if your function tries to read a sensor that then "blocks", there's not a lot you can do about it. Your stepper motor will stop. An alternative would be to use a "timer task" to keep the stepper motor satisfied whilst your main "loop( )" did other work (like reading sensors). The Timertask runs regardless at a frequency determined by you (eg every 10mS) to keep your stepper motor running smoothly. I did a video on Arduino timers in video #209 (and possibly #210) so you will need to do some research on this. As you are running on a Mega2560 it will support a task scheduler (RTOS) which I did a video about recently in #244; if you need to continuously hand-hold the stepper motor it would do the job but only you will know if it's beyond your current capabilities.
@yayser2 жыл бұрын
Hi Ralph. I have been trying to develop an electro-mechanical puzzle game for which I needed to code a state machine without knowing what it actually is. I have relatively little knowledge on Arduino and achived this by if / else routines and functions. At some point, I realized that I need some sort of flag to record which state my system is in, and only then was I able to switch between states. I just wish I knew what it is called before and wathced these wonderful videos before so that it would have been less-painful-two weeks:)) Anyways, at least now I know how valuable this information is, thanks again.
@RalphBacon2 жыл бұрын
It's actually always good to define a need and then to discover it. Whether that is a particular DIY tool or a coding technique your just KNOW that it is the right thing to use. So good luck with rewriting your code. It won't take that long because you already know what has to be done. But do spend time on the State Diagram - it's your blueprint for a successful program.
@tattoomafew2316 Жыл бұрын
You can still assign elevatorState with an integer like this: static elevatorState currState = elevatorState(0); // IDLE Writing it this way makes it possible to increment states. You could do something like: int i = 4; // out of range currState = elevatorState ( i % 3); // loops back around, assigns IDLE state So even when "i" is out of range from the number of states, it will loop back around and pick a valid state.
@RalphBacon Жыл бұрын
Unfortunately, I would consider that using "magic numbers" and is not considered Best Practice. Using an enum (ideally a class enum) forces you (the developer) to use meaningful state names. I'm not sure that performing maths on a state is that meaningful, just my 2c worth! But maybe you could write a function to do that, anyway.
@nmjerry2 жыл бұрын
U.S. 3 light stop lights have two additional states, for when the local central traffic controller is offline. They are flashing red and flashing yellow, which convert the stop light into either a 2 or 4 way stop sign. The flashing yellow like may be used to give one of the cross traffic paths preference, and means no stop required but cross with caution, the stop light is not working.
@RalphBacon2 жыл бұрын
I just knew someone would tell me that I hadn't covered all bases! As a reward, Jerry, I'll let you write the state machine for all the cases now known about. Should keep you busy for a while!
@renelefebvre532 жыл бұрын
FreeRtos with Esp32 or STM32 are great for do this.
@RalphBacon2 жыл бұрын
I have it on my list. Not just for ESP32 or STM32. FreeRTOS for Arduino, anyone? Seriously.
@RichDMonte2 жыл бұрын
Hi, in your video about using the DF Mp3 player I commented and asked for your thoughts on what I had done using 20 folders on the SD card and was working on adding LEDs to indicate which folder was active, WELL... I watched this video multiple times and think will solve my problem, just need to sort things out as to IDLE, CALLED< ARRIVED etc to fit my needs. Thanks for this video.
@RalphBacon2 жыл бұрын
Fantastic! I'm glad it's all up and running and giving you the opportunity to do some creative thinking too!
@jamesmoon5632 Жыл бұрын
Great lesson thanks 🙏but my static unsigned long time stays at 0. Is this due to updates to the IDE?
@RalphBacon Жыл бұрын
No, it won't be that. I can't remember the code I showed here but if you do this (below) it will prove that static variables do work: void loop() { static unsigned long counter = 0; Serial.print(Counter: "); Serial.println(counter++); delay(500); } At _compile time_ the declaration is removed from the loop and initialised. Thereafter, every time the loop is executed the counter is incremented like any other variable. The Good Thing is that the _scope_ of the variable is restricted to the loop (or whatever function you declared it in), not every function you might write.
@jamesmoon5632 Жыл бұрын
@@RalphBacon that sounds fair ill have a go and thanks for the reply. Love your channel
@peircedan Жыл бұрын
@@RalphBacon I'm thinking you are keeping the explanations simplified. In reality the static variable is not removed from the loop. Static variables are initialized by compiler generated startup code that is executed at run time before control jumps to main(). This contrasts to automatic variables that are created and initialized on the stack every time a function is called. The location of the variable declaration inside the code block of the loop is the vary thing that limits the scope of the variable to that code block. In my opinion understanding storage class is worth learning and ought not be glossed over.
@Chriva2 жыл бұрын
You missed "BACK" (!) in the intro. excellent video as always Mr. Bacon :)
@jyvben15202 жыл бұрын
only for the people who were there before
@RalphBacon2 жыл бұрын
Different video series, different intro!
@jstro-hobbytech2 жыл бұрын
I'm kidding Ralph. This is an awesome tutorial. I know of state machines in circuit logic but wasn't familiar with the c++ data type enum.
@RalphBacon2 жыл бұрын
Glad you enjoyed it!
@jlr3636 Жыл бұрын
So years ago a operator would sit on a stool, ask “floor please”, pull some levers, and away we go. Actually a technical job to stop at the correct floor and align the car with the floor. Today that job has been replaced with a $10 Arduino. Years from now the Arduino will be replaced by “telie transport” , you’ll just think of the floor and flash bam you’ll be there. Times change.
@RalphBacon Жыл бұрын
It's called "progress", I believe. Whether you want it or not 😮
@seanmcdonald656 Жыл бұрын
Fantastic video
@RalphBacon Жыл бұрын
Thanks! 😃
@gpTeacher2 жыл бұрын
Thank you for this series of videos Ralph. They're terrific! I've been doing an Ardiuino unit with my Grade 11s and they're SO Into It!. I showed them tone() on Thursday and you'd think they were Man being given fire by me, Prometeus! The music students immediately grabbed their Bach scores and started programming the kits to play symphonies. What have I unleashed? I'll be showing these two videos to my G12s in a couple of months so the future CS and CE students will have an idea before they get to university. I'd like a clarification. I use the "lastPressed = millis();" construct in my sketches for detecting button presses, but I define the variable as a global long type. What is the disadvantage of that strategy rather than the static variable defined in loop()? Thanks for helping me understand this. Best wishes, Gord
@RalphBacon2 жыл бұрын
Using globals (spawn of the devil etc) will, of course, still work. But unless the variable has to be _globally_ available, to several functions, then it has no place in the global namespace. Put it inside the function that needs it. One "disadvantage" of global variables is that they exist for the duration of the sketch and are thus allocated memory space. Temporary variables only exist for as long as they need to (but not static ones, they exist forever too). One final aspect to globals. It's an easy cop-out to define a global on the basis that a couple of functions need it. It's better to pass the variable (by reference, ideally) to the functions that require it. It makes the code self-documenting too. I suppose it's all down to how "tidy" you want the final program to be!
@Bob_Burton2 жыл бұрын
The timing variables should be *unsigned* otherwise at some point they will go negative and the timing comparisons will no longer work as expected
@gpTeacher2 жыл бұрын
@@Bob_Burton thanks for the insight Bob!
@byronwatkins25652 жыл бұрын
You also need a "doors closing" state and you need to queue calls from multiple floors. Your hardware should have a switch for each floor. Real elevators also need a limit switch to terminate the doors opening state and a safety switch to halt closing. These additions will require additional states and transitions.
@RalphBacon2 жыл бұрын
Not in this demo, Byron 😉 I did mention a missing state (DOORS CLOSED) at the end that we would just ignore as the "boredom factor" would otherwise assert itself. But it's good to see you're obviously on top of this State Machine malarky!
@computergururick8 ай бұрын
Great presentation
@RalphBacon8 ай бұрын
Thank you!
@Sembazuru2 жыл бұрын
That "default" case in the switch statement can come in handy if writing something horribly complicated as it can trap cases that you've forgotten or haven't gotten around to writing yet. Or just don't write the entrance case and let the default pick that one up (though I would consider that sloppy coding).
@RalphBacon2 жыл бұрын
Yes, the "default" can catch unexpected conditions and should always be implemented just-in-case, even if you are positive you've covered all bases!
@MaxStagsted2 жыл бұрын
I ALWAYS use the default case to raise "unhandled state" or similar exception, it makes that error so much simpler to debug. Never use it as a normal case.
@andrewkieran89422 жыл бұрын
Excellent! Thanks Ralph!
@RalphBacon2 жыл бұрын
Glad you liked it!
@TheTobi360 Жыл бұрын
Great video, thanks!
@RalphBacon Жыл бұрын
Glad you liked it!
@oscarfoxtrot992 жыл бұрын
err, I'll just get the stairs next time! - seriously it's all good stuff Ralph thanks for another useful video 😃
@RalphBacon2 жыл бұрын
We all need the exercise anyway! Did you know that in the USA a "lift" company, as it was then known, was so successful in installing their "elevator" brand that a "lift" became universally known as an elevator and they lost their patent to the name! 🤷♂️
@wilfredosandovaldelgado36902 жыл бұрын
That is a great way to program, when You need go betwin tasks, thanks for.
@RalphBacon2 жыл бұрын
You're welcome!
@RomanKuechler2 жыл бұрын
Great video. Very well explained. State machines are sometimes explained very differently on the web, as is the approach to programming it. This has annoyed me a bit in the past. Your video helped me a lot to better understand State Machines. Thanks very much. Now, I wonder if there will come a part 3?
@RalphBacon2 жыл бұрын
You really are a glutton for punishment, Roman! 😁
@RomanKuechler2 жыл бұрын
@@RalphBacon Don't worry - I think you've probably all said what mattters. I don't expect a third part. You really take your time with your explanations and I really appreciate that. This also sets you apart from many other electronics channels. Keep it up. Regards.
@pornpojhanhaboon99602 жыл бұрын
Hi, I always use fsm design technique. I prefer quantum-leap qm modeller free software to generate codes and modify them to use both without and with rtos ( freertos, ucosII/III). Another technique that is always used with fsm is event driven programming.
@RalphBacon2 жыл бұрын
Thanks for sharing! It's certainly a very detailed approach and in case anyone else is interested in using this software, here's the link: www.state-machine.com/qm/
@dafydds2 жыл бұрын
Hi, just wanted to say thanks for this video, as always, it's really great. I don't know why or how, but as I'm plodding through my personal coding project, your videos (and Github) lands some form of a gem and that makes me stop and think. This is just a case as I'm working on a PID/BBQ project and I've just started to look at the idea of having different temperature readers; but I need to know the 'state' of the PID/controller as well as the mode in which I'm readings temps (from what type of probe or API). So having 'states' I can clearly define, in English, what and where things are at... I find it quite funny really that your videos keep on moulding my project LOL. Thanks for these great videos!
@RalphBacon2 жыл бұрын
If my videos make you stop, think and adjust your approach to coding, my work here is done. Thanks Dav! 👍🏻
@SomeGuyInSandy2 жыл бұрын
Fantastic! I am working on a robot fed oscillating conveyor. The conveyor is driven by a closed loop stepper motor. I'm using a Controllino (Arduino clone) to coordinate the robot, conveyor, and the movement of another machine. It's going to be pretty trick when it's completed. Your videos are clear and concise, and because of them I understand enough of Arduino FSM to get me over the hump! Thanks :) By the way, do you have a suggestion of reading material that picks up from where your video left off?
@RalphBacon2 жыл бұрын
To learn more, Google is your best friend. There are many (advanced) videos on FSMs that go far beyond what I covered. TBH I think some of it is just too much theory over practical application, but one topic to consider is Hierarchical State Machines (ie State Machines within State Machines) which is most definitely required for larger programs to avoid State Explosion (yes, it's a real thing).
@SomeGuyInSandy2 жыл бұрын
@@RalphBacon Thank you. I will dive into those, and try not to get blowed up!
@SomeGuyInSandy2 жыл бұрын
@@RalphBacon So, in my travels with HSMs, the 'QP Framework' keeps coming up as the tool to use for embedded systems. Is this indeed something that is widely used? Do you recommend taking the time to learn it?
@lint20232 жыл бұрын
Very interesting. Thanks.
@RalphBacon2 жыл бұрын
Glad it was helpful!
@HandsomeDevil54448 ай бұрын
Great vid Ive understood that only void loop runs repeatedly so I thought switch case had to be in the void loop so why in the void toggle ylw ? I must not understand how the code runs.
@RalphBacon8 ай бұрын
If I understand your question correctly, we change the state variable so that on each iteration of the loop function, it jumps to the correct code for the current state. The loop function then just calls a (sub) function to do the heavy lifting, keeping the code nice and clean.
@TheUnofficialMaker2 жыл бұрын
Can a state be triggered by an interrupt? Let's say we have a snail mail monitor with a 2 line lcd that normally displays 'Waiting for Mail', followed by the time and date on second line.(State MsgMailWait). When the rf receiver receives the notification that mail has arrived (interrupt) , change msg to 'Mail Delivered' and time on first line, date and time on the second line as before. Would you just have a new MsgMailRx state?
@dozog2 жыл бұрын
For sure it can. Anything a button can do (change between states), the code inside an interrupt handler can also do. A simple way would be to let some code inside the interrupt handler set a flag (a boolean variable indicating the interrupt has happened) and the code in the state functions can read (and reset) that flag.
@RalphBacon2 жыл бұрын
What he said 👆🏻
@chrismolloy1312 жыл бұрын
Here is a link to an easy to use Finite State Machine library. Each state has an enter, update and exit functions.
@RalphBacon2 жыл бұрын
You can't post links here or your comment will be zapped. If you email me the link I'll add it here.