Understanding Finite State Machines (or Finite-State Automaton)

  Переглядів 7,849

Gary Explains

4 місяці тому

A Finite State Machine can, at any given time, be in exactly one of a fixed number of states. The machine can transition from one state to another depending some input data or event.

FSM's are sometimes called a finite-state automaton, finite automaton, or just simply a state machine.

Introduction to Android app development: www.dgitacademy.com

Let Me Explain T-shirt: teespring.com/gary-explains-l...

Twitter: garyexplains
Instagram: garyexplains

КОМЕНТАРІ
Michael Carnright
Michael Carnright 23 дні тому
Awesome! Reminds me of railroad diagram
Robin Holmes
Robin Holmes 2 місяці тому
Thank you! Python, Control logic?? Keep it coming :-)
Mark Stouffer
Mark Stouffer 2 місяці тому
The thumbnail seems to indicate a relationship between finite state machines and indexable fingers. I wanted to know about that.
SO 1291
SO 1291 3 місяці тому
WTH is the difference between "Red Amber" and "Amber" colors?
SO 1291
SO 1291 3 місяці тому
@Gary Explains Thank you for your reply :)
Gary Explains
Gary Explains 3 місяці тому
In Europe red/amber comes after red, whereas amber comes after green. That way when you see amber you know which direction it is going.
prabhat yadav
prabhat yadav 3 місяці тому
More is good 😄
prabhat yadav
prabhat yadav 3 місяці тому
Great explanation....🙂😀made complex term ...far easier...
Gary Explains
Gary Explains 3 місяці тому
Glad to hear that.
Fatimah Aljaafari
Fatimah Aljaafari 3 місяці тому
We want to see similar in C. If it for FSM for protocol will be great
Gary Explains
Gary Explains 3 місяці тому
I published the C FSM video already! 👍
Mark Keller
Mark Keller 3 місяці тому
*GARY!!!* Good evening Professor! Good evening fellow classmates! Stay safe out there everyone!!!
Gary Explains
Gary Explains 3 місяці тому
MARK!
Roger Andreassen
Roger Andreassen 3 місяці тому
Wouldn't mind at all to do this in another language. Wait.. Norwegian? Just kidding. But my teacher was a stickler for grammar as we did something like this on the BBC Micro and Turbo Pascal at the end of the 80s. We had bespoke norwegian made machines with around 220 Kb, the odd memory was for some graphics indeed.
jayk806
jayk806 4 місяці тому
Great explanation. Really inspiring, actually. Thanks!
Gary Explains
Gary Explains 4 місяці тому
Glad it was helpful!
Shan
Shan 4 місяці тому
yes AI + FSM + Python
excited box
excited box 4 місяці тому
yes MORE
Quarky
Quarky 4 місяці тому
C or Rust examples would be amazing!
Quarky
Quarky 4 місяці тому
@Gary Explains oh, I guess I missed the notification. I'll look for it! Thanks to UKposts's stupid recommendations, now I have too many channels with notifications enabled :(
Gary Explains
Gary Explains 4 місяці тому
I published the C one already 👍
Muddy Export
Muddy Export 4 місяці тому
RUST please.
Gregório Filho
Gregório Filho 4 місяці тому
It would be nice to have future videos on context free grammars and Chomsky hierarchy!
32bits
32bits 4 місяці тому
FSM in C and comparing to Python for a simple example would be usefull. Having written many large and complex progams running on MCU's without FSM's it would be good to know the best preactice process / steps for using FSM's.
Techno Projects
Techno Projects 4 місяці тому
FSM in C, thank you
Shah Jr.
Shah Jr. 4 місяці тому
Python FSM game please!
Shah Jr.
Shah Jr. 4 місяці тому
Python FSM game please!
devjock
devjock 4 місяці тому
This man just headfakes us all into compiler design, and it's beautiful!
Robert Baron
Robert Baron 4 місяці тому
@devjock I realize he is not explaining compiler design (see the original post for context), but he also doesn't mention the relationships between regular expressions and finite state machines, nor does he mention common applications that they are used in.
devjock
devjock 4 місяці тому
@Robert Baron You have a point that it's not quite there, but to be fair (and pardon me if this is very apparent, but) if he'd be explaining compiler design, then the video would've been named "Compiler design". Not making the connection is fine. These are soft-skills that will come to the surface whenever people do decide to take a course in compiler design, and subsequently, they'll pick up on the intricacies much better. RIght now it's handily packaged in an entertaining video, and the knowledge will hang around until it's needed. (insert witty reference to interrupt handling) But yeah, that's exactly why I called it a headfake. Gary makes us learn skills that are potentially useful in more than one field.
Robert Baron
Robert Baron 4 місяці тому
Sorry, Gary get gets close to, but not quite there. Sure, if you have had a course in compiler design, you already know this - however, if you haven't had such a course then I suspect making the connection is rather difficult.
Ray Lai
Ray Lai 4 місяці тому
Yes please do a video on FSM using GO... THANK YOU!
Trey Quattro
Trey Quattro 4 місяці тому
"sad puppy state" - that's where I live!
hybotics
hybotics 4 місяці тому
The "-1."or such as "`123." are valid. In fact, Python *does* accept these as valid.
IAmPattycakes
IAmPattycakes 4 місяці тому
FSMs are a basic but fundamental concept that's the backbone of most software. I'm not really the audience who needs it, but I'd like to see more videos like this that cover basic design principles. Or FSMs in Go.
Stepan S
Stepan S 4 місяці тому
Thanks Gary! I cannot find the code on github :(
Gary Explains
Gary Explains 4 місяці тому
A Google search for "Gary explains GitHub" should be sufficient. Here is the link github.com/garyexplains/examples/tree/master/FSM
John Schjetne
John Schjetne 4 місяці тому
FSM in C, please! Great video, thanks!
camryh salem
camryh salem 4 місяці тому
Fsm is everything
Daniel Glasser
Daniel Glasser 4 місяці тому
Additional videos on the topic would be good. I write my states rather differently, and have variations based on the nature of the input data. For lexical scanning like your number validation FSM, I would have the accepting states all transition to the "valid" terminal state on the EOI (end of input) state. All states would transition to the "error" state if any unrecognized input was received, and for the non-accepting states, EOI isn't recognized. It might be fun to show how FSMs of this sort are mapped to regular expression syntax, since an RE is often the best way to parse input tokens from a character stream. Of course, FSMs are useful for a lot of things that RE can't be used.
Markus Zeller
Markus Zeller 4 місяці тому
I was researching this topic a few months ago. Your examples and explanation is way better than anything I've found. Also your idea of using it for validation is awesome and gave me more inspiration to use it. Before knowing a FSM I just used jumptables or switch statements.
Markus Zeller
Markus Zeller 4 місяці тому
@Robert Baron Tnx. I am looking forward peeking in.
Robert Baron
Robert Baron 4 місяці тому
If you are writing finite state machines professionally, I would encourage you to consider using a tool like flex (github.com/westes/flex). The syntax is simpler and it will probably be more general and provable optimal for a given set of regular expressions ( the language that FSMs implement). For example, here is the lex example that does something similar (I'm not handling all of the error conditions): /* A simple example doing something similar to what * Gary did, but using lex to generate the DFA from * from a regular expression * * to build: * flex * gcc lex.yy.c */ %option noyywrap %{ #include #include #include #include %} %% ^(-[0-9]+|[0-9]*)?(\.?[0-9]+)?[ \t]* { printf("floating point accepted %s ",yytext); } [ \t]+ { /* skip whitespace */; } [ \f ] { /* skip blanklines*/; } .* { /* this matches everything that isn't matched above */ printf("ERROR: %s ", yytext); } %% int main() { yylex(); }
Marathi Gooner
Marathi Gooner 4 місяці тому
Would like if you did a some videos or a series on FSM for AI using python. If you could also explain some Graph Search Algorithms like RBFS in that series then that would be great
Larry Gall
Larry Gall 4 місяці тому
Where do you have "Red-Amber" before green? In the U.S. it's just green -> Amber, then Red (and back to green).
0x 52696368617264
0x 52696368617264 4 місяці тому
Same for Canada, except Quebec of course, where amber is just a decoration. No need for red-amber, red-green, or pink etc.
Gary Explains
Gary Explains 4 місяці тому
In Europe. It helps the driver know which way the traffic light will go next. If you see just amber then you know red is next.
Ashok Kumar
Ashok Kumar 4 місяці тому
Happy to get more content from you.awesome stuff sir !
Cédric Floquet
Cédric Floquet 4 місяці тому
Hi Gary. I was a bit surprised that you made a video about FSMs, but as a programmer I really enjoyed it, and I think you explained it very well. (btw I also enjoyed the videos you made a while ago about writing a "software CPU") I'd like to see more videos about FSMs, in C (which I know but I find the subject interesting) and Rust (which I barely know, and am curious about). I think a video about FSMs for Game AI in Python would be very interesting as well.
Gary Explains
Gary Explains 4 місяці тому
@Cédric Floquet Understood. Thanks. Yes programming videos are also part of my repertoire. I have videos on C, Rust, Python, linked lists, sorting, and more.
Cédric Floquet
Cédric Floquet 4 місяці тому
@Gary Explains I was surprised because I've mostly seen videos about hardware stuff (which I also like) on your channel lately. Even though there has been programming videos before, of course. But it was a pleasant surprise :)
Gary Explains
Gary Explains 4 місяці тому
I am glad you enjoyed it. Thanks for the feedback about future videos. One question, if I may, why were you surprised that I made a video about FSMs?
walkin mn
walkin mn 4 місяці тому
I´m learning Python so I would love more videos using it
middleclasspoor
middleclasspoor 4 місяці тому
This makes me so happy for high level languages! I don't know how you low level guys do it. I know this is an example of a fundamental computer science concept but if I had to program in this manner all of the time I would lose my mind! That's why I will never touch assembler! For me personally I don't care for anymore on the topic but the more sophisticated in your audience certainly may. Anyway, thanks for the great info. I'm really enjoying your channel!
RPG_ash
RPG_ash 4 місяці тому
Interesting!
cmdLP
cmdLP 4 місяці тому
What about PDA, push down automata, FSM extended by a stack. You could use it to verify/parse JSON.
Andrew D'Arcy-Evans
Andrew D'Arcy-Evans 4 місяці тому
Thanks Gary. If anyone wants a LOT more on this topic, this guy has 65 lectures on FSM ... ukposts.info/have/v-deo/hKV4p22On6J5uHU.html
Thaer Nejem
Thaer Nejem 4 місяці тому
Python games AI please
Mitchell Van Noy
Mitchell Van Noy 4 місяці тому
Second thought, I don't think a person who wasn't interested in this topic would watch the whole video and then comments after, they'd just move onto something else.
Mitchell Van Noy
Mitchell Van Noy 4 місяці тому
I've never heard of FSM, I'd watch a second video on this topic
Fabio Salles
Fabio Salles 4 місяці тому
Hey Gary please just keep on using Python! 😁👍🏼
Chud Chadanstud
Chud Chadanstud 4 місяці тому
Imagine using python for fsm lol. The absolute state of python. They're regretting not having switch cases. You don't need to think with swtch-cases
Chud Chadanstud
Chud Chadanstud 4 місяці тому
@Laxman Nikhil awesome. Looking forward to it. Will definitely play with it.
Gary Explains
Gary Explains 4 місяці тому
@Laxman Nikhil I haven't looked into the up coming changes, but I read that the switch won't work like other languages. Do you have any insights or experience about that?
Laxman Nikhil
Laxman Nikhil 4 місяці тому
Just an FYI python is getting switch cases in PEP 662-Structural Pattern Matching, www.python.org/dev/peps/pep-0622/. It is expected to be arriving in Python 3.10
Chud Chadanstud
Chud Chadanstud 4 місяці тому
@Gary Explains Lol you caught me, not a big fan of python, especially its dynamic nature, too many uncertainties. I'm just saying it's a lot easier for beginners to get up and running with FSM in other languages except for python. Using pointers and enums for FSM in embedded C, a main function can look like this: void main() { while(1) { (*stateMachine[currentState].stateFunc)(); } }
Gary Explains
Gary Explains 4 місяці тому
@Chud Chadanstud Enums are just auto assigned integers. I could have used integers or Python's enum. That isn't the point. You made a snide comment about using Python in favour of a language with a switch statement. You shouldn't have. A switch is the worse way to make an FSM: hardcoded, unreadable, unmaintainable, and certainly not elegant.
Flankymanga
Flankymanga 4 місяці тому
I think finite state machines are very important in device firmware thus showing one written in C for the audience would be beneficiary.
Laxman Nikhil
Laxman Nikhil 4 місяці тому
What a timing! I just started Cpython internals book which talks about Finite State Automaton very briefly. You video made it much more clear. Thanks Gary
James Goacher
James Goacher 4 місяці тому
I have used this for probably ALL my working life, wasn't called FSM though it was called Logic. Initially Relay Logic then Solid State Logic, then PDP8 then PLC(Ladder or CSF) and then Computer directly. Then retirement. I have drawn a State Machine for a Client but only after the fact. The Loop Back was illustrated by a on the connecting line btw. Problem with basic State Machines is that they insist upon only a single change in State whereas my field of Machine Control often requires multiple Branching and coming back together. That requires passing to another State Machine (not sure why 'Finite' in there), not sure at this moment how you would comeback together. I preferred roughing out a program using a sort of pseudo 'C' in which what you are showing would probably be a 'Case' statement. I am almost twenty years out of date now and certainly not 'Current' and Python has come along during that time and do not like it very much. Try a version of 'C' or Assembler (my preferred) and by inference the Arduino version of 'C'. The machines I wrote Control for could quite happily mangle you or more importantly the Operator very badly so this is not a flippant subject for me.
James Goacher
James Goacher 4 місяці тому
That is a lot of information and I wxpect I know most of the things you are referring to by different descriptions. I am not comfortable with expressive abbreviations and those things which sound cute as well so I just use them as is. I do not prefer Ladder Logic if there is a choice. Seimens PLC, which I used often had a Logic Block Form and a sort of Assembler form They called them Control Flow System (CFS) and Statement List (STL) which were far more flexible and "Leaner". The last version I used almost twenty years ago, S7 could even be considered Object Type with a bit of imagination using local and global variables very nicely. I do not recall a State Machine type of function. I created Step Functions (the design is within their literature) with Set/Reset blocks formed into Sequence Steps with the time critical stuff going off in dedicated modules and in the background. I do not believe that you can get a meaningful timer of less than a tenth, maybe 0.05 with a PLC without very careful program layout because of the Scan Time Issue. The last time I added a scan time indicator into a program (using an S5-115 generation unit at the basic end of the range) where I was concerned about reaction time and wanted to check before I decided to use an expensive interupt type module it was about 15ms and I only need 30ms so I stayed with the cheaper solution. Processors are much faster nowadays up from 4.77MHz to lots of GHz now so I expect that PLC have speeded up too. My current knowledge of the subject remains the same as twenty years ago, not kept up-to-date. I will read your reply again more carefully. It was interesting.
Daniel Glasser
Daniel Glasser 4 місяці тому
Ladder logic is used to implement state machines. Sometimes many simultaneous state machines. Ladder Logic also deals with analog signals pretty well, whereas most FSM you're going to see written in Python will be dealing with far less complex "real world" situations, since the beginner is not really ready to deal with hysteresis, feedback loops, and process control timing, where a difference of 0.0002 seconds (200 microseconds) might be the difference of diverting a bottle on a conveyer that failed visual inspection into a reject bin or kicking the bottle so hard that it smashes on the wall (or hits a factory worker if you're very unlucky). I have great respect for PLCs, Logix controllers, and other such devices, and for the people who program them well. I studied various forms of state machines in college, did some embedded programming and compiler development in various jobs after college, and over the years, most of my significant work involved extensive use of state machines. It was about 20 years after I graduated from college that I first started working with PLCs, but I picked it up pretty quickly. Still, it took me a while so that my code could compensate for cranky pneumatic actuators that changed performance significantly from when the bottle inspector was turned on to about 15 minutes of running once the rubber pressure hoses had stopped softening. The reason they're called "Finite" is because there are a countable number of defined states the state machine can be in. There are many kinds of FSMs, ranging from simple accepting automata which have a single "start" state and have terminal states, and really don't branch a lot, but there are much more complex FSM. Often, it is easier to create multiple linked state machines, each having its own independent state, but with synchronization points where they can affect one another. Deterministic Finite Autonoma (DFAs) are predictable and will always behave the same for a given set of inputs, but there are other kinds that, although the state transitions are well defined, the outcome for a given set of inputs can be different based on some external influence such as a random number generator. There are push-down autonoma that have a state stack (Turing machines), "Finite State Machines with Oracle" that depend on an external process to determine state changes, and so on. Regular Expressions are "Accepting Finite State Machines", and are good for parsing serial input data. My typical FSM for power sequencing of a circuit board defines each state in terms of the entry conditions, a list of actions to take on entry to the state (handled by an "enter state" procedure), a list of exit conditions each with the state that condition causes transition to, and an "evaluate" procedure that is called or event (timer, interrupt, etc.) handling, and in which the exit conditions are evaluated and the exit handling and transition to the next state is signaled when a matching condition is found. In C or Assembly, all states are represented as 'structs' that have function pointers for the "enter state" and "evaluate" entries (some also have a "reset" function pointer), and the FSM is driven by an outer "super-loop" that may run multiple parallel FSMs for different purposes (eg, asynchronous communication, watchdogs, key decode, A/D, etc.). What I do is often safety and time critical, and frankly, a "switch" statement isn't going to cut it. I always start out with a directed graph of the states, labeling all of the edges with the conditions under which the that edge is followed. A lot of analysis gets done on the graph before the first line of C code is written, though typically, the graph gets modified as the interactions between the FSM implementation and the hardware it runs in become better understood. After burning out a few $800.00+ FPGAs, you learn to be very careful about FSM design. Many real-world FSM are most easily documented as a set of macro-states which are each smaller FSM made of of "micro-states". In these cases, rather than having a lot of parallel FSM that interact, you can think of it as either a birds-eye-view of a single gigantic FSM or an FSM made of "black box" states that are much simpler than the top-level FSM in which they exist. I'd much rather do formal documentation for 16 FSM each with around 10 states than one FSM with 160 states.
Alain Graham
Alain Graham 4 місяці тому
Part-time traffic lights (they do exist) have an end.
marsch
marsch 4 місяці тому
These are totally underrated!
marsch
marsch 4 місяці тому
@Gary Explains Also check the Xstate JS/TypeScript lib, it's really nice and has a cool SM visualizer
Gary Explains
Gary Explains 4 місяці тому
Tell me about it! 😊
Durragas
Durragas 4 місяці тому
I should be studying for my Digital Systems exam but I'm browsing UKposts instead. Then I see this video. Perfect timing.
Gary Explains
Gary Explains 4 місяці тому
Now you can do both!!! 😁
Wayne Stewart
Wayne Stewart 4 місяці тому
Python FSM for Game AI. That would be awesome.
SpaceFace102
SpaceFace102 4 місяці тому
I would like to see this applied in C!
SpaceFace102
SpaceFace102 4 місяці тому
@Tech Byte Nothing, but I would like to see how Gary goes about coding it. Maybe I'd learn a thing or two!
Chud Chadanstud
Chud Chadanstud 4 місяці тому
It's already in C and its 1000x easier. Just use switch statements.
Tech Byte
Tech Byte 4 місяці тому
Who is stopping you from doing that ?
Curious Cat
Curious Cat 4 місяці тому
More please!
Shubham Bhushan
Shubham Bhushan 4 місяці тому
More Videos on CS topics please. And in python
Johny Bro
Johny Bro 4 місяці тому
Maybe more real world problems with fsm and then move onto the game?. Bcoz I feel like it would be too complex.
Shehryar Hussain
Shehryar Hussain 4 місяці тому
Hey Gary, In few days I will have an exam for digital system and I'm revising for fsm and can't believe you uploaded this video. Thank you. Will watch this to understand it better.
Gary Explains
Gary Explains 4 місяці тому
Best of luck!
Lester
Lester 4 місяці тому
Thank you!
Gary Explains
Gary Explains 4 місяці тому
You're welcome!
Z3U5
Z3U5 4 місяці тому
*One of the most complex yet important topic in Computer Science.*
Ashwani Rai
Ashwani Rai 4 місяці тому
Hi garry thanks for this topic was wondering for a video where how regular expression are implemented. Not how to use matcher in java or c rather how to write own regular expression matcher logic .
Wi-Fi Glossary and Terminology - Jargon Buster
28:06
Gary Explains
Переглядів 10 тис.
A-Level Comp Sci: Finite State Machine
8:21
justAlevel
Переглядів 44 тис.
БЕРЕМЕННА В 16 ► НАСТЯ из МЫТИЩИ
1:23:58
CheAnD TV - Андрей Чехменок
Переглядів 462 тис.
София - Болгария | Жизнь других | ENG | 19.09.2021
43:34
Жанна Бадоева Жизнь Других
Переглядів 233 тис.
Apple A15 Bionic Will Use ARMv9, Probably!
10:45
Gary Explains
Переглядів 55 тис.
Qualcomm just bought startup founded by Apple's chief CPU architect
10:04
How CPUs and Processors are Made for Smartphones, Laptops, and Desktops
25:05
NTFS vs FAT32 vs exFAT - Everything You Need To Know
14:16
Gary Explains
Переглядів 28 тис.
What is Wi-Fi 6? (feat. Honor Router 3)
16:15
Gary Explains
Переглядів 15 тис.
Linux Directories Explained - including /etc /home /var /proc /usr
13:39
Gary Explains
Переглядів 26 тис.
Finite State Machines explained
14:13
Abelardo Pardo
Переглядів 432 тис.
Cortex-A510 - New Armv9 Power Efficiency Core for Smartphones
12:51
Gary Explains
Переглядів 11 тис.
L1: Introduction to Finite-state Machines, Regular Languages
1:05:58
UC Davis Academics
Переглядів 10 тис.
БЕРЕМЕННА В 16 ► НАСТЯ из МЫТИЩИ
1:23:58
CheAnD TV - Андрей Чехменок
Переглядів 462 тис.
София - Болгария | Жизнь других | ENG | 19.09.2021
43:34
Жанна Бадоева Жизнь Других
Переглядів 233 тис.
2 тиждень - Танці з зірками. 8 сезон
3:6:10
Танці з зірками
Переглядів 471 тис.
СЕРГЕЙ ОРЛОВ и ГАРИК ОГАНИСЯН в DZK
54:23
ЛЬВЫ НА ДЖИПЕ
Переглядів 262 тис.
НИКТО НИКОГДА не был В КОСМОСЕ - ТОПЛЕС
37:21
Джамбулат Маг
0:58
КАХА MEDIA
Переглядів 2,6 млн