sequential logic design - eth z · carnegie mellon 3 introduction ¢ outputs of sequential logic...
TRANSCRIPT
Carnegie Mellon
1
DesignofDigitalCircuits2017Srdjan CapkunOnur Mutlu(Gueststarring:FrankK.Gürkaynak andAanjhan Ranganathan)
AdaptedfromDigitalDesignandComputerArchitecture,DavidMoneyHarris&SarahL.Harris©2007Elsevier
http://www.syssec.ethz.ch/education/Digitaltechnik_17
SequentialLogicDesign
Carnegie Mellon
2
Whatwillwelearn?¢ Howcanacircuitrememberavalue
¢ Differenttypesofmemorizingelements
¢ FiniteStateMachines
¢ HowtowriteFiniteStateMachinesinVerilog
Carnegie Mellon
3
Introduction¢ Outputsofsequentiallogicdependoncurrentand prior
inputvalues– ithasmemory.
¢ SequentialCircuits:§ Givesequencetoeventswhichallowsorderingofoperations§ Needaspecialcircuittostorethecurrentstateofcircuit
¢ Controllingwhentochangestate§ ASYNCHROUNOUS
Assoonascircuitfinishes,itmovestonextstate§ SYNCHRONOUS
Aglobalcontrolsignal(clock)thattellseveryonewhentomove
(anarchic)
(communist) – THIS LECTURE
Carnegie Mellon
4
SequentialCircuit
Combinational+Memory=Sequential
CombinationalCircuitinpu
ts
outputs
MemoryElement
¢ WeknowCombinationalCircuits,justneedsomeMEMORY
Carnegie Mellon
5
Howcanacircuitremember?¢ Bistable circuitscanhavetwodistinctstates
§ Oncetheyareinonestate,theywillremainthere.
¢ TheLoopkeepsthestatestable
0 1 0=State0
Carnegie Mellon
6
Howcanacircuitremember?¢ Bistable circuitscanhavetwodistinctstates
§ Oncetheyareinonestate,theywillremainthere.
¢ TheLoopkeepsthestatestable
1 0 1=State1
Carnegie Mellon
7
Howcanacircuitremember?¢ Bistable circuitscanhavetwodistinctstates
§ Oncetheyareinonestate,theywillremainthere.
¢ Buthowcanwemovefromonestatetoanother?
Carnegie Mellon
8
Howcanacircuitremember?¢ Bistable circuitscanhavetwodistinctstates
§ Oncetheyareinonestate,theywillremainthere.
¢ Buthowcanwemovefromonestatetoanother?§ Weaddoneswitchtobreaktheloopandatthesametimeadd
anotherswitchthatconnectsaninputtothecircuit
Carnegie Mellon
9
TheDLatch¢ DLatchisthebasicbi-stablecircuitusedinmodernCMOS.
§ Theclockcontrolstheswitches.Onlyoneisactive atatime.§ TraditionallytheinputiscalledD(Data)andtheoutputQ
𝑫
𝑪𝒍𝒌
𝑸
Carnegie Mellon
10
TheDLatchhastwomodes¢ Latchmode,loopisactive,inputdisconnected,keepsstate
𝑫 𝑸 𝑸𝑸
Carnegie Mellon
11
TheDLatchhastwomodes¢ Latchmode,loopisactive,inputdisconnected,keepsstate
¢ Transparentmode,loopisinactive,inputisconnectedandpropagatestooutput
𝑫 𝑸 𝑸
𝑫 𝑫 𝑫𝑫
𝑸
Carnegie Mellon
12
SummaryDLatch¢ Simplebi-stablecircuit
§ Canbeusedtostorea0ora1.
¢ Hastwomodes§ Transparentmode:inputpropagatestooutput§ Latchmode:theoutputisstored(alsocalledopaquemode)
¢ Theclockcontrolsthemodesofoperation.§ Dependingonthetype,itmightbelatchistransparentwhenClk=1
orlatchistransparentwhenClk=0
Carnegie Mellon
13
DLatchiscommonlyused...but…¢ Itisabittrickytouse
§ Thereisalongtransparenttime,latchisnotstoring§ Problematicifwehaveaseriesoflatchesthatformapipeline
¢ Usuallyusedwithalternatingclocksforeachstage§ Ifonelatchistransparent atCLK=0thenextoneislatching§ Makesuretherearenottwotransparentlatchesinarow
¢ AFlip-Flop(FF)isacircuitthatcombinestwolatches§ AMaster latchthatistransparentwhenCLK=0§ AndaSlave latchthatistransparentwhenCLK=1(orviceversa)
¢ ThroughoutthislecturewewilluseFlip-Flops
Carnegie Mellon
14
Risingedgetrigerred DFlip-Flop¢ Twoinputs:CLK,D
¢ Function§ Theflip-flop“samples”DontherisingedgeofCLK§ WhenCLKrisesfrom0to1,DpassesthroughtoQ§ Otherwise,Qholdsitspreviousvalue§ QchangesonlyontherisingedgeofCLK
¢ Aflip-flopiscalledanedge-triggereddevicebecauseitisactivatedontheclockedge
D Flip-FlopSymbols
D QQ
Carnegie Mellon
15
DFlip-FlopInternalCircuit¢ Twoback-to-backlatches(L1andL2)controlledby
complementaryclocks§ WhenCLK=0
§ L1istransparent§ L2isopaque§ DpassesthroughtoN1
§ WhenCLK=1§ L2istransparent§ L1isopaque§ N1passesthroughtoQ
¢ Thus,ontheedgeoftheclock(whenCLKrisesfrom01)
¢ DpassesthroughtoQ
CLKD Q
Q
CLKD Q
Q
D N1
CLK
L1 L2
Carnegie Mellon
16
Registers¢ Multipleparallelflip-flopsthatstoremorethan1bit
CLK
D Q
D Q
D Q
D Q
D0
D1
D2
D3
Q0
Q1
Q2
Q3
D3:04 4
CLK
Q3:0
Carnegie Mellon
17
EnabledFlip-Flops¢ Inputs:CLK,D,EN
§ Theenableinput(EN)controlswhennewdata(D)isstored
¢ Function§ EN=1:DpassesthroughtoQontheclockedge§ EN=0:theflip-flopretainsitspreviousstate
InternalCircuit
D Q
CLKEN
DQ
0
1D QEN
Symbol
Carnegie Mellon
18
ResettableFlip-Flops¢ Inputs:CLK,D,Reset
§ TheResetisusedtosettheoutputto0.
¢ Function:§ Reset=1:Qisforcedto0§ Reset=0:theflip-flopbehaveslikeanordinaryDflip-flop
Symbols
D QReset
r
Carnegie Mellon
19
ResettableFlip-Flops¢ Two types:
§ Synchronous:resets at the clock edge only§ Asynchronous:resets immediately when Reset =1
¢ Asynchronously resettable flip-flop requires changing theinternal circuitry of the flip-flop (see Exercise 3.10)
¢ Synchronously resettable flip-flop?
Carnegie Mellon
20
ResettableFlip-Flops¢ Two types:
§ Synchronous:resets at the clock edge only§ Asynchronous:resets immediately when Reset =1
¢ Asynchronously resettable flip-flop requires changing theinternal circuitry of the flip-flop (see Exercise 3.10)
¢ Synchronously resettable flip-flop?
InternalCircuit
D Q
CLK
D QReset
Carnegie Mellon
21
SettableFlip-Flops¢ Inputs:CLK,D,Set
¢ Function:§ Set=1:Qissetto1§ Set=0:theflip-flopbehaveslikeanordinaryDflip-flop
Symbols
D QSet
s
Carnegie Mellon
22
SynchronousSequentialLogicDesign¢ Breakscyclicpathsbyinsertingregisters
§ Theseregisterscontainthestateofthesystem§ Thestatechangesattheclockedge,sowesaythesystemis
synchronizedtotheclock
¢ Rulesofsynchronoussequentialcircuitcomposition:§ Everycircuitelementiseitheraregisteroracombinationalcircuit§ Atleastonecircuitelementisaregister§ Allregistersreceivethesameclocksignal§ Everycyclicpathcontainsatleastoneregister
¢ Twocommonsynchronoussequentialcircuits§ FiniteStateMachines(FSMs)§ Pipelines
Carnegie Mellon
23
FiniteStateMachine(FSM)consistsof:¢ Stateregister:
§ Storethecurrentstateand§ Loadthenextstateattheclockedge§ Sequentialcircuit
¢ Nextstatelogic§ Determineswhatthenextstatewillbe§ Combinationalcircuit
¢ Outputlogic§ Generatestheoutputs§ CombinationalCircuit
NextState
CurrentState
S’ S
CLK
CL
Next StateLogic
NextState
CL
OutputLogic
Outputs
Carnegie Mellon
24
FiniteStateMachine(FSM)¢ FSMsgettheirnamebecauseacircuitwithkregisterscan
beinoneofafinitenumber(2k)ofuniquestates.
Carnegie Mellon
25
FiniteStateMachines(FSMs)¢ Nextstateisdeterminedbythecurrentstateandtheinputs
¢ Twotypesoffinitestatemachinesdifferintheoutputlogic:§ MooreFSM:outputsdependonlyonthecurrentstate§ MealyFSM:outputsdependonthecurrentstateandtheinputs
CLKM Nk knext
statelogic
outputlogic
Moore FSM
CLKM Nk knext
statelogic
outputlogic
inputs
inputs
outputs
outputsstate
statenextstate
nextstate
Mealy FSM
Carnegie Mellon
26
FiniteStateMachineExample¢ Trafficlightcontroller
§ 2inputs:Trafficsensors:TA,TB (TRUEwhenthere’straffic)§ 2outputs:Lights:LA,LB
TA
LA
TA
LB
TB
TB
LA
LB
Academic Ave.
BravadoBlvd.
Dorms
Fields
DiningHall
Labs
Carnegie Mellon
27
FSMBlackBox¢ Inputs:CLK,Reset,TA,TB
¢ Outputs:LA,LB
TA
TB
LA
LB
CLK
Reset
TrafficLight
Controller
Carnegie Mellon
28
FSMStateTransitionDiagram¢ MooreFSM:outputslabeledineachstate
§ States:Circles§ Transitions:Arcs
S0LA: greenLB: red
Reset
Carnegie Mellon
29
FSMStateTransitionDiagram¢ MooreFSM:outputslabeledineachstate
§ States:Circles§ Transitions:Arcs
TA
LA
TA
LB
TB
TB
LA
LB
Academic Ave.
BravadoBlvd.
Dorms
Fields
DiningHall
Labs
S0LA: greenLB: red
S1LA: yellowLB: red
S3LA: redLB: yellow
S2LA: redLB: green
TATA
TB
TB
Reset
Carnegie Mellon
30
FSMStateTransitionTable
CurrentState Inputs NextStateS TA TB S'S0 0 XS0 1 XS1 X XS2 X 0S2 X 1S3 X X
Carnegie Mellon
31
FSMStateTransitionTable
CurrentState Inputs NextStateS TA TB S'S0 0 X S1S0 1 X S0S1 X X S2S2 X 0 S3S2 X 1 S2S3 X X S0
Carnegie Mellon
32
FSMEncodedStateTransitionTable
CurrentState Inputs NextStateS1 S0 TA TB S'1 S'00 0 0 X0 0 1 X0 1 X X1 0 X 01 0 X 11 1 X X
State EncodingS0 00S1 01S2 10S3 11
Carnegie Mellon
33
FSMEncodedStateTransitionTable
CurrentState Inputs NextStateS1 S0 TA TB S'1 S'00 0 0 X 0 10 0 1 X 0 00 1 X X 1 01 0 X 0 1 11 0 X 1 1 01 1 X X 0 0
State EncodingS0 00S1 01S2 10S3 11
Carnegie Mellon
34
FSMEncodedStateTransitionTable
CurrentState Inputs NextStateS1 S0 TA TB S'1 S'00 0 0 X 0 10 0 1 X 0 00 1 X X 1 01 0 X 0 1 11 0 X 1 1 01 1 X X 0 0
State EncodingS0 00S1 01S2 10S3 11
S1’=(S1 ·S0)+(S1 ·S0 ·TB)+(S1 ·S0 ·TB)
S0’=(S1 ·S0 ·TA)+(S1 ·S0 ·TB)
Carnegie Mellon
35
FSMEncodedStateTransitionTable
CurrentState Inputs NextStateS1 S0 TA TB S'1 S'00 0 0 X 0 10 0 1 X 0 00 1 X X 1 01 0 X 0 1 11 0 X 1 1 01 1 X X 0 0
State EncodingS0 00S1 01S2 10S3 11
S1’=S1 xor S0 Simplification (Inspection or K-Maps)
S0’=(S1 ·S0 ·TA)+(S1 ·S0 ·TB)
Carnegie Mellon
36
FSMOutputTableCurrentState OutputsS1 S0 LA LB0 00 11 01 1
Carnegie Mellon
37
FSMOutputTableCurrentState OutputsS1 S0 LA LB0 0 green red0 1 yellow red1 0 red green1 1 red yellow
Output Encodinggreen 00yellow 01red 10
Carnegie Mellon
38
FSMOutputTableCurrentState OutputsS1 S0 LA1 LA0 LB1 LB00 0 0 0 1 00 1 0 1 1 01 0 1 0 0 01 1 1 0 0 1
Output Encodinggreen 00yellow 01red 10
Carnegie Mellon
39
FSMOutputTableCurrentState OutputsS1 S0 LA1 LA0 LB1 LB00 0 0 0 1 00 1 0 1 1 01 0 1 0 0 01 1 1 0 0 1
Output Encodinggreen 00yellow 01red 10
LA1 =S1LA0 =S1 ·S0LB1 =S1LB0 =S1 ·S0
Carnegie Mellon
40
FSMSchematic:StateRegister
S1
S0
S'1
S'0
CLK
state register
Resetr
Carnegie Mellon
41
FSMSchematic:NextStateLogic
S1
S0
S'1
S'0
CLK
next state logic state register
Reset
TA
TB
inputs
S1 S0
r
Carnegie Mellon
42
FSMSchematic:OutputLogic
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
Carnegie Mellon
43
FSMTimingDiagram S0LA: greenLB: red
S1LA: yellowLB: red
S3LA: redLB: yellow
S2LA: redLB: green
TATA
TB
TB
Reset
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)
Carnegie Mellon
44
FSMStateEncoding¢ Binaryencoding:i.e.,forfourstates,00,01,10,11
¢ One-hotencoding§ Onestatebitperstate§ OnlyonestatebitisHIGHatonce§ I.e.,forfourstates,0001,0010,0100,1000§ Requiresmoreflip-flops§ Oftennextstateandoutputlogicissimpler
Carnegie Mellon
45
CLKM Nk knext
statelogic
outputlogic
Moore FSM
CLKM Nk knext
statelogic
outputlogic
inputs
inputs
outputs
outputsstate
statenextstate
nextstate
Mealy FSM
Moorevs.MealyFSM¢ AlyssaP.Hackerhasasnailthatcrawlsdownapapertape
with1’sand0’sonit.Thesnailsmileswheneverthelastfourdigitsithascrawledoverare1101.DesignMooreandMealyFSMsofthesnail’sbrain.
Carnegie Mellon
46
reset
Moore FSM
S00
S10
S20
S30
S41
0
1 1 0 1
1
01 00
StateTransitionDiagrams(snail- 1101)
¢ MealyFSM:arcsindicateinput/output
reset
S0 S1 S2 S30/0
1/0 1/0 0/01/1
0/01/0
0/0
Mealy FSM
Carnegie Mellon
47
FSMDesignProcedure§ Prepare
§ Identifytheinputsandoutputs§ Sketchastatetransitiondiagram§ Writeastatetransitiontable§ Selectstateencodings
§ ForaMooremachine:§ Rewritethestatetransitiontablewiththeselectedstateencodings
§ Writetheoutputtable§ ForaMealymachine:
§ Rewritethecombinedstatetransitionandoutputtablewiththeselectedstateencodings
§ WriteBooleanequationsforthenextstateandoutputlogic§ Sketchthecircuitschematic
Carnegie Mellon
48
DesignofDigitalCircuits2017Srdjan CapkunOnur Mutlu(Gueststarring:FrankK.Gürkaynak andAanjhan Ranganathan)
AdaptedfromDigitalDesignandComputerArchitecture,DavidMoneyHarris&SarahL.Harris©2007Elsevier
http://www.syssec.ethz.ch/education/Digitaltechnik_17
SequentialLogicDesign
Carnegie Mellon
49
LastWeekinVerilog¢ WehaveseenanoverviewofVerilog
¢ Discussedbehavioralandstructuralmodeling
¢ Showedcombinationallogicconstructs
Thisweek¢ SequentialcircuitdescriptioninVerilog
¢ Developingtestbenches forsimulation
Carnegie Mellon
50
SequentialCircuit
Combinational+Memory=Sequential
CombinationalCircuitinpu
ts
outputs
MemoryElement
¢ WeknowCombinationalCircuits,justneedsomeMEMORY
Carnegie Mellon
51
SequentialLogicinVerilog¢ Defineblocksthathavememory
§ Flip-Flops,Latches,FiniteStateMachines
¢ SequentialLogicistriggeredbya‘CLOCK’event§ Latchesaresensitivetolevelofthesignal§ Flip-flopsaresensitivetothetransitioningofclock
¢ Combinationalconstructsarenotsufficient§ Weneednewconstructs:
§ always§ initial
Carnegie Mellon
52
alwaysStatement,DefiningProcessesalways @ (sensitivity list)
statement;
¢ Whenevertheeventinthesensitivitylistoccurs,thestatementisexecuted
Carnegie Mellon
53
Example:DFlip-Flopmodule flop(input clk,
input [3:0] d, output reg [3:0] q);
always @ (posedge clk)q <= d; // pronounced “q gets d”
endmodule
Carnegie Mellon
54
Example:DFlip-Flopmodule flop(input clk,
input [3:0] d, output reg [3:0] q);
always @ (posedge clk)q <= d; // pronounced “q gets d”
endmodule
¢ Theposedge definesarisingedge(transitionfrom0to1).
¢ Thisprocesswilltriggeronlyiftheclk signalrises.
¢ Oncetheclk signalrises:thevalueofdwillbecopiedtoq
Carnegie Mellon
55
Example:DFlip-Flopmodule flop(input clk,
input [3:0] d, output reg [3:0] q);
always @ (posedge clk)q <= d; // pronounced “q gets d”
endmodule
¢ ‘assign’statementisnotusedwithinalwaysblock
¢ The<=describesa‘non-blocking’assignment§ Wewillseethedifferencebetween‘blockingassignment’and
‘non-blocking’assignmentinawhile
Carnegie Mellon
56
Example:DFlip-Flopmodule flop(input clk,
input [3:0] d, output reg [3:0] q);
always @ (posedge clk)q <= d; // pronounced “q gets d”
endmodule
¢ Assignedvariablesneedtobedeclaredasreg
¢ Thenamereg doesnotnecessarilymeanthatthevalueisaregister.(Itcouldbe,itdoesnothavetobe).
¢ Wewillseeexampleslater
Carnegie Mellon
57
DFlip-FlopwithAsynchronousResetmodule flop_ar (input clk,
input reset, input [3:0] d, output reg [3:0] q);
always @ (posedge clk, negedge reset)begin
if (reset == ‘0’) q <= 0; // when resetelse q <= d; // when clk
endendmodule
¢ Inthisexample:twoeventscantriggertheprocess:§ Arisingedge onclk§ Afallingedgeonreset
Carnegie Mellon
58
DFlip-FlopwithAsynchronousResetmodule flop_ar (input clk,
input reset, input [3:0] d, output reg [3:0] q);
always @ (posedge clk, negedge reset)begin
if (reset == ‘0’) q <= 0; // when resetelse q <= d; // when clk
endendmodule
¢ Forlongerstatementsabeginendpaircanbeused§ Inthisexampleitwasnotnecessary
¢ Thealwaysblockishighlighted
Carnegie Mellon
59
DFlip-FlopwithAsynchronousResetmodule flop_ar (input clk,
input reset, input [3:0] d, output reg [3:0] q);
always @ (posedge clk, negedge reset)begin
if (reset == ‘0’) q <= 0; // when resetelse q <= d; // when clk
endendmodule
¢ Firstresetischecked,ifresetis0,qissetto0.§ Thisisan‘asynchronous’resetastheresetdoesnotcarewhat
happenswiththeclock
¢ Ifthereisnoresetthennormalassignmentismade
Carnegie Mellon
60
DFlip-FlopwithSynchronous Resetmodule flop_sr (input clk,
input reset, input [3:0] d, output reg [3:0] q);
always @ (posedge clk)begin
if (reset == ‘0’) q <= 0; // when resetelse q <= d; // when clk
endendmodule
¢ Theprocessisonlysensitivetoclock§ Resetonlyhappenswhentheclockrises.Thisisa‘synchronous’
reset
¢ Asmallchange,hasalargeimpactontheoutcome
Carnegie Mellon
61
DFlip-FlopwithEnableandResetmodule flop_ar (input clk,
input reset,input en,input [3:0] d, output reg [3:0] q);
always @ (posedge clk, negedge reset)begin
if (reset == ‘0’) q <= 0; // when resetelse if (en) q <= d; // when en AND clk
endendmodule
¢ Aflip-flopwithenableandreset§ Notethattheensignalisnot inthesensitivitylist
¢ Onlywhen“clk isrising”AND “enis1”dataisstored
Carnegie Mellon
62
Example:DLatchmodule latch (input clk,
input [3:0] d, output reg [3:0] q);
always @ (clk, d)if (clk) q <= d; // latch is transparent when
// clock is 1endmodule
lat
q[3:0]
q[3:0][3:0]d[3:0] [3:0]
clk[3:0] D[3:0] [3:0]Q[3:0]C
Carnegie Mellon
63
Summary:SequentialStatementssofar¢ Sequentialstatementsarewithinan‘always’block
¢ Thesequentialblockistriggeredwithachangeinthesensitivitylist
¢ Signalsassignedwithinanalwaysmustbedeclaredasreg
¢ Weuse<= for(non-blocking)assignmentsanddonotuse‘assign’withinthealwaysblock.
Carnegie Mellon
64
Summary:BasicsofalwaysStatementsmodule example (input clk,
input [3:0] d, output reg [3:0] q);
wire [3:0] normal; // standard wirereg [3:0] special; // assigned in always
always @ (posedge clk)special <= d; // first FF array
assign normal = ~ special; // simple assignment
always @ (posedge clk)q <= normal; // second FF array
endmodule
¢ Youcanhavemanyalwaysblocks
Carnegie Mellon
65
Summary:BasicsofalwaysStatementsmodule example (input clk,
input [3:0] d, output reg [3:0] q);
wire [3:0] normal; // standard wirereg [3:0] special; // assigned in always
always @ (posedge clk)special <= d; // first FF array
assign normal = ~ special; // simple assignment
always @ (posedge clk)q <= normal; // second FF array
endmodule
¢ Assignmentsaredifferentwithinalwaysblocks
Carnegie Mellon
66
WhydoesanalwaysStatementMemorize?module flop (input clk,
input [3:0] d, output reg [3:0] q);
always @ (posedge clk)begin
q <= d; // when clk rises copy d to qend
endmodule
¢ Thisstatementdescribeswhathappenstosignalq
¢ …butwhathappenswhenclockisnotrising?
Carnegie Mellon
67
WhydoesanalwaysStatementMemorize?module flop (input clk,
input [3:0] d, output reg [3:0] q);
always @ (posedge clk)begin
q <= d; // when clk rises copy d to qend
endmodule
¢ Thisstatementdescribeswhathappenstosignalq
¢ …butwhathappenswhenclockisnotrising?
¢ Thevalueofq ispreserved(memorized)
Carnegie Mellon
68
WhydoesanalwaysStatementMemorize?module comb (input inv,
input [3:0] data, output reg [3:0] result);
always @ (inv, data) // trigger with inv, dataif (inv) result <= ~data;// result is inverted dataelse result <= data; // result is data
endmodule
¢ Thisstatementdescribeswhathappenstosignalresult§ Wheninv is1,resultis~data§ Whathappenswheninv isnot1 ?
Carnegie Mellon
69
WhydoesanalwaysStatementMemorize?module comb (input inv,
input [3:0] data, output reg [3:0] result);
always @ (inv, data) // trigger with inv, dataif (inv) result <= ~data;// result is inverted dataelse result <= data; // result is data
endmodule
¢ Thisstatementdescribeswhathappenstosignalresult§ Wheninv is1,resultis~data§ Wheninv isnot1,resultisdata
¢ Circuitiscombinational(nomemory)§ Theoutput(result)isdefinedforallpossibleinputs(inv data)
Carnegie Mellon
70
alwaysBlocksforCombinationalCircuits¢ Ifthestatementsdefinethesignalscompletely,nothingis
memorized,blockbecomescombinational.§ Caremustbetaken,itiseasytomakemistakesandunintentionally
describememorizingelements(latches).
¢ Alwaysblocksallowpowerfulstatements§ if .. then .. else§ case
¢ Usealwaysblocksonlyifitmakesyourjobeasier
Carnegie Mellon
71
AlwaysStatementisnotAlwaysPractical…reg [31:0] result;wire [31:0] a, b, comb;wire sel,
always @ (a, b, sel) // trigger with a, b, selif (sel) result <= a; // result is aelse result <= b; // result is b
assign comb = sel ? a : b;
endmodule
¢ Bothstatementsdescribethesamemultiplexer
¢ Inthiscase,thealwaysblockismorework
Carnegie Mellon
72
SometimesAlwaysStatementsareGreatmodule sevensegment (input [3:0] data,
output reg [6:0] segments);
always @ ( * ) // * is short for all signalscase (data) // case statement4'd0: segments = 7'b111_1110; // when data is 04'd1: segments = 7'b011_0000; // when data is 1 4'd2: segments = 7'b110_1101;4'd3: segments = 7'b111_1001;4'd4: segments = 7'b011_0011;4'd5: segments = 7'b101_1011;// etc etcdefault: segments = 7'b000_0000; // required
endcase
endmodule
Carnegie Mellon
73
ThecaseStatement¢ Likeif .. then .. else canonlybeusedinalways
blocks
¢ Theresultiscombinationalonlyiftheoutputisdefinedforallcases§ Didwementionthisbefore?
¢ Alwaysuseadefault casetomakesureyoudidnotforgetacase(whichwouldinferalatch)
¢ Usecasez statementtobeabletocheckfordon’tcares§ Seebookpage202,example4.28
Carnegie Mellon
74
Non-blockingandBlockingStatements
always @ (a)begin
a <= 2’b01;b <= a;
// all assignments are made here// b is not (yet) 2’b01end
always @ (a)begin
a = 2’b01;// a is 2’b01
b = a;// b is now 2’b01 as wellend
Non-blocking Blocking
¢ Valuesareassignedattheendoftheblock.
¢ Allassignmentsaremadeinparallel,processflowisnot-blocked.
¢ Valueisassignedimmediately.
¢ Processwaitsuntilthefirstassignmentiscomplete,itblocks progress.
Carnegie Mellon
75
Whyuse(Non)-BlockingStatements¢ Therearetechnicalreasonswhybotharerequired
§ Itisoutofthescopeofthiscoursetodiscussthese
¢ Blockingstatementsallowsequentialdescriptions§ Morelikeaprogramminglanguage
¢ Ifthesensitivitylistiscorrect,blockswithnon-blockingstatementswillalwaysevaluatetothesameresult§ Itmayrequiresomeadditionaliterations
Carnegie Mellon
76
Example:BlockingStatements
always @ ( * )beginp = a ^ b ; // p = 0 g = a & b ; // g = 0s = p ^ cin ; // s = 0 cout = g | (p & cin) ; // cout = 0
end
¢ Assumeallinputsareinitially‘0’
Carnegie Mellon
77
Example:BlockingStatements
always @ ( * )beginp = a ^ b ; // p = 1 g = a & b ; // g = 0s = p ^ cin ; // s = 1cout = g | (p & cin) ; // cout = 0
end
¢ Theprocesstriggers
¢ Allvaluesareupdatedinorder
¢ Attheend,s=1
¢ Nowa changesto‘1’
Carnegie Mellon
78
SameExample:Non-BlockingStatements
always @ ( * )beginp <= a ^ b ; // p = 0 g <= a & b ; // g = 0s <= p ^ cin ; // s = 0 cout <= g | (p & cin) ; // cout = 0
end
¢ Assumeallinputsareinitially‘0’
Carnegie Mellon
79
SameExample:Non-BlockingStatements
always @ ( * )beginp <= a ^ b ; // p = 1 g <= a & b ; // g = 0s <= p ^ cin ; // s = 0 cout <= g | (p & cin) ; // cout = 0
end
¢ Theprocesstriggers
¢ Allassignmentsareconcurrent
¢ Whens isbeingassigned,p isstill0,resultisstill0
¢ Nowa changesto‘1’
Carnegie Mellon
80
SameExample:Non-BlockingStatements
always @ ( * )beginp <= a ^ b ; // p = 1 g <= a & b ; // g = 0s <= p ^ cin ; // s = 1 cout <= g | (p & cin) ; // cout = 0
end
¢ Sincethereisachangeinp,processtriggersagain
¢ Thistimes iscalculatedwithp=1
¢ Theresultiscorrectaftertheseconditeration
¢ Afterthefirstiterationp haschangedto‘1’aswell
Carnegie Mellon
81
RulesforSignalAssignment¢ Usealways @(posedge clk) andnon-blocking
assignments(<=)tomodelsynchronoussequentiallogicalways @ (posedge clk)
q <= d; // nonblocking
¢ Usecontinuousassignments(assign …)tomodelsimplecombinationallogic.
assign y = a & b;
Carnegie Mellon
82
RulesforSignalAssignment(cont)¢ Usealways @ (*) andblockingassignments(=)to
modelmorecomplicatedcombinationallogicwherethealwaysstatementishelpful.
¢ Donotmakeassignmentstothesamesignalinmorethanonealwaysstatementorcontinuousassignmentstatement
Carnegie Mellon
83
FiniteStateMachines(FSMs)¢ EachFSMconsistsofthreeseparateparts:
§ nextstatelogic§ stateregister§ outputlogic
CLKM Nk knext
statelogic
outputlogic
inputs outputsstatenextstate
Carnegie Mellon
84
FiniteStateMachine(FSM)consistsof:¢ Stateregister:
§ Storethecurrentstateand§ Loadthenextstateattheclockedge§ Sequentialcircuit
¢ Nextstatelogic§ Determineswhatthenextstatewillbe§ Combinationalcircuit
¢ Outputlogic§ Generatestheoutputs§ CombinationalCircuit
NextState
CurrentState
S’ S
CLK
CL
Next StateLogic
NextState
CL
OutputLogic
Outputs
Carnegie Mellon
85
FSMExample1:Divideby3
TheoutputYisHIGHforoneclockcycleoutofevery3.Inotherwords,theoutputdividesthefrequencyoftheclockby3.
Carnegie Mellon
86
FSMinVerilog,Definitionsmodule divideby3FSM (input clk,
input reset, output q);
reg [1:0] state, nextstate;
parameter S0 = 2'b00;parameter S1 = 2'b01;parameter S2 = 2'b10;
¢ Wedefinestate andnextstate as2-bitreg
¢ Theparameterdescriptionsareoptional,itmakesreadingeasier
Carnegie Mellon
87
FSMinVerilog,StateRegister// state register
always @ (posedge clk, posedge reset)if (reset) state <= S0;else state <= nextstate;
¢ Thispartdefinesthestateregister(memorizingprocess)
¢ Sensitivetoonlyclk,reset
¢ Inthisexampleresetisactivewhen‘1’
NextState
CurrentState
S’ S
CLK
Carnegie Mellon
88
FSMinVerilog,NextStateCalculation// next state logicalways @ (*)
case (state)S0: nextstate = S1;S1: nextstate = S2;S2: nextstate = S0;default: nextstate = S0;
endcase
¢ Basedonthevalueofstatewedeterminethevalueofnextstate
¢ Analways .. case statementisusedforsimplicity.
CL
Next StateLogic
NextState
Carnegie Mellon
89
FSMinVerilog,OutputAssignments// output logic
assign q = (state == S0);
¢ Inthisexample,outputdependsonlyonstate§ MooretypeFSM
¢ Weusedasimplecombinationalassign
Carnegie Mellon
90
FSMinVerilog,WholeCodemodule divideby3FSM (input clk, input reset, output q);
reg [1:0] state, nextstate;
parameter S0 = 2'b00;parameter S1 = 2'b01;parameter S2 = 2'b10;
always @ (posedge clk, posedge reset) // state registerif (reset) state <= S0;else state <= nextstate;
always @ (*) // next state logiccase (state)
S0: nextstate = S1;S1: nextstate = S2;S2: nextstate = S0;default: nextstate = S0;
endcaseassign q = (state == S0); // output logic
endmodule
Carnegie Mellon
91
FSMExample2:SmilingSnail¢ AlyssaP.Hackerhasasnailthatcrawlsdownapapertape
with1’sand0’sonit.Thesnailsmileswheneverthelastfourdigitsithascrawledoverare1101.
Moore
Mealy
Carnegie Mellon
92
FSMExample2:VerilogDefinitionsmodule smilingsnail (input clk,
input reset,input a,output y);
reg [1:0] state, nextstate;
parameter S0 = 2'b00;parameter S1 = 2'b01;parameter S2 = 2'b10;parameter S3 = 2’b11;
a/y
Carnegie Mellon
93
FSMExample2:StateRegister// state register
always @ (posedge clk, posedge reset)if (reset) state <= S0;else state <= nextstate;
¢ Thispartdefinesthestateregister(memorizingprocess)
¢ Sensitivetoonlyclk,reset
¢ Inthisexampleresetisactivewhen‘1’
Carnegie Mellon
94
FSMExample2:NextStateCalculation// next state logicalways @ (*)
case (state)S0: if (a) nextstate = S1;
else nextstate = S0;S1: if (a) nextstate = S2;
else nextstate = S0;S2: if (a) nextstate = S2;
else nextstate = S3;S3: if (a) nextstate = S1;
else nextstate = S0;default: nextstate = S0;
endcase
Carnegie Mellon
95
FSMExample2:OutputAssignments// output logic
assign y = (a & state == S3);
¢ Inthisexample,outputdependsonstateandinput§ MealytypeFSM
¢ Weusedasimplecombinationalassign
Carnegie Mellon
96
FSMExample2:WholeCodemodule smilingsnail (input clk,
input reset,input a,output y);
reg [1:0] state, nextstate;
parameter S0 = 2'b00;parameter S1 = 2'b01;parameter S2 = 2'b10;parameter S3 = 2’b11;
// state registeralways @ (posedge clk, posedge reset)
if (reset) state <= S0;else state <= nextstate;
// next state logicalways @ (*)
case (state)S0: if (a) nextstate = S1;
else nextstate = S0;
S1: if (a) nextstate = S2;else nextstate = S0;
S2: if (a) nextstate = S2;else nextstate = S3;
S3: if (a) nextstate = S1;else nextstate = S0;
default: nextstate = S0;endcase
// output logicassign y = (a & state == S3);
endmodule
Carnegie Mellon
97
WhatDidWeLearn?¢ BasicsofDefiningSequentialCircuitsinVerilog
¢ Alwaysstatement§ Isneededfordefiningmemorizingelements(flip-flops,latches)§ Canalsobeusedtodefinecombinationalcircuits
¢ Blockingvs Non-blockingstatements§ =assignsthevalueimmediately§ <=assignsthevalueattheendoftheblock
¢ WritingFSMs§ Nextstatecalculation§ Determiningoutputs§ Stateassignment
Carnegie Mellon
98
WhatDidWeLearn?¢ DLatchisthebasicmemorizingelement
§ Transparentmode,copiesinputtooutput§ Latchmode,keepscontent
¢ (Rising)EdgeTriggeredFlip-Flopsaremorepractical§ Inputiscopiedtooutputwhentheclockrisesfrom0to1
¢ FiniteStateMachines§ Moore,outputdependsononly thecurrentstate§ Mealy,outputdependsoncurrentstateandtheinputs.
¢ ThreeAspectsofanFSM§ Holdsthepresentstate§ Calculatethenextstate§ Determinetheoutputs
Carnegie Mellon
99
Tomorrow…¢ TiminginCombinationalcircuits
§ PropagationandContaminationDelays
¢ TimingforSequentialcircuits§ SetupandHoldtime§ Howfastcanmycircuitwork?
¢ HowtimingismodeledinVerilog
¢ VerificationusingVerilog§ Howcanwemakesurethecircuitworkscorrectly§ DesigningTestbenches