comp541 state machines
DESCRIPTION
COMP541 State Machines. Montek Singh Feb 4, 2010. Topics. More advanced Verilog State Machines How to design machines that go through a sequence of events Basically close this loop. First Topic. More Verilog…. Hierarchy. module and3(input a, b, c, output y); assign y = a & b & c; - PowerPoint PPT PresentationTRANSCRIPT
1
COMP541COMP541
State MachinesState Machines
Montek SinghMontek Singh
Feb 4, 2010Feb 4, 2010
TopicsTopics More advanced VerilogMore advanced Verilog State MachinesState Machines
How to design machines that go through a sequence How to design machines that go through a sequence of eventsof events
Basically close this loopBasically close this loop
2
First TopicFirst Topic More Verilog…More Verilog…
3
HierarchyHierarchy
module and3(input a, b, module and3(input a, b, c, output y);c, output y);
assign y = a & b & c;assign y = a & b & c;
endmoduleendmodule
module inv(input a,module inv(input a,
output y);output y);
assign y = ~a;assign y = ~a;
endmoduleendmodule
module nand3(input a, b, c output y); wire n1; // internal signal
and3 andgate(a, b, c, n1); // instance of and3 inv inverter(n1, y); // instance of inverterendmodule
Internal VariablesInternal Variables
module fulladder(input a, b, cin, output s, cout);module fulladder(input a, b, cin, output s, cout);
wire p, g; // internalwire p, g; // internal
assign p = a ^ b;assign p = a ^ b;
assign g = a & b;assign g = a & b;
assign s = p ^ cin;assign s = p ^ cin;
assign cout = g | (p & cin);assign cout = g | (p & cin);
endmoduleendmodule
p
g s
un1_cout cout
cout
s
cin
ba
Bitwise Operators (we have used)Bitwise Operators (we have used)module gates(input [3:0] a, b,
output [3:0] y1, y2, y3, y4, y5);
assign y1 = a & b; // AND
assign y2 = a | b; // OR
assign y3 = a ^ b; // XOR
assign y4 = ~(a & b); // NAND
assign y5 = ~(a | b); // NOR
endmodule
// single line comment
/*…*/ multiline comment
Reduction OperatorsReduction Operatorsmodule and8(input [7:0] a, module and8(input [7:0] a,
output y);output y);
assign y = &a;assign y = &a;
// &a is much easier to write than// &a is much easier to write than
// assign y = a[7] & a[6] & a[5] & a[4] &// assign y = a[7] & a[6] & a[5] & a[4] &
// a[3] & a[2] & a[1] & a[0];// a[3] & a[2] & a[1] & a[0];
endmoduleendmodule
PrecedencePrecedence
~ NOT
*, /, % mult, div, mod
+, - add,sub
<<, >> shift
<<<, >>> arithmetic shift
<, <=, >, >= comparison
==, != equal, not equal
&, ~& AND, NAND
^, ~^ XOR, XNOR
|, ~| OR, XOR
?: ternary operator
Highest
Lowest
NumbersNumbers Format: Format: N'BvalueN'Bvalue
N = number of bits, B = baseN = number of bits, B = base N'B is optional but recommended (default is decimal)N'B is optional but recommended (default is decimal)
Number # Bits Base Decimal Equivalent
Stored
3’b101 3 binary 5 101
‘b11 unsized binary 3 00…0011
8’b11 8 binary 3 00000011
8’b1010_1011 8 binary 171 10101011
3’d6 3 decimal 6 110
6’o42 6 octal 34 100010
8’hAB 8 hexadecimal 171 10101011
42 Unsized decimal 42 00…0101010
Bit Manipulations: Ex 1Bit Manipulations: Ex 1assign y = {a[2:1], {3{b[0]}}, a[0], 6’b100_010};
// if y is a 12-bit signal, the above statement produces:
y = a[2] a[1] b[0] b[0] b[0] a[0] 1 0 0 0 1 0
// underscores (_) are used for formatting only to make it easier to read. Verilog ignores them.
Bit Manipulations: Ex 2Bit Manipulations: Ex 2
module mux2_8(input [7:0] d0, d1,module mux2_8(input [7:0] d0, d1,
input s,input s,
output [7:0] y);output [7:0] y);
mux2 lsbmux(d0[3:0], d1[3:0], s, y[3:0]);mux2 lsbmux(d0[3:0], d1[3:0], s, y[3:0]);
mux2 msbmux(d0[7:4], d1[7:4], s, y[7:4]);mux2 msbmux(d0[7:4], d1[7:4], s, y[7:4]);
endmoduleendmodule
mux2
lsbmux
mux2
msbmux
y[7:0][7:0]
s
d1[7:0] [7:0]
d0[7:0] [7:0]
s[3:0] d0[3:0][3:0] d1[3:0]
[3:0]y[3:0]
s[7:4] d0[3:0][7:4] d1[3:0]
[7:4]y[3:0]
Synthesis:
Verilog:
Behavioral StatementsBehavioral Statements Statements that must be inside always Statements that must be inside always
statements:statements: if / elseif / else case, casezcase, casez
Reminder: Variables/signals assigned in an Reminder: Variables/signals assigned in an always statement must be declared as regalways statement must be declared as reg (even if they’re not actually registered! More in a (even if they’re not actually registered! More in a
moment) moment)
Comb. Logic using Comb. Logic using casecase
module sevenseg(input [3:0] data,
output reg [6:0] segments);
always @(*)
case (data)
// abc_defg
0: segments = 7'b111_1110;
1: segments = 7'b011_0000;
2: segments = 7'b110_1101;
3: segments = 7'b111_1001;
4: segments = 7'b011_0011;
5: segments = 7'b101_1011;
6: segments = 7'b101_1111;
7: segments = 7'b111_0000;
8: segments = 7'b111_1111;
9: segments = 7'b111_1011;
default: segments = 7'b000_0000; // required
endcase
endmodule
Note the *
Synthesizing an Unwanted Latch?Synthesizing an Unwanted Latch? Could happen!Could happen! Check the synthesizer outputCheck the synthesizer output In order for a case statement to imply In order for a case statement to imply
combinational logic, all possible input combinational logic, all possible input combinations must be described by the HDLcombinations must be described by the HDL
Remember to use a Remember to use a default default statement when statement when necessarynecessary May be good practice anywayMay be good practice anyway And all And all if if statements w/ matching statements w/ matching elseelse
Combinational Logic using Combinational Logic using casezcasez
module priority_casez(input [3:0] a,
output reg [3:0] y);
always @(*)
casez(a)
4'b1???: y = 4'b1000; // ? = don’t care
4'b01??: y = 4'b0100;
4'b001?: y = 4'b0010;
4'b0001: y = 4'b0001;
default: y = 4'b0000;
endcase
endmodule
Blocking vs. Nonblocking Assignments Blocking vs. Nonblocking Assignments (review)(review) <= is a “nonblocking assignment”<= is a “nonblocking assignment”
Occurs simultaneously with othersOccurs simultaneously with others
= is a “blocking assignment”= is a “blocking assignment” Occurs in the order it appears in the fileOccurs in the order it appears in the file
// nonblocking assignmentsmodule syncgood(input clk, input d, output reg q); reg n1; always @(posedge clk) begin n1 <= d; // nonblocking q <= n1; // nonblocking endendmodule
// blocking assignmentsmodule syncbad(input clk, input d, output reg q); reg n1; always @(posedge clk) begin n1 = d; // blocking q = n1; // blocking endendmodule
Rules for Signal AssignmentRules for Signal Assignment Use always @(posedge clk) and nonblocking Use always @(posedge clk) and nonblocking
assignments (<=) to model synchronous assignments (<=) to model synchronous sequential logicsequential logic
always @ (posedge clk)always @ (posedge clk)
q <= d; // nonblockingq <= d; // nonblocking
Use continuous assignments (assign …) to Use continuous assignments (assign …) to model simple combinational logic.model simple combinational logic.
assign y = a & b; assign y = a & b;
Use always @ (*) and blocking assignments (=) Use always @ (*) and blocking assignments (=) to model more complicated combinational logic to model more complicated combinational logic where the always statement is helpful.where the always statement is helpful.
Do not make assignments to the same signal in Do not make assignments to the same signal in more than one always or continuous more than one always or continuous assignment statementassignment statement
Next TopicNext Topic Finite State MachinesFinite State Machines
A basic sequential building blockA basic sequential building block
18
Synchronous Sequential Logic Synchronous Sequential Logic DesignDesign Registers contain the state of the systemRegisters contain the state of the system The state changes at the clock edge, so The state changes at the clock edge, so
system is system is synchronized synchronized to the clockto the clock Rules:Rules:
Every circuit element is either a register or a Every circuit element is either a register or a combinational circuitcombinational circuit
All registers receive the same clock signal All registers receive the same clock signal (important!)(important!)
Every cyclic path contains at least one registerEvery cyclic path contains at least one register
Two common synchronous sequential circuitsTwo common synchronous sequential circuits Finite State Machines (FSMs)Finite State Machines (FSMs) PipelinesPipelines
Finite State Machine (FSM)Finite State Machine (FSM) Consists of:Consists of:
State register thatState register thatStore the current state and Store the current state and Loads the next state at Loads the next state at
clock edgeclock edge
Combinational logic thatCombinational logic thatComputes the next stateComputes the next stateComputes the outputsComputes the outputs
NextState
CurrentState
S’ S
CLK
CL
Next StateLogic
NextState
CL
OutputLogic
Outputs
Finite State Machines (FSMs)Finite State Machines (FSMs) Next state is determined by the current state Next state is determined by the current state
and the inputsand the inputs Two types of finite state machines differ in the Two types of finite state machines differ in the
output logic:output logic: Moore FSM: Moore FSM: outputs depend only on the current outputs depend only on the current
statestate Mealy FSM: Mealy FSM: outputs depend on the current state and outputs depend on the current state and
the inputsthe inputs
Moore and Mealy FSMsMoore and Mealy FSMs
22
CLKM Nk knext
statelogic
outputlogic
Moore FSM
CLKM Nk knext
statelogic
outputlogic
inputs
inputs
outputs
outputsstate
statenextstate
nextstate
Mealy FSM
FSM ExampleFSM Example Traffic light controllerTraffic light controller
Traffic sensors: TTraffic sensors: TAA, T, TBB (TRUE when there’s traffic) (TRUE when there’s traffic)
Lights: LLights: LAA, L, LBB
TA
LA
TA
LB
TB
TB
LA
LB
Academic Ave.
Bravado
Blvd.
Dorms
Fields
DiningHall
Labs
FSM Black BoxFSM Black Box• Inputs: Inputs: CLKCLK, , ResetReset, , TTAA, , TTBB
• Outputs: Outputs: LLAA, , LLBB
TA
TB
LA
LB
CLK
Reset
TrafficLight
Controller
Design Simple FSMDesign Simple FSM When When resetreset, L, LAA is green is green
and Land LBB is red is red As long as traffic on As long as traffic on
Academic (TAcademic (TAA high), keep high), keep LLAA green green
When TWhen TAA goes low, goes low, sequence to traffic on sequence to traffic on BravadoBravado
Follow same algorithm for Follow same algorithm for BravadoBravado
Let’s say clock is 5 secs. Let’s say clock is 5 secs. (time for yellow light)(time for yellow light)
25
TA
LA
TA
LB
TB
TB
LA
LB
Academic Ave.
Bravado
Blvd.
Dorms
Fields
DiningHall
Labs
StatesStates What sequence do the traffic lights follow?What sequence do the traffic lights follow?
Reset to State 0, LReset to State 0, LAA is green and L is green and LBB is red is red Next (on board)?Next (on board)?
26
TA
LA
TA
LB
TB
TB
LA
LB
Academic Ave.
Bra
vado
Blvd
.
Dorms
Fields
DiningHall
Labs
State Transition DiagramState Transition Diagram
• Moore FSM: outputs labeled in each state• States: Circles• Transitions: Arcs
S0LA: greenLB: red
S1LA: yellowLB: red
S3LA: redLB: yellow
S2LA: redLB: green
TATA
TB
TB
Reset
TA
LA
TA
LB
TB
TB
LA
LB
Academic Ave.
Bra
vado
Blvd
.
Dorms
Fields
DiningHall
Labs
State Transition TableState Transition Table
Current State Inputs
Next State
S TA TB S'
S0 0 X S1
S0 1 X S0
S1 X X S2
S2 X 0 S3
S2 X 1 S2
S3 X X S0
FSM Encoded State Transition FSM Encoded State Transition TableTable
State Encoding
S0 00
S1 01
S2 10
S3 11
Current State Inputs Next State
S1 S0 TA TB S'1 S'00 0 0 X 0 1
0 0 1 X 0 0
0 1 X X 1 0
1 0 X 0 1 1
1 0 X 1 1 0
1 1 X X 0 0
FSM Output TableFSM Output Table
Current State Outputs
S1 S0 LA1 LA0 LB1 LB0
0 0 0 0 1 0
0 1 0 1 1 0
1 0 1 0 0 0
1 1 1 0 0 1
Output Encoding
green 00
yellow 01
red 10
LA1 = S1
LA0 = S1S0
LB1 = S1
LB0 = S1S0
FSM Schematic: State RegisterFSM Schematic: State Register
S1
S0
S'1
S'0
CLK
state register
Reset
r
Next State LogicNext State Logic
S1
S0
S'1
S'0
CLK
next state logic state register
Reset
TA
TB
inputs
S1 S0
r
Output LogicOutput Logic
S1
S0
S'1
S'0
CLK
next state logic output logicstate register
Reset
LA1
LB1
LB0
LA0
TA
TB
inputs outputs
S1 S0
r
FSM Timing DiagramFSM Timing Diagram
CLK
Reset
TA
TB
S'1:0
S1:0
LA1:0
LB1:0
Cycle 1 Cycle 2 Cycle 3 Cycle 4 Cycle 5 Cycle 6 Cycle 7 Cycle 8 Cycle 9 Cycle 10
S1 (01) S2 (10) S3 (11) S0 (00)
t (sec)
??
??
S0 (00)
S0 (00) S1 (01) S2 (10) S3 (11) S1 (01)
??
??
0 5 10 15 20 25 30 35 40 45
Green (00)
Red (10)
S0 (00)
Yellow (01) Red (10) Green (00)
Green (00) Red (10)Yellow (01)
S0LA: greenLB: red
S1LA: yellowLB: red
S3LA: redLB: yellow
S2LA: redLB: green
TATA
TB
TB
ResetS1
S0
S'1
S'0
CLK
next state logic output logicstate register
Reset
LA1
LB1
LB0
LA0
TA
TB
inputs outputs
S1 S0
r
Current State Inputs Next State
S1 S0 TA TB S'1 S'00 0 0 X 0 1
0 0 1 X 0 0
0 1 X X 1 0
1 0 X 0 1 1
1 0 X 1 1 0
1 1 X X 0 0
State EncodingState Encoding Binary encoding: i.e., for four states, 00, 01, Binary encoding: i.e., for four states, 00, 01,
10, 1110, 11 One-hot encodingOne-hot encoding
One state bit per stateOne state bit per state Only one state bit is HIGH at onceOnly one state bit is HIGH at once I.e., for four states, 0001, 0010, 0100, 1000I.e., for four states, 0001, 0010, 0100, 1000 Requires more flip-flopsRequires more flip-flops Often next state and output logic is simplerOften next state and output logic is simpler Synthesizer will often use one-hot (you can change)Synthesizer will often use one-hot (you can change)
36
Moore State DiagramMoore State Diagram
State/OutputInputs
Mealy State DiagramMealy State Diagram Output depends on Output depends on
input and stateinput and state
37
Input/Output
38
State Table vs. DiagramState Table vs. Diagram Same informationSame information Table is perhaps easier to fill in from Table is perhaps easier to fill in from
descriptiondescription Diagram is perhaps easier to understandDiagram is perhaps easier to understand
You can label states with English descriptionYou can label states with English description
39
Design ProcedureDesign Procedure Take problem description and refine it into a Take problem description and refine it into a
state table or diagramstate table or diagram Assign codes to the statesAssign codes to the states Derive Boolean equations and implementDerive Boolean equations and implement
Or, write Verilog and compileOr, write Verilog and compileSee example next classSee example next classDesigning with gates and FFs more involved because you Designing with gates and FFs more involved because you
have to derive input and output functionshave to derive input and output functions
40
Example – Sequence RecognizerExample – Sequence Recognizer Circuit has input, X, and output, ZCircuit has input, X, and output, Z Recognizes sequence 1101 on XRecognizes sequence 1101 on X
Specifically, if X has been 110 and next bit is 1, make Specifically, if X has been 110 and next bit is 1, make Z highZ high
41
How to Design StatesHow to Design States States States rememberremember past history past history Clearly must remember we’ve seen 110 when Clearly must remember we’ve seen 110 when
next 1 comes alongnext 1 comes along
Tell me one necessary stateTell me one necessary state
42
Beginning StateBeginning State Start state: let’s call it AStart state: let’s call it A If 1 appears, move to next state BIf 1 appears, move to next state B
Input / Output
43
Second 1Second 1 New state, CNew state, C To reach C, must have seen 11To reach C, must have seen 11
44
Next a 0Next a 0 If 110 has been received, go to DIf 110 has been received, go to D Next 1 will generate a 1 on output ZNext 1 will generate a 1 on output Z
45
What else?What else? What happens to arrow on right?What happens to arrow on right? Must go to some state.Must go to some state. Where?Where?
46
What Sequence?What Sequence? Here we have to interpret problemHere we have to interpret problem We’ve just seen 01We’ve just seen 01
Is this beginning of new 1101?Is this beginning of new 1101? Or do we need to start over w/ another 1?Or do we need to start over w/ another 1?
Textbook: decides that it’s beginning (01…)Textbook: decides that it’s beginning (01…)
47
Cover every possibilityCover every possibility Well, must have every possibility out of every Well, must have every possibility out of every
statestate In this case, just two: X = 0 or 1In this case, just two: X = 0 or 1 You fill in other casesYou fill in other cases
48
Fill inFill in
49
Full AnswerFull Answer
50
State MinimizationState Minimization When we make state diagram, do we need all When we make state diagram, do we need all
those states?those states? Some may be redundantSome may be redundant State minimization procedures can be usedState minimization procedures can be used
We won’t cover nowWe won’t cover now
51
How to code FSM in VerilogHow to code FSM in Verilog Case statement very useful here!Case statement very useful here!
But first, let’s look at the parameter statementBut first, let’s look at the parameter statement
52
Parameter – Just ShorthandParameter – Just Shorthandmodule seq_rec (CLK, RESET, X, Z);module seq_rec (CLK, RESET, X, Z);input CLK, RESET, X;input CLK, RESET, X;output Z;output Z;
reg [1:0] state, next_state;reg [1:0] state, next_state;
parameter A = 2'b00, B = 2'b01, parameter A = 2'b00, B = 2'b01, C = 2 'b10, D = 2'b11;C = 2 'b10, D = 2'b11;
Notice that we’ve assigned codes to the states – more later
53
Next StateNext State
always @(X or state)always @(X or state)beginbegin
case (state)case (state) A: if (X == 1)A: if (X == 1)
next_state <= B;next_state <= B; elseelse
next_state <= A;next_state <= A; B: if(X) next_state <= C;else next_state <= A;B: if(X) next_state <= C;else next_state <= A; C: if(X) next_state <= C;else next_state <= D;C: if(X) next_state <= C;else next_state <= D; D: if(X) next_state <= B;else next_state <= A;D: if(X) next_state <= B;else next_state <= A;endcaseendcase
endend
The last 3 cases do same thing.Just sparse syntax.
54
On Reset or CLKOn Reset or CLKalways @(posedge CLK or posedge RESET)always @(posedge CLK or posedge RESET)beginbeginif (RESET == 1)if (RESET == 1)
state <= A;state <= A;elseelse
state <= next_state;state <= next_state;endend
Notice that state only gets updatedon posedge of clock (or on reset)
55
OutputOutputalways @(X or state)always @(X or state)beginbegincase(state)case(state)
A: Z <= 0;A: Z <= 0;B: Z <= 0;B: Z <= 0;C: Z <= 0;C: Z <= 0;D: Z <= X ? 1 : 0;D: Z <= X ? 1 : 0;
endcaseendcaseendend
56
Comment on CodeComment on Code Could shortenCould shorten Don’t need Don’t need next_statenext_state, for example, for example
Can just set state on clockCan just set state on clock
Don’t need three Don’t need three alwaysalways clauses clauses Although it’s clearer to have combinational code be separateAlthough it’s clearer to have combinational code be separate
Template helps synthesizerTemplate helps synthesizer Check to see whether your state machines were recognizedCheck to see whether your state machines were recognized
57
WorkWork Read 3.5-3.6Read 3.5-3.6 Might be good to look at Chapter 4 (Verilog Might be good to look at Chapter 4 (Verilog
only)only)
58
TodayToday More VerilogMore Verilog Simple state machinesSimple state machines
How to code them in VerilogHow to code them in Verilog
Next TimeNext Time Look at Moore equivalent of sequence recognizerLook at Moore equivalent of sequence recognizer Delays and TimingDelays and Timing
ReadRead Textbook Ch. 3.4-3.6Textbook Ch. 3.4-3.6
59