VIEWS: 5 PAGES: 38 POSTED ON: 9/2/2011
Chapter D Finite State Machines D1 The Notion of a State Finite state machines (FSMs) provide us with a very useful way of understanding systems which change at discrete events in time. The system could be a robot navigating through some obstacles, the behaviour of a cat or the functioning of a vending machine. Even speech recognition can be described as a FSM, or the machine translation (“parsing”) of Java source code to ultimately produce a running program. Also FSMs are fundamental in understanding what “computation” actually is from a theoretical perspective, more on this in Chapter ?? For the moment we shall consider a number of examples of FSMs, how they can be represented all the way from high- level symbolic diagrams to the lowest level of digital electronics. And we shall also see how biological systems implement FSMs. Let’s start by considering the states of Tom cat, a few of which are shown in Fig.1 . Figure 1. Here’s some pictures of Tom existing in a number of states, each with its own particular “activity” (output or response). There is hunting, hiding, sleeping and scratching. These are of course behavioural states, walking, sleeping, burying, hiding, grooming. Catch Tom in the garden and you’ll certainly find him in one of these states. But he does not stay in a single state for very long; he may be grooming until a mouse comes along. Tom will then make a transition into a new state, probably hunting, jumping or just plain being silly. The transition is caused by Tom receiving the input stimulus of catching sight of the mouse. The new state has an associated output or response, the actions associated with hunting. If we observed Tom for a significant period of time, we may well discover that we could describe his entire total behaviour as a collection of a limited (finite) number of states. We represent a state as a circle containing a label and the output behaviour of Tom associated with the state. Each state is linked to another state by one or more transition arrows, and each arrow would be labelled by an stimulus which would cause that transition between the states (see Fig.2). Moving from one state to another would only occur on receipt of the particular stimulus without debate or probability. The system is mechanical. Moreover, once the system is constructed it is complete in that Tom can never exist in a state we have not included in the diagram. But if we did find a new state in our analysis of Tom’s days, then of course we could extend his FSM. See dog S2 Hear noise hiding See dog S1 hunting See mouse See mouse See dog S5 playing S4 S3 cleaning wandering Feel bored See friend Feel an itch I’m tired Hear noise S7 scratching S6 sleeping Feel an itch Figure 2. An analysis of the life of a living Tom cat into states each with their associated behavioural activity, (“output” or response). Transitions between Tom’s states are shown by arrows labelled with the stimulus producing the transition. Each oval represents a state of behaviour: It is labelled with a state name and also the response output by each state Tom, represented by a Finite State Machine, lives in an environment. This is important, since this environment provides the stimuli inputs to the FSM and also is the arena in which the response behaviour is actioned. It is clear that this model is general: A soft-drink dispenser modelled as an FSM exists in an environment of customers, a robot-controller FSM exists within an environment of obstacles, a speech-recognition FSM exists within an environment of input spoken words. So we suggest that a natural system can be analysed into and FSM and an environment, and that the states and transitions of the FSM together with stimuli and responses, may be used to visualize, simulate and therefore understand its properties. Whether or not this is successful depends on the accuracy of our analysis. On the other hand the engineer, who has the freedom to construct a system (such as a soft- drink dispenser) from scratch, will be able to construct a perfect FSM to solve a particular problem. D2. The Definition of a State Machine The basic concept of an FSM is shown in Fig.3. The FSM is presented as a “black- box” (that’s the square which hides the details of the exact operation), situated within. The FSM is situated in an “environment” from which it receives input. stimuli (S) and to which it provides outputs or responses (R). The FSM consists of a number of states, labelled Q1,Q2,… Each state can be configured to receive one or more stimuli. On receipt of a particular stimulus the FSM can change state, e.g., from Q1 to Q2. Upon that transition into Q2, the output of the FSM becomes R2, associated with Q2. This replaces the previous output R1, associated with the previous state Q1. So as time unfolds, the FSM jumps between states with associated outputs, driven by input stimuli. FSM (a) Basic structure of a FSM. The Q2 square box contains the FSM Q1 which exists in a number of states S R Q1,Q2,Q3. The FSM is situated Q3 within an environment which provides input stimuli (S) to the FSM and which accepts the FSM’s output or response (R). Environment FSM Q1 S R Q2 (b) All states are able to receive the input stimuli, the response Q3 comes from the output of only one state, here Q1. FSM Q1 S R Q2 (c) Here an input stimulus has caused the FSM to change state from Q1 to Q2, whereupon the Q3 FSM outputs the response R from Q2 Figure 3. Structure and operation of a FSM. Think of the FSM as a “black box” which lives in an environment receiving input stimuli and emitting an output response The description is “deterministic”, there is no randomness or ambiguity of the output. There is a clear and well-defined movement between states and their associated outputs. There are several ways of representing a FSM. In this chapter we shall discuss several of these. Perhaps the easiest to understand is the “State Diagram” notation we introduced with Tom. This is graphical and represents states as circles and transitions as arcs, Figure 4. The state is labelled with a name (Q1,Q2,… or anything you like) inside the circle. The output associated with the state is also indicated in the circle, here shown within square brackets, e.g. [R1], “response 1”. Transitions between the states are labelled with the stimulus “S” which causes the transition. Finally, there are two special states, the starting state for the machine, indicated by an arrow onto the circle, and the end state, indicated by a double circle. Note that some FSMs (such as traffic-light controllers) do not have an end state, but run continually through some sequence of states. S Q1 Q2 Q1 Q2 [R1] [R2] [R1] [R2] (a) (b) (c) Figure 4. State Diagram notation. (a) States are shown as circles connected by arrows indicating which stimulus S causes a transition between the states. Each state is labelled with a name (Q1,Q2,…) and also the output or response which that state produces. This is enclosed in square brackets, [R1], [R2],… There are two special states, (b) the initial state indicated by the arrow and (c) the final state indicated by a double circle. We should also mention here that there are two “flavours” of FSMs, “Moore” and “Mealy”. The distinction between these will be discussed in section D18 and centres around when a new output is generated. The Moore machines (which we shall be using in the following examples) associates an output with a state. Mealy machines associate an output with a transition between states. D3. A Door Combination Lock Let’s take as our first example an electronic lock controlling entry to a door. I’m sure you’ve seen these locks, a polished aluminium box next to a restricted-entry door with keys labelled 0 to 9. Well’ we’re going to take a simpler (though equally powerful) keypad comprising just two keys, “0” and “1”. That sounds rather binary! The system is sketched in Fig.5(a) The binary keypad provides inputs S to the FSM which must decide whether the correct input sequence of 0s and 1s has been entered. Let’s agree that the entry code is the 4-bit sequence “0110”. If this sequence has been correctly input to the FSM, then the FSM moves into its end-state where it outputs a “1” or “open” command to the release mechanism (a solenoid operated lock). Any incorrect sequence outputs a “0” which means “do not open”. 0 0 open input FSM Release (a) 1 mechanism 1 Q1 0 Q2 1 Q3 1 Q4 0 Q5 (b) [0] [0] [0] [0] [1] Q1 0 Q2 (c) [0] [0] 1 Q1 0 Q2 [0] [0] (d) 1 0 Q1 0 Q2 1 Q3 [0] [0] [0] (e) 1 0 0 0 1 1 Q1 Q2 Q3 Q4 0 Q5 [0] [0] [0] [0] [1] 0 1 0 1 (f) Figure 5. FSM description of a door lock. (a) Shows the system structure and (b) – (f) shows stages in the development of the FSM State Diagram (see text). Starting in state Q1, the FSM will move to the ends state Q5 if the correct sequence of binary digits “0 1 1 0” is entered at the keypad. All states output “0” except Q5 which outputs a 1 to the release mechanism. Let’s work out how to build the FSM “State Diagram” in stages. First we have to work out how to detect the correct key sequence. This is easy, we need to detect a “0” then a “1” then a “1” then a “0”. This sequence can be represented as a straight linear graph of five states, see Fig.5(b). From the starting state, each correct input stimulus advances our journey, from left to right, along the stepping-stones of the states until we reach the end state Q5. Note that this state outputs the response [1] which signals the release mechanism to “open”; all the other states, Q1,… Q4 output the response [0] which clearly means “do not open”. Let’s reflect a moment on what these states represent: Q1 We have not received a “0”. Erroneous “1’s” have been keyed in Q2 We have received a “0”, the first correct key code Q3 We have received a “0” and a “1” correct two key codes in the sequence Q4 We have the three key codes “011” Q5 We’ve finally got everything “0110” This state diagram can recognize the correct sequence of input digits. But it cannot yet respond to an incorrect input, such as 0111. We must augment this basis state diagram with transitions which will handle incorrect input digits. The first incorrect digit will be a “1” instead of a “0”. When we are in Q1 If we input a “1”, then we must not allow the FSM to progress to Q2, we must return to Q1. So we augment the original FSM with a loop from Q1 to Q1 which is invoked on receipt of input “1”. This is shown in Fig.5(c). What about the next possible error? Assuming we have entered the correct first digit “0”, and so we are in state Q2 we are expected to enter a “1”, but let’s say we enter a “0”. What do we do? There are two options, first we could decide that the entire key code entered was incorrect, so we could return to state Q1 and start afresh. But we don’t need to do this. We have entered “00”, so we could interpret the second “0” as the “0” beginning the correct sequence “0110”. In other words, we should return to Q2, since this second (erroneous) “0” is at least a valid “0”! So we add the transition shown in Fig5(d) back to Q2. So let’s assume that we are in Q2 and then we input a “1” which brings us into state Q3 (that means we’ve correctly input “01”). Now we are expected to input a “1” (the next digit in the code sequence “0110”). If we input a “1” then we proceed to Q4 “010” but once again we err and input a “0”. To which state should we transit? Again or last input “0” could be interpreted as the start of the sequence “0110” so we return to Q2 which has recognised the “0”, Fig.5(e). Sooner or later we shall triumph over our forgetfulness and arrive in state Q4 where we have entered “011”. There is one more digit to go. If we enter “0” we proceed to Q5 and the door opens, but, no we key-in a “1”. So to which state do we transit? Well, we have entered “0111” There is no way in which any part of this string can be considered to belong to our desired “0110”, so there is but one choice, to return to the start, to state Q1. The complete state diagram for the door lock is shown in Fig.5(f). D4. A Parity Checker Our second example of a FSM is a parity checker. Of course, before we get to grips with the FSM we must understand what “parity” means. Parity is a useful concept used in transmission of data across a communication channel, like a serial connection, a USB port or an internet conversation. We know that all data and instructions are encoded as numbers, which at the fundamental level of electronic signals are present as “bits”. So, for example a the color of an object on a web age may be encoded as the hexadecimal number FF0000 (pure red, see chapter 1) which in binary is 1111 1111 0000 0000 0000 0000. This “stream” of 24 bits appears as an input (stimulus) to our program (FSM) and we must process these bits. One important processing function is to count the number of “1’s” in this incoming bit- stream. This count or “parity” can be used to check if there has been any error in communication. For example, if the communication protocol has been agreed to send a bit-stream comprising only odd-numbers of bits set to “1”, then we may check the data on receipt, to see if there is an odd number of high bits. If there is not, then an error has occurred in the communication channel, and we must then request that the data be re-sent. In this example we consider the case of odd parity. Any correctly received bit- stream must contain an ODD number of “1s”. The FSM must output a “1” whenever the bit-stream contains an odd number of “1s”, else it outputs a “0”. The block diagram description of this problem is shown in Fig6(a). The input stream of binary digits enters the FSM which analyzes this stream and outputs a message “odd” when the parity is odd. 0 Odd number Input stream Of 1s Output FSM Message 1 “odd” 1011011 (a) 1 Even Odd [0] [1] 0 (b) 0 1 Figure 6. Parity Detector FSM. (a) shows the general system structure, (b) the State Diagram describing the FSM. On input of an even number of 1s, the FSM will be in state “Even”, an odd number will place the FSM into state “Odd”. The FSM “State Diagram” is shown in Fig6(b). We start in the state “Even” which means zero bits received. There are two possible inputs or stimuli, “0” or “1”. If we receive a “0” then we return to the state “Even” (since “0” is an even number). But if we receive a “1” then we transit to the state “Odd” and we output a “1” indicating that we have found odd parity. In this state, any received “0” does not change the number of “1s” received and so the parity; we remain in state “Odd”. But if we receive a “1” then we have received in total two 1s, and so transit to the state “Even”. Clearly this FSM is capable of “counting” the number of 1s received, and if this is an odd number will output a “1”, or if this is an even number, will output a “0”. I guess’ you’ll figure out some other uses for this circuit. D5. Traffic Lights Let’s consider a problem in control engineering where an electronic controller, perhaps using a microprocessor, must be built, to control a set of traffic lights at a road junction. There are also sensors a and b placed on the roads A and B which respond to cars arriving there. The idea is that if the lights on road B are red, and a car arrives at sensor b, then the lights will cycle through a change so that B gets a green light. Road A behaves in the same way. This is sketched in Fig.7(a). To construct a FSM controller, we must first enumerate the smallest number of states we shall need to use, and to do that we go and find some traffic lights and observe them. Fig.7(b) shows the states (a) b B a A TO TO a Q1 Q2 Q3 Q4 (b) TO TO b TO TO Q8 Q7 Q6 Q5 Figure7. (a) Traffic Lights at the junction of roads A and B. Sensors a and b detect the arrival of a car at the lights on each road. (b) Finite state diagram showing the symbolic state of each pair of lights (left is A right is B) together with transitions which move between states. “TO” is a timeout (delay) stimulus provided internally by the controller. Input stimuli “a” and “b” are produced by the respective road sensor. Now for the transitions between the states. Some like Q2 -> Q3 Q4 -> Q5 are produced by the timeout delay circuits. These “timeout” transitions are indicated in Fig.7(b) as “TO” Now we must handle the stimuli from the road sensors. Let’s agree to start in State Q3 where cars are freely flowing along road B and let’s assume that no cars have arrived at a. Then a car arrives and triggers the sensor at a. This will make a transition from Q3 to Q4 to begin the cycle of light changes. States Q4 and Q5 are linked by the timeout and so are Q5 and Q6. Another timeout and the system is in state Q7 with traffic now halted on road B and flowing freely on road A. Then, when a car arrives at b it will trigger a transition Q7->Q8 and the dual steps of timeout will follow to get the lights back into state Q3, where the traffic flow will resort to its original state. There is an obvious limitation to the controller designed above; it responds immediately to cars arriving at its sensors which would interrupt reasonable traffic flow by a rapid switching of lights. Some delay needs to be build in between the receipt of a road sensor stimulus and its use to trigger a state change. An alternative would be to count the cars arriving at the sensor, and trigger a transition when this is above a threshold. D6. Counting People Entering a Room Here we wish to design a system which will count people entering and leaving a room, and at any time know how many people are in the room. We assume there’s an electronic entry and exit sensor near the doorway which generates events for our FSM. The simplest approach is shown in Figure 8. Here, an “in” event will cause a transition to the next state down the line, and each “out” event will return to the previous state. Each state outputs the count it represents. There is of course one problem with this FSM. At the moment we can only count up to 5 people. If we want to count more people, then we need more states. But what about the situation where we cannot know the number which has to be counted? This FSM cannot cope with this problem, and remain “Finite” in size. We’ll return to this in Chapter ?? when we discuss an extension of the FSM description into “Turing Machines”. 1 1 1 1 Q0 Q1 Q2 Q3 Q4 [0] [1] [2] [3] [4] 1 0 0 0 0 Figure 8. Counting people entering and leaving a room. Input S=1 is produced by a sensor when someone enters, input S=0 when some one leaves. Each state can output the number of people in the room at any time. When the output R=0, then the lights can be switched off. Note that this FSM can only count up to 4 people. D7. The usefulness of Finite State Machines Before we consider some further examples, it’ stime to sit back and reflect on the usefulness of FSM’s. Sure we have constructed some nice graphical diagrams to capture the behaviour of some systems, but what can be do with these? Let’s address this question here, and summarise the most important characteristics of FSMs 1. They give us a simple and intuitive way of describing a system which has discrete dynamics (that’s our State Transition Diagrams). 2. They give us a complete and unambiguous way of describing a system 3. An FSM is an “abstract machine” That means that we can make a mathematical description of the machine reason about its behaviour without actually building it. 4. Since the description is mathematical, we can use mathematical proof to be sure of the functioning of the machine. 5. They can be directly and unambiguously converted into a computer program (e.g. via the “SDL” language). 6. They can be directly and unambiguously converted into a digital electronic circuits. Wow, that’s something, but what does this all mean? Well, simply that you’ll see FSMs everywhere from now on! But of particular interest to the engineer are points (5) and (6) which tell us that if we can construct a FSM for a system, we can directly generate the computer program or digital electronic circuit which will make that system work: The above traffic-light FSM can be concerted into an electronic circuit to run the traffic-lights, and so can the door counter. Also the examples we shall soon see concerning recognition of words in sentences can be directly converted into computer programs. We shall return to discuss the mathematical aspects in chapter?? D8. Acceptors and Transducers - Recognising Laughter Imagine a microphone connected to your computer which was programmed to recognise whether someone was laughing in the room. It would have to recognise “Ha!”, “HaHa!”, “HaHaHa!” and so on. This is quite easy and could be constructed using the FSM shown below, where we assume that the FSM gets a series of characters as its input events. Have a look at Figure 9. From the starting state Q1, it may only exit if a “H” is observed. If any other character is received, (which is not an “H”) then it returns to itself, that’s the loop labelled “~H” where the tilde “~” is the logic symbol for “not”. Having received an “H” the FSM is in state Q2. If the next character received is then an “a”, then the machine proceeds to Q3. But any other character does not fit into the required substring Ha and so a transition back to the starting state must be made, this is labelled “~a”. Once in state Q3 three things can happen; (i) a “!” is received signalling the end of the “Ha”, in which case we exit to the terminal state Q4, (ii) a “h” is received in which case we return to Q2 in expectation of an associated “a”, or (iii) any other character is received in which case we have an incorrect string and we must exit to S1 the starting state. This FSM only outputs a response R=1 when it has recognised a specific pattern of input stimuli. Such FSMs are called “acceptors” since they are built to accept one or H a ! Q0 Q1 Q2 Q3 [0] [0] [0] [1] ~H ~a h ~(! or h) Figure 9. FSM for recognising laughter. From Q0 an input “H” transits to Q1, any other character returns to Q0. From Q1 we move to Q2 on receiving an “a”, which means we’ve got “Ha”. But if we don’t get an “a” then we return to Q0 to start afresh. From Q2 we accept either a “!” to signal we’ve received a single “Ha!”, or if we get an “h” then we recycle to Q1 in wait for an “a”. Anything else, then back to the beginning. This FSM recognises strings such as “Ha!”, “Haha!”, “Hahaha!” etc. more input strings. The door combination lock discussed in section D3 is another example of a acceptor. But we have also seen examples of FSMs which output a value at every state, like the people-counter in Section D4 Here the input stimulus was converted or “transduced” into a numerical value. So there are two classes of FSMs, “acceptors” and “transducers”. D9. Recognising Text – A Computer Program Parser When we write a computer program, we produce a bunch of text which is input into a compiler or interpreter which must ultimately convert this into a series of instructions which the CPU can execute. The part of the compiler which does this is called the “parser” and is fed by a stream of input characters and must “parse” this stream into a series of tokens which can be used to generate the machine code. There are also special symbols such as the semicolon, well-loved by C and Java programmers, whitespace “ “ and brackets “[“ and “]” familiar to us from out work on the Sam-2 CPU in Chapter 2. Let’s sketch here a simple FSM to parse the “mov ax,[3]” type of instruction we encountered in our Sam-2 work. There are various possible patterns we have to recognise: mov ax, [addr] mov bx, [addr] mov [addr], ax, mov [addr],bx We assume that we have a method in out program which can detect the tokens “mov” and “add” (that would be another FSM which would like the Laughter-detector above). A partial state diagram for this problem is shown in Fig.10. Q8 Error [e] ] Q7 ~ax or ~bx addr mov ax , [ Q1 Q2 Q3 Q5 Q6 bx , [ Q4 Q9 Q10 addr Figure 10. Acceptor FSM for parsing either “mov ax,[addr]” Q11 or “mov bx,[addr]. The error state is shown only receiving a transition “~ ax or ~bx”, ie if neither “ax” or “bx” have been ] recognised. Other states transit to the error state if their indicated input S is not received. Q12 Q1 The starting state is a new line of code From here if we receive a “mov” token then we transit to Q2 which represents “mov” received From here if we receive an “ax” then we transit to Q3 or if we receive a “bx” then we transit to Q4. If we receive anything else, we transit to SError which records the fact that there is a “syntax” error in our code and outputs an error message. Q3 We have parsed “mov ax” Q4 We have parsed “mov bx” From Q3 if we receive a comma “,” then we proceed to Q5 else we proceed to SError From Q5 if we receive a “[“ then we proceed to Q6 else we proceed to SError In Q6 we must receive a number “addr” we go to Q7 else we proceed to SError From Q7 we must receive a “]” to put us in Q8 Q8 Correct parsing of the code “mov ax,[addr]”. This outputs R = 1. A Similar chain of events leads us from SQ to S=Q12 which have parses the code “mov bx,[addr]” And further chains could be used to parse the other possible lines of code of the form “mov [addr],ax”. D10. Counting Brackets We’ve already seen one “counting” example, people entering and leaving a room, so why are we looking at another “counting” example? Well, this is fundamental to computing, especially programming. It’s also fundamental to mathematics, which is closely allied to theoretical computing. So what are brackets? They are convenient symbols which enclose something. There is a left “bra-“, the symbol “(“ and a right “- ket” , the symbol “)”. Together the make a “bra-ket”, the symbol “ ( )”. I.e., they should only come in pairs. What can we place within this bra-ket? Well, we can write “(3 + 1)” and we all know that this means “4”! What about this expression, “5 x ( 3+1)”. What does this equals ? It’s faily obvious that we must first do the “3+1 = 4”, and then do the 5 x (4) = 20. Yep that’s right! The bra-kets tell us what to do first. So bra-kets are a way of ordering our processing in sequential stages. Let’s take another example. What does “((6+7) x (5+3))” mean? Well the “(6+7)” are bra-keted which means that we must first do this sum, (6+7) = 13. Then the “(5+3)” are bra-keted which means we must also do this sum, (5 + 3) = 8. So we replace these bra-kets with their arithmetical results and get 13 x 8 Which gives us the result 101. Here’s another example for you to ponder upon. What is the value of ( (4 +1) x (5 x 2)) ? Yep, it’s 50! Great, well done! But look at the structure of the above expression. We have ( (b) x (c) ) where “(b)” is the intermediate calculation “4+1” and “(c)” is the intermediate calculation “5x2”. The outer bra-kets in “( … )” in “( ()() )” combine these intermediate results, in this case multiplying the 5 ( which comes from 4 +1) with the 10 (which comes from the 5x2) to give the result 50. In other words, bra-kets give us a symbolism to help us carry out the correct computations in the correct order. So what? Well, if you look at the examples provided above, you will see that the number of bras equals the number of kets. If we have two “(“s in an expression then we have two “)”s. So an expression ( (3 + 1) x ( 3 x 5) ) + 4 is fine, since we have 3 bras “(“ and three kets “)”. But this expression (3 + 1) x (3 x 5) + 4) Is incorrect since we have 2 bras and 3 kets. A computer program (a parser) fed with this input would give you a “syntax error” without hesitation. The parser expects matched bra-kets (if there’s three ((( then there must be three ))) )! Wow! How many bras and how many kets did you scan in the previous sentence? Bras and kets are important in high-level languages such as “C” and “Java” since they identify blocks of programming code which are written to achieve specific goals, such as adding numbers, finding the brightest point in an image, or reading user key-press input. Bra-kets give the programmer a tool to structure the written code. So let’s attempt to build a FSM to do this important task. Have a look at Fig.11. State Q1 is fundamental here. In this state, we have “matched” brackets, an equal number of bras and kets. Let’s say we have the string “(a(bc)d)”. Then the first input to the FSM is the first “(“. This moves us from Q1 to Q2. Then we get the “a”. This is neither a “(“ nor a “)” so we stay in Q2 thanks to the “~( OR ~)” loop. Then we get another “(“ so we move to Q3. Then we get the “b”, which is neither a “(“ nor a “)” so we return to Q3. The same happens when we get the “c”. So we remain in Q3. The next input is S = “)” so we go back to Q2 and then we get a “d” which keeps us in Q2. Finally we get the input S = “)” which puts us into Q1 which outputs a “1” indicating that the brackets are matched. ~( or ~) ~( or ~) ( ( Q1 Q2 Q3 [1] [0] [0] ~( ) ) Figure 11. Bracket checker FSM. This accepts characters “(“, “)” and “a-z”. We exit Q1 only on input S = “(“ . Once in Q2 we only move to Q3 if we receive a “(“ or else return to Q1 if we find a matching “)”, e.g if the input was “(ansbd)”. We advance to Q3 if we have received two “(“’s , e.g. if the input was “(aab(dhf”. It is clear to see that we find ourselves in Q1 only if the brackets match, such as “(a)” or “(a(bcd))”. But this FSM is incapable of matching any more than two pairs of brackets. The FSM works well, perfectly. But only if up to two bras and two kets are expected. Any more, then the FSM cannot cope. And here’s a fundamental limitation of the FSM approach. While we can extend the FSM to recognise three, four or a hundred matching bra-kets, we cannot extend it to recognize an unspecified number of bra- kets. The FSM formalism does not have sufficient expressive power to generalise. As we shall see in Chapter??, the Turing Machine formalism suggests a solution. D11. Designing a Soft-Drink Dispenser Let’s tackle a classic problem in electronic engineering, designing a controller to work a soft-drink dispenser. Let’s take a relatively easy scenario: You will be issued with a can if you have deposited 30p (or more, but no change is given). The machine only accepts 10p and 20p coins. Of course these may be deposited in any order. After each coin you put in the machine, it moves to a new state which of course reflects the total money entered. The end states are simply when sufficient money has been deposited, if at least 30p is deposited, then the final state will output R=1 and release the can of drink. State Q1 is the entry state with nothing entered. At each state, until the end, there are two possible events, the deposit of 10p or 20p. So the FSM has the structure of a binary tree. There are five possible end states, shown in Fig.12(a). It’s easy to understand this tree. When you deposit a coin, there are two possibilities, either a 10p or a 20p. The state diagram summarises all possible combinations. Only when you have paid enough (or too much!) does the FSM output R=1 to dispense you drink. Q1 Q1 [0] [0] 10 20 10 Q2 Q4 [0] [0] 20 Q 20 2 10 20 Q9 [0] 10 [1] 10 Q3 Q7 Q8 [0] 40 [1] [1] Q 20 20 3 10 [0] 20 30 30 10 Q5 Q6 [1] [1] Q5/7/8 Q6/9 [1] [1] 30 40 (a) (b) Figure 12. Soft drink dispenser FSM. (a) Binary tree state diagram: Transitions indicate a deposit of either 10p or 20p to purchase a drink worth 30p. Terminal (double-circled)\states indicates the money deposited to release a drink. This state diagram is a “binary tree” – on each coin deposit there are two possibilities, 10p or 20p. Each transition represents one of these. (b) Reduced state diagram, The question arises, can we simplify this state diagram, and the answer is yes! Consider the terminal states in Fig.12(a). There are two classes of states. In one we have entered 30p and in the other we have entered 40p. So we should coalesce these two “classes” of states into two states, one where we have entered 30p and one where we have entered 40p. So we take Q5, Q7 and Q8 as identical and also Q6 and Q9 as identical. This produces the simplified state diagram is shown in Fig.12(b). D12 Table-Based FSM Representation – Parity Checker The diagrammatic representation of an FSM as a State Diagram is appealing to our human way of working and perhaps thinking, and while it captures an FSM completely may not be the best way to prepare for a software or digital electronic implementation. To prepare for understanding how this is done, we now introduce a table-based methodology for constructing FSMs. It is important that this new methodology maintains the essential structure of the FSM: States, the output or response of that state and transitions between the states caused by external or internal stimuli. Finally we must have closure, which means that each state will lead to an existing state within the machine. 1 Even Odd (a) [0] [1] 0 0 1 Present Input Next Output State (PS) (S) State (R) Even 0 Even 0 (b) Even 1 Odd 0 Odd 0 Odd 1 Odd 1 Even 1 Figure 13 Parity Detector FSM represented both as (a) the original State Diagram and (b) as a Symbolic State Transition Table. The first two columns contain the present state PS and the input S causing the transition. The last two columns show the next state, but the ouput R is from the present state PS. Let’s take a few of the example seen above and convert them to Tables, first the parity detector reproduced in Figure 13 together with the Symbolic State Transition Table. To construct the table we inspect the State Diagram. Starting with the present state (PS) as “Even” we create a line in the Table for each possible input S to this state. This gives the lines starting with “Even” “0” and “Even” “1”. We then follow the State Diagram arcs to each of these inputs to discover the next state (NS). The first two lines become “Even” “0” “Even” and “Even” “1” “Odd”. We finally add the output (R) from the present state. Note carefully that we use the present state and not the next state to get the output. This is because it’s the present state that generates the output. Repeating this for the Odd state and its inputs generates the whole table shown in Fig.13(b) This table is easy to convert to a computer program, and also into a digital electronic circuit. We’ll discuss such a program in section?? Below and you’ll have opportunity to play with the program in the Activities at the end of this chapter. D13 Table-Based FSM Representation – Door Lock Here we produce a Symbolic State Transition Table for a cut-down version of the door lock we met in Section D3. The simplified door lock opens when the string of two bits “01” is entered at the keypad. The state diagram is shown in Fig. 14(a) where the terminal state Q3 outputs R=1 to trigger the opening mechanism, the starting and intermediate states Q1 and Q2 both output R=0. The table shown in Fig.14(b) is easily constructed, one only has to remember that the output R is derived from the present state PS and not from the next state NS. 0 1 Q1 Q2 Q3 [0] [0] [1] 1 0 Present State Input (S) Next State Output (R) (PS) (NS) Q1 0 Q2 0 Q1 1 Q1 0 Q2 0 Q2 0 Q2 1 Q3 0 Q3 0 Q3 1 Q3 1 Q3 1 Figure 14. Simplified door lock FSM (based on the example shown in Fig.5). This accepts the string “0 1” to unlock the door, the output signal “r=1” being generated in Q3. (a) shows the State Diagram and (b) the Symbolic State Transition Table. The next state (NS) is generated from the present state (PS) by the input stimulus S, and each PS generates its output response R. D14 Setting a FSM into Digital Electronic Hardware. Parity Checker The Symbolic State Transition Tables contain symbols as well as numbers. We know that at its digital electronic level circuits work with numbers, and more specifically binary numbers. So to prepare for digital electronics, we must get rid of the symbols and replace or “encode” them with numbers. Let’s take the parity checker once more. As shown in Fig.15 the encoding is straightforward (and natural). We encode each occurrence of the symbol “Even” as “0” and each occurrence of the symbol “Odd” as “1”. So we obtain the Encoded State Transition table in Fig.15(b). This is now ready to be cast into digital electronics. Present Input Next Output State (PS) (S) State (R) Even 0 Even 0 Even 1 Odd 0 Odd 0 Odd 1 Odd 1 Even 1 (a) Present Input Next Output State (PS) (S) State (R) 0 0 0 0 0 1 1 0 1 0 1 1 1 1 0 1 (b) Figure 15 The Parity Checker: Conversion of the Symbolic State Transition Table (a) to the Encoded State Transition Table (b) which can be set into a digital electronic circuit. The encoding is simple; Even -> 0 and Odd -> 1. The state table has been effectively translated into binary numbers. But before we get down to details, let’s have a look at the block-diagram structure of a general digital FSM. This is shown in Fig.16 and consists of three functional blocks: 1. The “CI” block represents Combinatorial Logic Input (where “combinatorial logic” means “gates”). 2. The “CO” block represents Combinatorial Logic Output 3. The “L” block is a “latch”, a small amount of memory which stores the present state PS. Let’s attack each of these blocks. First the CI block. Remember that each line in the State Transition Table used the value of the present state (PS) and the value of the input (S) to work out the value of the next state (NS)? Well that’s exactly what the CI block does. Also the output R is worked out from the value of the present state PS. That’s the job of the CO block which is fed by PS at its inputs. Think of both CI and CO blocks as bunches of logic gates. Now what about the “latch” L? Well, the FSM must be in a stable state until it requested to make a transition, in other words, the state, the PS mut be stored somewhere, and that’ what the latch does. The outpout of the latch is equal to what it is storing, which is the present state PS. So PS comes out of the latch, and flows back into CI where it is combined with input S to generate the next state NS which appears at the output of CI. But it does not enter L. The present state only becomes the next state on a transition. That happens when a clock pulse is applied to the “clk” (clock) input of L. At this moment there is a transition and NS becomes PS so the FSM moves into the next state. Input S / CI CO NS PS L / / / Output R clk / Figure 16 Block diagram of a Digital Electronics FSM. Inputs S and the present state PS enter a clock of “combinatorial logic” labelled CI. This is a collection of logic gates which generates the next state NS signals. The centre block L is a “latch” which stores the current value of the present state PS. This state is passed to CO which is the output logic gates. Finally PS is fed-back to the input of CI. The “clk” clock signal load the next state NS into the present state PS when a state transition occurs. The diagonal bars on the wires indicate that they may consist of several parallel wires. This discussion may have left you a little perplexed. If you think like I do, then you may want a couple of concrete examples worked out. So let’s move on to attack the parity detector details. First we must consider CI. Look at the encoded state transition table in Fig.17(a). This shows how the present state PS and the input S are combined to produce the next state NS. If we simply read the four lines in the table as a truth-table then we see at once that the output, NS is simply the output of a logical XOR-gate. So that’s C1 cracked! Now on to CO. Again, inspection of the encoded state transition table shows that the output R is equal to the present state PS. So CO involves nothing else than outputting PS, we don’t need any logic here. Finally we must think about L. Here the only decision we must make is as to what we must remember, i.e., how many bits of data. We know that the input to L is NS and the output is PS. Again, the encoded state transition table shows that there are only two possible values of the FSM’s state, 0 or 1. So we need one bit of memory. As you know, this is a one-bit data latch. Putting these three components together, as outlined in the general block-diagram of Fig.16 gives us our final circuit, sketched in Fig.17(b). You will have the opportunity to examine this circuit using a digital-logic simulator in the Activities at the end of this chapter. Present Input Next Output State (PS) (S) State (R) 0 0 0 0 0 1 1 0 1 0 1 1 1 1 0 1 (a) P S NS Output R Input S CI M clk (b) Figure 17 Parity detector FSM. (a) shows the encoded state transition table and (b) the equivalent digital logic implementation. Input S is provided by a switch and the output R by a LED. Note the present state PS at the output of the D-latch and NS generated from PS and S by the XOR-gate. The clock signal “clk” loads NS into the latch where it is output as the value of PS. So NS becomes PS, a transition has occurred. D.15 Electronic Door Lock As a second example of the procedure discussed above, let’s look at the electronic door-lock problem we introduced in Section D3 And see how we can set this into digital hardware. To keep things manageable, we’ll work with a cut-down version of the door lock comprising the first two stages, the lock will open when the digits “0” and “1” are input in that sequence. This simpler door lock is shown in Fig.18(a) as the State Diagram and the Symbolic State Transition Table. You should feel happy by now of the equivalence of these two representations, and how to produce the Table from the Diagram. The next state is to compose the Encoded State Transition table. This is shown in Fig.18(b) The encoding of the states is easy, we’ve just used the number following the “Q” as a two-bit binary number. So we have Q1 -> 01, Q2 -> 10, Q3 -> 11. So both the represent state (PS) and the next state (NS) are encoded as two-bit numbers. We’ve laid out the table in a slightly unusual way. In fact there’s two tables, one which shows the two next state bit and a second which shows the Output bit (which when “1” will open the door). This is to help us identify the “products”! of logic states which we need to “sum” to generate the composite logic function. The miniterms needed are labelled “a” to “d” for the higher order NS bit (bit-2) and as “e” to “I” for the lower order NS bit (bit-1). For example term “a” is a = Not (PS2) AND (PS1) AND (S) which electronic implementation is shown in Fig.19(a). All the products forming this term are generated in the same way, and they are combined in an OR-gate to produce the entire term “a”. This is shown in Fig.19(b). A similar construction is made for the NS bit-2 terms and the Output R terms producing the combinatorial circuit shown In Fig.19(c). Finally the combinatorial next state and output state are combined with the memory element to produce the final circuit diagram shown in Figure 20. Present State Input (S) Next State NS2 NS1 (PS2 PS1) (NS2 NS1) Products Products 01 0 10 e 01 1 01 a (a) 10 0 10 f 10 1 11 b g 11 0 11 c h 11 1 11 d i (b) Product a = Not (PS2) AND (PS1) AND (S) Present State Input (S) Next State Output (PS2 PS1) (NS2 NS1) Products 01 0 10 0 01 1 01 0 (c) 10 0 10 0 10 1 11 0 11 0 11 k 11 1 11 l Figure 18. Encoded State Transition Tables for the Simplified door-lock from Figure?? Here a separate table is provided for the next state (NS) output (a) and for the output response (R) from the FSM. Each of the logic product terms is indicated with a letter; in (a) the NS bit-2 terms (NS2) are labelled “a” to “d” and the NS bit-w terms (NS1) are labelled “e” to “i”. This corresponds to the labelling of the digital circuits in Figs?? And ??. One product, “a” is explicitly written out in (b). This corresponds to the second line of the table in (a). PS2 PS1 S PS2 PS1 S a a b NS2 c (a) (b) PS2 PS1 S e PS2 PS1 f NS1 g h R i (c) (d) Figure 19 Circuits derived from the Encoded State Transition Tables for the Simplified door-lock. (a) shows the generation of the single product term “a” contributing to the bit-2 next state output NS2 and (b) shows the complete “sum of products” for the next state bit-2 (NS2) output. The NS1 bit-1 output is shown in (c) and the FSM output R in (d). Keypad / input S 1 CI CO NS2 NS1 PS2 L Output PS1 / / / response R 2 2 1 clk (a) / 2 a b NS 2 c d PS2 L PS1 e f clk g NS 1 h i R (b) Figure 20 Digital logic door lock example. (a) is a block-diagram of combinatorial logic elements and latch L, (b) shows the gate-level implementation of the door-lock. D.16 A ROM-Based Digital FSM Approach to the Door Lock In a previous chapter we took a hard-nosed look at digital electronic circuits. One principle we saw was that it is possible to use a programmable memory to simulate any combination of logic gates. Also, that there exist chips containing arrays of programmable logic elements which can effect these logic functions. Here we shall see how to implement the door-lock in Read-Only-Memory. The basic circuit is shown in Fig.21(a) which contains four elements, a ROM, and three D-latches. These latches provide the latching function “L” for the three bits required to encode the states Qn, input S and output R of the FSM. The ROM provides the combinatorial logic functionality (“CI” and “CO”). At each clock pulse instigating a transition, the present state PS exits the latch as two bits, PS2 and PS1. These are fed to the ROM as part of a 3-bit address. The third bit of the address is the input S. So the address into the ROM has this form Bit 4 2 1 Address = PS2 PS1 S The data which is selected by this input address represents the next state NS and flows into the latch. The data has this form Bit 4 2 1 Data = NS2 NS1 R To see how we must construct these address-data bits, let’s consider the first line of the encoded state transition table shown in Fig.15(b). This is PS2 PS1 S NS2 NS1 R 0 1 0 1 0 0 The address (PS2 PS1 S) is 010. Since we must have a 4-bit address, we add a leading 0 to give us 0010. The data (NS2 NS1 R) is 100. Again we add a leading 0 to give the data 0100. So we have generated the ROM line Address = 0010 Data = 0100 This is the fifth line in the memory shown in Fig.21(b). The entire ROM contents were generated in this way. Clearly, once the encoded state transition table has been built for a particular problem, then the ROM-based implementation is simple to generate, much easier than an implementation using discrete logic gates. A final comment concerning the first two lines of the ROM address and data. The addresses 000 and 001 have no correspondence in the symbolic table (they would have encoded state “Q0”). But we started our symbolic labelling with “Q1” which was encoded as addresses 010 and 011. This was not a wise choice, in fact it is a mistake, since the ROM has two locations without any meaning, and the electronic circuit will reference these locations. To recover from this mistake, we put data into addresses 000 and 001 to get us into our starting state 010. This explains the data values for these two addresses. Conclusion? Well, it’s best to start our enumeration of states at zero, ie “Q0”. (a) S 0000 0010 0001 0010 0010 0100 0011 0010 0100 0100 0101 0111 0110 0111 addr 0111 0111 ROM R L (b) clk Figure 21 ROM-based electronic door lock. The digital FSM is outlined in (a). The combinatorial logic is provided by the ROM which feeds into the latch made up of three D-latch elements. Note that the input S and output R are connected to the lowest bit. In (b) the details of the ROM are shown. The data at each address has been obtained by inspection of the enecoded state transition table (Fig.15(b)). Note that S and R are connecterd to the lowest bit. While the door-lock needs only 3 bits of data, four bits are shown here since that is the smallest unit offered by the digital simulator. D.17 A FSM Robot Controller As part of the Activities at the end of this chapter, you will be invited to program a robot controller using a symbolic state transition table. A screen-shot of the simulator you will use is shown in Fig.22. The robot has two sensors, a left bumper and a right bumper which input into the table FSM. Each state has four possible outputs, move forwards a bit, move backwards a bit, turn left a bit and turn right a bit. You can load various “robot worlds” into the simulator which contain a number of obstacles. Figure 22. Robot FSM simulator. The right panel shows the robot with its left and right input sensors approaching an obstacle. The FSM Table on the left panel combines input from the present state “This” with the input sensors “ipL” and “ipR”. The output is the next state “Next” and the response motor drive signals “Left”, “Right”, “Front”, “Back”. Note these all outputs for a particular “This” state are the same. Our model of a FSM has the output determined by the present state. Let’s look at an example FSM table which you will be invited to construct, see Fig.23. First note we have labelled the first state “Q0”, with a view on a future encoding as “00”. We do not make the encoding mistake we made with the door lock again! Before we dissect this table, let’s have a look at its basic structure. Each of the two states has 4 lines in the table. This is because there are two binary inputs, so therefore four possible combinations of inputs. We must deal with each of these. Second, an event may cause a transition out of a state back into the same robot state (e.g. line 1) or into a different state (line 3) but may not go to an unknown state. This table has been slightly contrived to make the robot move until it hits the wall, turn right (clockwise) and then move forwards again: Line This IpL ipR Next L R F B 1 Q0 0 0 Q0 0 0 1 0 2 Q0 0 1 Q0 0 0 1 0 3 Q0 1 0 Q1 0 0 1 0 4 Q0 1 1 Q0 0 0 1 0 5 Q1 0 0 Q0 0 1 0 0 6 Q1 0 1 Q0 0 1 0 0 7 Q1 1 0 Q1 0 1 0 0 8 Q1 1 1 Q0 0 1 0 0 Figure 23. Symbolic State Transition Table for the simulated robot controller . The present state “This” input to the FSM is combined with the left and right bumber inputs “IpL” and “IpR”. The table produces the next state “Next” output and the robot movement left “L”, right “R”, forwards “F” or back “B”. Lines1-4: The Robot is in State Q0, the output is F=1 so the robot moves forwards. Lines 5-8: The robot is in State Q1, the output is R=1, so the robot turns right (clockwise) Line1: Neither left or right inputs are true. The next state is again Q0. Line2: The right input is true, there has been a collision with the right bumper. The state machine ignores this and will plough on forward, and keep on going, back into Q0. Line3: This is more interesting, there is a collision on the left. While the robot still moves forwards for a time (F=1) it’s next state is Q1 Now we jump to Line 7 since we are in Q1 and there is still input from the left bumper. The output now become R=1 “turn right – clockwise” and the next state is Q1=1, so that we may continue to keep turning. So we arrive back in Q1=1 and if IpL is still 1 then we shall keep on turning and once more return to Q1=1. Only when we return to Q1 and both IpL=0 and IpR = 0 do we arrive at line 5, where the next state becomes Q0, where we shall move forwards, although we still turn a little more right here. Now let’s see how to encode the symbolic table in such a way as to be able to produce a ROM-based FSM implementation. Glance once more at the table presented in Fig.23 and you will see that already the inputs IpL, IpR, and the outputs F B R L are already encoded as bits. It’s only the state names “This” and “Next” which are written as text, and it’s these which must be encoded, or represented at a set of bits. This is quite easy, if we label the states as numbers “0”, “1”, “2”, … “N”, since we may then use the binary representation of these numbers as out bits. Let’s choose to represent our states as 4-bit binary numbers. As we know this will give us a maximum of 2 x 2 x 2 x 2 = 16 possible states, which may well be enough for a small application. Converting the numerical values of the states in the above table to bits, we obtain the isomorphic table, shown in Fig.24(a). A ROM-based implementation is shown in Fig.24(b). Line This IpL ipR Next L R F B 1 00 0 0 00 0 0 1 0 2 00 0 1 00 0 0 1 0 3 00 1 0 01 0 0 1 0 4 00 1 1 00 0 0 1 0 5 01 0 0 00 0 1 0 0 6 01 0 1 00 0 1 0 0 7 01 1 0 01 0 1 0 0 8 01 1 1 00 0 1 0 0 (a) S 000010 0000 000010 0001 010010 0010 000010 0011 000100 0100 000100 0101 010100 0110 000100 addr 0111 ROM R L clk (b) Figure 24. Robot Controller shows as (a) the Encoded State Transition Table for the robot controller ROM contents generated by encoding state “Q0” as 00 and state “Q1” as 01. (b) with the ROM contents used to implement this controller D.18 Moore and Mealy Machines You may have noticed that a FSM involves a number operations. First the present state is combined with the stimulus input. Second an output is produced. Third, the state is updated, i.e., there is a transition. It turns out that there are two different architectures for combining these operations. These are known as “Moore” and “Mealy” architectures. Our discussion has been centered around the “Moore” machine where the output is generated by the present state. In other words the output is associated with the state. The transition serves to move between states depending on the input stimulus. The transition was always associated with a clock signal. But we can do this another way. We can associate the output with the transition between states. So, as soon as a stimulus is received, it produces a new output, without having to wait for the clock signal. This is the “Mealy” architecture, where the clock signal is used to move between states, but not generate the output. So in the Moore architecture, the output as well as generation of the new state happens on the clock signal, even though the stimulus may have arrived some time before the clock signal is issued. In the Mealy architecture, as soon as the stimulus is received, the output response obtains, the stimulus “flows through” to the output. Input S / CI CO PS NS L / / / Output R clk / (a) Input S / / / Output R CI CO PS L / / clk / (b) Figure 25. Two architectures of FSMs. (a) the “Moore” machine we have been discussing in this chapter. Here the output is only a function on the present state PS, while in (b) the “Mealy” machine, the output R depends on the PS and also the input state S. The output of the Mealy machine changes during the transition from the PS to the NS and not when the PS is established. This difference is made clear in Fig.25 where the direct path from input stimulus to output response is evident. We shall not develop these ideas further here, it is advanced material. Yet it is useful to know of the distinction, which you may encounter in your researches. D.19 A Biological FSM. There is some evidence that FSMs are used by biological systems to effect controllers and that they are implemented using biological neural nets. A well-known example are the simple neural circuits used to generate patterns of behaviour, such as locomotion or breathing. These neural circuits which maintain some rhythmic or oscillatory activity are know as “Central Pattern Generators” (CPGs) and have been widely studied in the case of invertebrate creatures where they have been found to consist of small numbers of interconnected neurons. One example studied by Getting in 1983 is the Tritonia swim CPG. (Tritonia is a “sea-slug” and is found a tasty snack by star-fish).This consists of a group of four interconnected neurons with excitory and inhibitory synapses, see Fig.26 The effect is to produce alternate activity in the dorsal and ventral swim motor neurons which enable it to escape a marauding star-fish. A cycle of states begins with b firing, where a does not fire due to the inhibitory connection nor does c fire due to its inhibitory connection with b. But eventually a fires and, after a delay, so does c. When c fires it inhibits both b and a. After a while b fires again, and the cycle repeats. a c b d Figure 26. Neural network providing the CPG FSM for Tritonia. Solid circles are excitory synapses, hollow circles are inhibitory. Since there is clearly a finite number of states in this cycle, this neural net can be cast as a FSM. Marvin Minsky has made this point, and has provided a mathematical equivalence between the MsCulloch-Pitts neurons we are using here and the FSM approach we have been studying. The interesting point is, that the FSM formalism may be applied to various underlying technologies, whether software, digital electronic or biological neural. Another suggestion has been made by Kohonen, who notes that the coupling of a neural associative memory with a delay (providing the equivalent of our “latch” circuit element) may be able to recall learned and remembered sequences of actions. A cat sees a mouse, recognises the mouse, prepares to run and runs! While there is at the moment little neuro-anatomical evidence for the suggested circuits, the digital- biological correspondence is enchanting, and demands further research. The structure of Kohonen’s circuitry is shown in Fig?? and clearly resembles the digital electronic FSM discussed in this chapter. stimulus response / / M / / delay Figure 27. Kohonen’s suggestion for a biological sequence generator. A stimulus input into an associative memory “M” elicits a response “R”, but the output from “M” is fed back, together with the input “S” to form an “address” into M. The “delay” is the equivalent of our digital “latch”, providing temporary storage of the FSM’s state. Compare this figure with Fig.?? D.20 Software FSMs and Games Programming If you look at a modern object-oriented games programming engine such as “Unreal Tournament”, you’ll discover the behaviour of the actors situated in these games is programmed using the FSM formalism. Indeed may modern texts on “game-AI” will include a detailed discussion of FSMs. There are also examples of contemporary AI development environments, such as Agent-based technologies (such as “Jade”). These software agents, which are programmed to have autonomous decision-making capabilities and behaviour often incorporate a FSM within each agent. Within the software development and engineering communities, various “patterns” of programming FSMs have been developed. Again this is beyond the level of this text. D.21 Roundup We hope that you have experienced the power and usefulness of the FSM approach in designing complex control and analysis engines which are of great use in real-world situations. The mapping from a human-centric “symbolic” description to a hardware (or software) implementation is important. Sure, we have skirted around some issues, the formal mathematics of FSMs. The limitations of FSMs. But we have also hinted that FSMs have a fundamental place in the understanding of the “nature” of computation. It is this aspect which we shall revisit in chapter ?? where we explore an extension of the FSM into the “Universal Turing Machine” which provides us with a theoretical understanding of the computers which pervade our lives. D.22 Activities These activities will give you some hands-on experience of working with Finite State Machines (FSMs). First some paper exercises, using the directed graph formalism, then some work using a Table-based FSM to control the behaviour of a simple robot. We shall also use a Digital Electronics simulator to explore some digital FSM implementations. ACTIVITIES 1 Question 1. Consider the FSM shown below. This receives letters of the alphabet as input. Which sequences of letters "strings" will it accept? Question 2. This question is a classic in Computer Science. A real doozer. It's used to check your pgorams or even your programs. Like in C or Java, whenever you begin a block of code with a '{' bra then you have to end it with a '}' ket to make up a paired '{ }' bra-ket. (Thanks to Dirac for the terminology). So the FSM receives a stream of characters like this ahds{ oieocvis{oxvvc}nnn} and it has to decide if the bra-kets are 'balanced', ie if the number of left bras { is the same as the number of right kets } . The example I just gave you wan perfectly balanced. The next example isn't main() { int i; intj j = i+1; ....so that program would not compile. Make a FSM that will indicate when the bra-kets are balanced. Here's a starting suggestion. Note that the states "S0", "S1", etc. are labelled with the number of unmatched bras. Question.3 Design a FSM which will accept a binary string not containing 000. Here's a starting point for you. Remember, the FSM has to signal when any string is inout which does not contain 000. If a string with 000 is presented then no further strings are accepted since the 'death string' has been processed. Ouch. Question 4. States Waking Up It's morning again. Your world consists of your bed, your alarm clock and your mobile phone. Possible states are sleeping, alarm buzzing, turning off alarm, pressing snooze button, getting up. 1. Draw out a state diagram graph for these states 2. Label transitions between the states that have meaning for you 3. Look at your state diagram. Is it possible for you to leave the house with the alarm switched on? 4. Compare and contrast your state diagram with a friend. 5. Now add in the answering phone state. Can you now leave the house with the alarm on? Question 5. UCW is full of FSM's 1. Make a comprehensive list of all machines (eg vending machines (eg drink dispenser)) at UCW which may be modelled using the FSM approach 2. Choose one machine and produce a comprehensive FSM state diagram. Produce it directly if you like or by the 'reducing the tree' method used with the coke machine in class. Question 6. Here the problem is to design an FSM which will recognize the occurrence of "0110" in any series of input bits, sunce as 0100100010110010101010110. Below you can see a student's attempt to solve the problem. Does it work? How well does it work? Can you improve on it? Or is it a load of balls with some weird links? OK Solve the problem yourself. Question 7. Design an FSM controller for a safe lock. The lock should only open if the sequence RLLRR is received. Any other sequence should sound the alarm. ACTIVITIES 2 Question 8. Load up the FSM Robot Simulator from HERE. Unzip the folder and drop on your desktop. Now double click on the executable jar file *.jar" Note this is experimental software currently under development for you. The version we are using today is still a little rough. Fingers crossed. 1.1 Make a FSM Table so that the robot will move forwards until its left bumper hits. Then it should move backwards for ever. Load RWorld1. 1.2 Make a FSM Table so that the robot moves forwards until it hits the obstacle when it should turn right (clockwise) until its bumper is clear, when it should go straight on. 1.3 Single step the machine (brown man). Confirm your expectations. What happens when the robot hits the wall? Why does it not respond to the wall? Question 9. Load up "Controller 1" and "World4". The FSM was designed to allow the robot to move in and then out of the channel. But there's a mistake and it doesn't work well. 9.1 Observe the behavior of the robot. 9.2 Look at the FSM table and work out what is going on 9.3 There is an error in the table. Find it and correct it. Demonstrate the correct code to your tutor or friend. Question 10. Let's say we want to get the robot to go around the edge of a square block. We could use its left feeler to probe for the edge of the block, and use this left feeler as the robot moves around the block. Consider the left feeler touching the block. How should we instruct the robot to move? Consider the left feeler not touching the block - the robot is moving away from the block. How should we instruct the robot to move? Draw a state diagram for this problem. Fill out a FSM table and try out your solution using "World2" One correct solution is found in "Controller2.txt" ACTIVITIES 3 Digital Electronic Finite State Machine The following activities lead you through the procedure to construct a FSM in digital electronic hardware. Question 1 First let’s attack a paper-based question to review the principles of a FSM constructed from a memory chip and a latch chip. Then we shall implement this design using MultiMedia Logic simulator. The sketch below shows a memory chip with 16 cells (0 to F), each cell contains 4 bits of data. Two of these bits are used as outputs, the other two bits are recycled to provide the address information of the next state. The four bit emerge from the memory chip at its bottom and pass into the 4-bit data register shown there. The two address bits emerging from this data register are complemented by a further two input bits a and b which together form a 4-bit address which is shown on the left. [modify diagram to make order of these address bits explicit] 1.1 Complete the contents of the memory so that when input b=0, then the output data will repetitively cycle between the values 0 -> 1 ->2 ->3 ->0 and so on. Take input a=0; 1.2 Modify your table so that in addition to the above output, the FSM generates the reverse sequence 3 -> 2 -> 1 -> 0 -> 3, etc when input b=1. Take input a=0; 1.3 Explain how you would need to modify the above circuit to be able to drive a system of traffic lights through the states “red”, “red and amber”, “green”, “amber” and back to “red”. 1. Configure the above ROM with latch so that when input b is 0 then the outputs cycle through the sequence 0 -> 1 -> 2 -> 3 -> 0 -> …, and when input b I 1, the outputs cycle through 3 -> 2 -> 1 -> 0 -> 3 -> … Input a is set always to 0. 2. Explain how you would need to modify the above system to be able to drive a system of traffic lights through the states “red”, “red and amber”, “green”, “green”, “amber”, “red”. 3. Explain how you would modify your design so that if a pedestrian pressed a button (say “a”) then the lights would go to “amber” then “red”. Question 2. Here is a Multimedia Logic Circuit which implements the Finite State Machine presented above. The memory cell, top centre is the ROM, and the two rectangular “flipflops” make up the latch. The top two LEDs are the data output from the system. The additional OR-Gates have been included simply to reset the machine to a distinct starting state. N.B. When you start each simulation, set the “Reset” switch to “1”, then press the “Clock” switch, and the reset the Reset switch (!) to “0”. This will reset the circuit. Note also that the two lowest bits of the data output are fed back to the address lines, all other address lines are held at 0. So if the memory data is 02, then the next memory location is 2. If the memory data is 31 then the next memory location is 1. The data output to the LEDs comes from the high nibble. So if you have data 12 or 10 or 11 in memory, then the output in all cases will be “1”. Then the left “1” is output. Similarly all data 32, 31, 30, 33 will output a “3” to the two data LEDs, while the next address will be “2”, “1”, “0”, and “3” respectively. 1. Work out suitable memory contents to cycle around four output values n0,1,2,3,0, etc. The top two LEDs should display these numbers (in binary) of course. 2. Now modify the circuit by disconnecting the third memory line from “0” and connecting it to a toggle switch. Now work out suitable memory contents so when the switch is “1” the cycle is 1,4,1,4 and when the switch is “0” the output cycle is 2,3,2,3,… 3. Modify the circuit so you can simulate a simple traffic-light controller without any pedestrian input (to cycle “red”, “red and amber”, “green”, “amber”, “red” and so on. 4. Now modify the circuit so that when a pedestrian flips a switch, the lights go “amber” then “red” then stay “red” until the switch is flipped back. ACTIVITIES 3 Advanced Work Question 1. (a) Engineer a ROM-based implementation of a Robot-controller (with behaviour of your choice) (b) Engineer a hardware implementation of this controller using digital logic gates (and a latch) and simulate its behaviour. Chapter D Finite State Machines ...................................................................................1 D1 The Notion of a State .......................................................................................1 D2. The Definition of a State Machine..................................................................3 D3. A Door Combination Lock .............................................................................4 D4. A Parity Checker.............................................................................................7 D5. Traffic Lights ..................................................................................................8 D6. Counting People Entering a Room..................................................................9 D7. The usefulness of Finite State Machines.......................................................10 D8. Acceptors and Transducers - Recognising Laughter ....................................10 D9. Recognising Text – A Computer Program Parser.........................................11 D10. Counting Brackets.......................................................................................13 D11. Designing a Soft-Drink Dispenser ..............................................................15 D12 Table-Based FSM Representation – Parity Checker....................................16 D13 Table-Based FSM Representation – Door Lock ..........................................17 D14 Setting a FSM into Digital Electronic Hardware. Parity Checker ...............17 D.15 Electronic Door Lock..................................................................................20 D.16 A ROM-Based Digital FSM Approach to the Door Lock ..........................21 D.17 A FSM Robot Controller.............................................................................26 D.10 Moore and Mealy Machines .......................................................................29 D.10 A Biological FSM in your Brain and Body ................................................30 D.11 Games Programming...................................................................................31 D.12 Roundup ......................................................................................................31 D.13 Activities .....................................................................................................32 D.10 A Discrete Logic Robot Controller............. Error! Bookmark not defined. D.10 A Car Security System................................ Error! Bookmark not defined.