comp541 state machines – 2 registers and counters
DESCRIPTION
COMP541 State Machines – 2 Registers and Counters. Montek Singh Feb 11, 2010. Topics. Lab preview Verilog styles for FSM Don’t forget to check synthesis output and console msgs. State machine styles Moore vs. Mealy Building blocks: registers and counters. - PowerPoint PPT PresentationTRANSCRIPT
1
COMP541COMP541
State Machines – 2State Machines – 2Registers and CountersRegisters and Counters
Montek SinghMontek Singh
Feb 11, 2010Feb 11, 2010
TopicsTopics Lab previewLab preview Verilog styles for FSMVerilog styles for FSM
Don’t forget to check synthesis output and console Don’t forget to check synthesis output and console msgs.msgs.
State machine stylesState machine styles Moore vs. MealyMoore vs. Mealy
Building blocks: registers and countersBuilding blocks: registers and counters
2
Lab Preview: Buttons and Lab Preview: Buttons and DebouncingDebouncing Button Button normally highnormally high
press pulls it press pulls it lowlow Mechanical switches Mechanical switches
“bounce”“bounce” vibrations cause them to go to vibrations cause them to go to
1 and 0 a number of times1 and 0 a number of times hundreds of times!hundreds of times!
We’ll want toWe’ll want to ““Debounce”: Debounce”: Any ideas?Any ideas? Synchronize with clockSynchronize with clock
Think about:Think about: What does it mean to “press What does it mean to “press
the button”? Think carefully!!the button”? Think carefully!! What if button is held down for What if button is held down for
a long time?a long time? 3
Verilog Styles for FSMVerilog Styles for FSM Try to explain what synthesizer is Try to explain what synthesizer is
doingdoingRead the messages on the consoleRead the messages on the console
4
Pitfall: Beware of Unexpected Pitfall: Beware of Unexpected Latches!Latches! You can easily specify latches You can easily specify latches unexpectedlyunexpectedly
Hangover from programming in C…!Hangover from programming in C…!
alwaysalways will try to synthesize FF: will try to synthesize FF:
if (select) out <= A;if (select) out <= A;
if (!select) out <= B;if (!select) out <= B; FF added to save old value if condition is falseFF added to save old value if condition is false
To avoid extra FF, cover all possibilities:To avoid extra FF, cover all possibilities:
if (select) out <= A;if (select) out <= A;
elseelse out <= B; out <= B;
5
FSM Verilog: Using One Always BlockFSM Verilog: Using One Always Blockalways@(posedge clk) beginalways@(posedge clk) begin
case (state)case (state) s1: if (x1 == 1'b1) begins1: if (x1 == 1'b1) begin
state <= s2; outp <= 1'b1;state <= s2; outp <= 1'b1; endend else beginelse begin
state <= s3; outp <= 1'b0;state <= s3; outp <= 1'b0; endend
s2: begins2: begin state <= s4; outp <= 1'b1;state <= s4; outp <= 1'b1; endend s3: begins3: begin state <= s4; outp <= 1'b0;state <= s4; outp <= 1'b0; endend s4: begins4: begin state <= s1; outp <= 1'b0;state <= s1; outp <= 1'b0; endend endcaseendcaseendend
6
~x1
Synthesis OutputSynthesis OutputSynthesizing Unit <v_fsm_1>.Synthesizing Unit <v_fsm_1>. Related source file is "v_fsm_1.v".Related source file is "v_fsm_1.v". Found finite state machine <FSM_0> for signal <state>.Found finite state machine <FSM_0> for signal <state>. ---------------------------------------------------------------------------------------------------------------------------------------------- | States | 4 || States | 4 | | Transitions | 5 || Transitions | 5 | | Inputs | 1 || Inputs | 1 | | Outputs | 4 || Outputs | 4 | | Clock | clk (rising_edge) || Clock | clk (rising_edge) | | Reset | reset (positive) || Reset | reset (positive) | | Reset type | asynchronous || Reset type | asynchronous | | Reset State | 00 || Reset State | 00 | | Power Up State | 00 || Power Up State | 00 | | Encoding | automatic || Encoding | automatic | | Implementation | LUT || Implementation | LUT | ---------------------------------------------------------------------------------------------------------------------------------------------- Found 1-bit register for signal <outp>.Found 1-bit register for signal <outp>. Summary:Summary:
inferred 1 Finite State Machine(s).inferred 1 Finite State Machine(s).inferred 1 D-type flip-flop(s).inferred 1 D-type flip-flop(s).
7
Split Output OffSplit Output Off Separate Separate alwaysalways for outp for outp
8
CodeCodealways @(posedge clk)always @(posedge clk) case (state)case (state)
s1: if (x1 == 1'b1)s1: if (x1 == 1'b1) state <= s2;state <= s2; elseelse state <= s3;state <= s3; s2: state <= s4;s2: state <= s4; s3: state <= s4;s3: state <= s4; s4: state <= s1;s4: state <= s1; endcaseendcase always @(state)always @(state)
case (state)case (state) s1: outp <= 1'b1;s1: outp <= 1'b1; s2: outp <= 1'b1;s2: outp <= 1'b1; s3: outp <= 1'b0;s3: outp <= 1'b0; s4: outp <= 1'b0;s4: outp <= 1'b0; endcaseendcase
9
Synthesis (no latch)Synthesis (no latch)Synthesizing Unit <v_fsm_2>.Synthesizing Unit <v_fsm_2>. Related source file is "v_fsm_2.v".Related source file is "v_fsm_2.v". Found finite state machine <FSM_0> for signal <state>.Found finite state machine <FSM_0> for signal <state>. ---------------------------------------------------------------------------------------------------------------------------------------------- | States | 4 || States | 4 | | Transitions | 5 || Transitions | 5 | | Inputs | 1 || Inputs | 1 | | Outputs | 1 || Outputs | 1 | | Clock | clk (rising_edge) || Clock | clk (rising_edge) | | Reset | reset (positive) || Reset | reset (positive) | | Reset type | asynchronous || Reset type | asynchronous | | Reset State | 00 || Reset State | 00 | | Power Up State | 00 || Power Up State | 00 | | Encoding | automatic || Encoding | automatic | | Implementation | LUT || Implementation | LUT | ---------------------------------------------------------------------------------------------------------------------------------------------- Summary:Summary:
inferred 1 Finite State Machine(s).inferred 1 Finite State Machine(s).Unit <v_fsm_2> synthesized.Unit <v_fsm_2> synthesized.
10
Textbook Uses 3 Textbook Uses 3 alwaysalways Blocks Blocks
11
Three Three alwaysalways Blocks Blocks always @(posedge clk)always @(posedge clk) beginbegin
state <= next_state;state <= next_state; endend
always @(state or x1)always @(state or x1) beginbegin case (state)case (state) s1: if (x1==1'b1)s1: if (x1==1'b1) next_state <= s2;next_state <= s2; elseelse next_state <= s3;next_state <= s3; s2: next_state <= s4;s2: next_state <= s4; s3: next_state <= s4;s3: next_state <= s4; s4: next_state <= s1;s4: next_state <= s1; endcaseendcase endend
always @(state)always @(state) beginbegin case (state)case (state) s1: outp <= 1'b1;s1: outp <= 1'b1; s2: outp <= 1'b1;s2: outp <= 1'b1; s3: outp <= 1'b0;s3: outp <= 1'b0; s4: outp <= 1'b0;s4: outp <= 1'b0; endcaseendcase endend
12
Synthesis (again, no latch)Synthesis (again, no latch)Synthesizing Unit <v_fsm_3>.Synthesizing Unit <v_fsm_3>. Related source file is "v_fsm_3.v".Related source file is "v_fsm_3.v". Found finite state machine <FSM_0> for signal <state>.Found finite state machine <FSM_0> for signal <state>. ---------------------------------------------------------------------------------------------------------------------------------------------- | States | 4 || States | 4 | | Transitions | 5 || Transitions | 5 | | Inputs | 1 || Inputs | 1 | | Outputs | 1 || Outputs | 1 | | Clock | clk (rising_edge) || Clock | clk (rising_edge) | | Reset | reset (positive) || Reset | reset (positive) | | Reset type | asynchronous || Reset type | asynchronous | | Reset State | 00 || Reset State | 00 | | Power Up State | 00 || Power Up State | 00 | | Encoding | automatic || Encoding | automatic | | Implementation | LUT || Implementation | LUT | ---------------------------------------------------------------------------------------------------------------------------------------------- Summary:Summary:
inferred 1 Finite State Machine(s).inferred 1 Finite State Machine(s).Unit <v_fsm_3> synthesized.Unit <v_fsm_3> synthesized.
13
My PreferenceMy Preference The one with 2 The one with 2 alwaysalways blocks blocks Less prone to error than 1 Less prone to error than 1 alwaysalways Easy to visualize the state transitionsEasy to visualize the state transitions
14
State EncodingState Encoding So far we’ve used So far we’ve used binarybinary encoding encoding Not necessarily bestNot necessarily best
XST chooses one to minimize hardwareXST chooses one to minimize hardware
Can change by right-clicking Can change by right-clicking Synthesize-XSTSynthesize-XST Possible encodings next slidesPossible encodings next slides
15
Gray Code (synthesis output)Gray Code (synthesis output)========================================================================================================================* Advanced HDL Synthesis ** Advanced HDL Synthesis *========================================================================================================================
Analyzing FSM <FSM_0> for best encoding.Analyzing FSM <FSM_0> for best encoding.Optimizing FSM <state> on signal <state[1:2]> with gray encoding.Optimizing FSM <state> on signal <state[1:2]> with gray encoding.-------------------------------------- State | EncodingState | Encoding-------------------------------------- 00 | 0000 | 00 01 | 0101 | 01 10 | 1110 | 11 11 | 1011 | 10--------------------------------------
16
One-Hot EncodingOne-Hot EncodingOptimizing FSM <state> on signal <state[1:4]> Optimizing FSM <state> on signal <state[1:4]> with one-hot encoding.with one-hot encoding.
-------------------------------------- State | EncodingState | Encoding-------------------------------------- 00 | 000100 | 0001 01 | 001001 | 0010 10 | 010010 | 0100 11 | 100011 | 1000--------------------------------------
17
Hmmm, state register grew.
What’s up?
Safe Implementation ModeSafe Implementation Mode “ “XST can add logic to your XST can add logic to your
FSM implementation that FSM implementation that will let your state machine will let your state machine recover from an invalid recover from an invalid state. If during its state. If during its execution, a state machine execution, a state machine gets into an invalid state, gets into an invalid state, the logic added by XST will the logic added by XST will bring it back to a known bring it back to a known state, called a recovery state, called a recovery state. This is known as Safe state. This is known as Safe Implementation mode.” Implementation mode.” from XST manualfrom XST manual
18
Moore vs. Mealy FSMs?Moore vs. Mealy FSMs? So, is there a practical difference?So, is there a practical difference?
19
CLKM Nk knext
statelogic
outputlogic
Moore FSM
CLKM Nk knext
statelogic
outputlogic
inputs
inputs
outputs
outputsstate
statenextstate
nextstate
Mealy FSM
Moore vs Mealy RecognizerMoore vs Mealy Recognizer
reset
Moore FSM
S00
S10
S20
S30
S41
0
1 1 0 1
1
01 00
reset
S0 S1 S2 S3
0/0
1/0 1/0 0/01/1
0/01/0
0/0
Mealy FSM
Mealy FSM: arcs indicate input/output
Moore and Mealy Timing DiagramMoore and Mealy Timing Diagram
Mealy Machine
Moore Machine
CLK
Reset
A
S
Y
S
Y
Cycle 1 Cycle 2 Cycle 3 Cycle 4 Cycle 5 Cycle 6 Cycle 7 Cycle 8 Cycle 9 Cycle 10
S0 S3?? S1 S2 S4 S4S2 S3 S0
1 1 0 1 1 0 1 01
S2
S0 S3?? S1 S2 S1 S1S2 S3 S0S2
Moore vs. Mealy FSM SchematicMoore vs. Mealy FSM Schematic MooreMoore MealyMealy
S2
S1
S0
S'2
S'1
S'0
Y
CLK
Reset
A
S2
S1
S0
S'1
S'0
CLK
Reset
S1
S0
A
Y
S0S1
23
Registers and Counters: Registers and Counters: DefinitionsDefinitions Register – a set of flip-flopsRegister – a set of flip-flops
May include extensive logic to control state transitionMay include extensive logic to control state transitionMay allow shiftingMay allow shifting
registerregister also refers to fast memory for storing data in also refers to fast memory for storing data in a computera computer
CounterCounter Register that goes through sequence of states as it is Register that goes through sequence of states as it is
clockedclocked
Simple RegisterSimple Register Store D Store D On posedge of ClockOn posedge of Clock Clear signal normally Clear signal normally
highhigh Power-up resetPower-up reset
SymbolSymbol
24
ClockingClocking Typically don’t want to load every clockTypically don’t want to load every clock Can gate the clockCan gate the clock
But added clock skew is a problemBut added clock skew is a problem
25
EnableEnable If If loadload H, then D is H, then D is
gated throughgated through Otherwise, Q is fed Otherwise, Q is fed
backback Keep same valueKeep same value
No clock gatingNo clock gating
26
Did this because D FF doesn’t have a “no Did this because D FF doesn’t have a “no change” behaviorchange” behavior
CountersCounters Counter is a register – has stateCounter is a register – has state Also goes through sequence of states – counts Also goes through sequence of states – counts
– on clock or other pulses– on clock or other pulses Binary counter Binary counter
Counts through binary sequenceCounts through binary sequence nn bit counter counts from 0 to 2 bit counter counts from 0 to 2nn
27
Ripple CounterRipple Counter SimpleSimple So Q will alternate 1 So Q will alternate 1
and 0and 0
Why called ripple Why called ripple counter?counter?
28
Synchronous CountersSynchronous Counters Ripple counter is easyRipple counter is easy
rippling nature may cause problems, thoughrippling nature may cause problems, thoughdelay increases with bit width!delay increases with bit width!
Synchronous counter most commonSynchronous counter most common meaning every flip-flop is driven by the same clockmeaning every flip-flop is driven by the same clock
29
Synchronous CounterSynchronous Counter Same clock fed to Same clock fed to
all flip-flopsall flip-flops But…But…
delay again increases delay again increases with bit widthwith bit width
30
Parallel DesignParallel Design Now “constant” delayNow “constant” delay
higher order bits need higher order bits need gates with more fan-in gates with more fan-in thoughthough
Can gang these to Can gang these to make longer serial-make longer serial-parallel counterparallel counter
31
Verilog Counter (simple)Verilog Counter (simple)module count (CLK, EN, Q);module count (CLK, EN, Q);
input CLK, EN;input CLK, EN;output [3:0] Q;output [3:0] Q;
reg [3:0] Q;reg [3:0] Q;
always@(posedge CLK)always@(posedge CLK)beginbegin
if (EN)if (EN) Q <= Q + 4'b0001;Q <= Q + 4'b0001;
endendendmoduleendmodule
32
Verilog Counter (from book)Verilog Counter (from book)module count_4_r_v (CLK, RESET, EN, Q, CO);module count_4_r_v (CLK, RESET, EN, Q, CO);
input CLK, RESET, EN;input CLK, RESET, EN;output [3:0] Q;output [3:0] Q;output CO;output CO;
reg [3:0] Q;reg [3:0] Q;assign CO = (count == 4'b1111 && EN == 1’b1) ? 1 : 0;assign CO = (count == 4'b1111 && EN == 1’b1) ? 1 : 0;always@(posedge CLK or posedge RESET)always@(posedge CLK or posedge RESET)beginbegin
if (RESET)if (RESET) Q <= 4'b0000;Q <= 4'b0000;else if (EN)else if (EN) Q <= Q + 4'b0001;Q <= Q + 4'b0001;
endendendmoduleendmodule
33
Arbitrary CountArbitrary Count One more type of counter is usefulOne more type of counter is useful Count an arbitrary sequenceCount an arbitrary sequence
maybe you need a sequence of statesmaybe you need a sequence of states maybe a pseudo-random sequencemaybe a pseudo-random sequence
34
Circuit and State DiagramCircuit and State Diagram
35
Shift RegistersShift Registers Capability to shift bitsCapability to shift bits
In one or both directionsIn one or both directions
Why?Why? Part of standard CPU instruction setPart of standard CPU instruction set Cheap multiplicationCheap multiplication Serial communicationsSerial communications
Just a chain of flip-flopsJust a chain of flip-flops
36
Simple 4-Bit Shift RegisterSimple 4-Bit Shift Register Clocked in commonClocked in common Just serial in and serial outJust serial in and serial out Is this a FIFO?Is this a FIFO?
37
Verilog for Simple 4-bit Shift Verilog for Simple 4-bit Shift RegisterRegistermodule srg_4_r (CLK, SI, Q, SO);module srg_4_r (CLK, SI, Q, SO);
input CLK, SI;input CLK, SI;output [3:0] Q;output [3:0] Q;output SO;output SO;
reg [3:0] Q;reg [3:0] Q;assign SO = Q[3];assign SO = Q[3];
always@(posedge CLK)always@(posedge CLK)beginbegin
Q <= {Q[2:0], SI};Q <= {Q[2:0], SI};endend
endmoduleendmodule
38
SymbolSymbol How about enabling/disabling?How about enabling/disabling?
We could gate the clockWe could gate the clockBut have to potentially deal with skewBut have to potentially deal with skew
Usually an enable providedUsually an enable provided
39
Parallel LoadParallel Load Can provide parallel outputs from flip-flopsCan provide parallel outputs from flip-flops And also parallel inputsAnd also parallel inputs
40
SchematicSchematic
41
DetailNext
DetailDetail
42
Why is this useful?Why is this useful? Basis for serial communicationsBasis for serial communications KeyboardKeyboard Serial portSerial port
Initially to connect to terminalsInitially to connect to terminals Now mainly for modemNow mainly for modem
USBUSB FirewireFirewire
43
ExampleExample
44
Clocked 4 times
Could shift data in, or parallel load
What’s on wire at each clock?
Table Showing ShiftTable Showing Shift
45
Serial vs. Parallel TransferSerial vs. Parallel Transfer Parallel transfer – over as many wires as word Parallel transfer – over as many wires as word
(for example)(for example) Serial transfer – over a single wireSerial transfer – over a single wire
Trade time for wiresTrade time for wires Takes Takes n n times longertimes longer
although lately, may have speed advantages over parallel although lately, may have speed advantages over parallel in very high-speed scenariosin very high-speed scenarios
e.g., USB (Universal Serial Bus)e.g., USB (Universal Serial Bus)
46
Bidirectional Shift RegisterBidirectional Shift Register Shift either wayShift either way Now we have following possible inputsNow we have following possible inputs
Parallel loadParallel load Shift from leftShift from left Shift from rightShift from right Also “no change”Also “no change”
Schematic nextSchematic next
47
SchematicSchematic
48
Next WeekNext Week How to generate a VGA signalHow to generate a VGA signal Timing of sequential logicTiming of sequential logic
Then on toThen on to Arithmetic circuitsArithmetic circuits MemoriesMemories
49