the verilog primer - university of torontobharrington/cscb58/labs/verilogprimer.pdf · by steve...
TRANSCRIPT
TheVerilogPrimerBySteveEngels
SoyouwanttolearnVerilog
§ VerilogisanewlanguagethatisusedalotintheCSCB58labs.It’snothardtolearn,butitisdifferentfromotherlanguagesthatyou’veseenbefore.
§ ThisprimerismeanttogiveyouasenseofwhatVerilogisabout,andwhatyouneedtoknowinordertogetbyinthelabs.
§ It’salivingdocument,soifthere’sanythingthat’smissingorunclear,letusknow!
UnderstandingVerilog
§ ThefirstthingtorealizeaboutVerilogisthatitisnotaprogramminglanguage,butisahardwaredescriptionlanguage(HDL).
§ It’susedtodescribewhatthe circuitlayoutneedstolooklike, oncewestartdesigningcircuits thataretoolargeorcomplicated toimplementwithactualchips andwires.
BasicVerilogExample
§ Forinstance,thisisasimpleANDgate:
§ IfyouhadtocreateasoftwarelanguagethatwouldallowyoutospecifyanANDgatewiththeseinputsandoutputs,whatwouldthespecificationlooklike?
A B
Y
BasicVerilogExample(cont’d)
§ Itwouldhavetohavea namethatyoucoulduse todescribethegate.ú e.g.“and”
§ Itwouldhavetoallowyoutospecifytheinputsandoutputsofthegate.ú e.g.and(Y, A, B) ú Sincegatescanhavemanyinputsbutonlyoneoutput,theoutputislistedfirst,followedbyallofthegate’sinputs.
A B
Y
ThebasicsofVerilog
§ Verilogisbasedofftheideathatthedesignerofthecircuitneedsasimplewaytodescribethecomponentsofacircuitinsoftware.
§ ThereareseveralbasicprimitivegatesthatarebuiltintoVerilog.
ú two-inputgatesshownhere,butmulti-inputalsopossible.
Ø and(out,in,in) Ø or(out,in,in) Ø not(out,in)
Ø nand(out,in,in) Ø nor(out,in,in) Ø buf(out,in)
Ø xor(out,in,in) Ø xnor(out,in,in)
Creatingmodules
§ Usingbuilt-ingatesisonething,butwhatifyouwanttocreatelogicalunitsofyourown?
§ Moduleshelptospecifyacombinationofgateswithasetofoverallinputandoutputsignals.ú SpecifiedsimilarlytoCand Pythonfunctions.
ú Lesslikefunctionsthough, andmorelikespecifyinga partofacar.
ModuleExample
§ MakinganXORgate.ú AnXORgatecanbe representedwiththe followinglogicstatement:
ú Howwouldwedescribealogicequationlikethisinahardwaredesignlanguage?
A B
Y
Y = A·B + A·B
ModuleExample(cont’d)§ Nottohardtorepresentitinlogicgates.
§ HowwouldyouspecifytheANDandORgates?
A B
A B
Y
and(__,B,__) and(__,A,__) or(Y,__,__)
ModuleExample(cont’d)
§ Wiresthatareusedinternallyinthecircuittoconnectcomponentstogetheraredeclaredandlabeledusingthewirekeyword.ú Labeltheoutputofeachgate,sothatyoucanrefertoitwhenspecifyingtheinputsofothergates.
A B
A B
Y and(__,B,__) and(__,A,__) or(Y,__,__)
ModuleExample(cont’d)
§ Note:thewirenamesarenotbuiltinornamedaccordingtoanyconvention.Thenamesofthewiresisatthediscretionofthedesigner.
A B
A B
Y
not_a
not_b
b_not_a
a_not_b
ModuleExample(cont’d)§ Theresultis thecircuit description ontheright.
§ Theorderof thefivelines atthebottom doesn’tmatter.ú Remember:Verilogisahardwaredescription,notaprogramminglanguage,sotheresultisthesame.
wire not_a, not_b wire a_not_b, b_not_a and(b_not_a, B, not_a) and(a_not_b, A, not_b) or(Y, b_not_a, a_not_b) not(A, not_a) not(B, not_b)
ModuleExample(cont’d)
§ Themoduleisnearlydone!
§ Onlymissingthreethings:1. Semicolonsat
theendofeachline.
2. Statementsdescribingthecircuit’sinputandoutputs.
input A, B; output Y; wire not_a, not_b; wire a_not_b, b_not_a; and(b_not_a, B, not_a); and(a_not_b, A, not_b); or(Y, b_not_a, a_not_b); not(A, not_a); not(B, not_b);
ModuleExample(cont’d)§ Lastmissingfeature:3. Keywords
layingoutthestartandendofthemodule,aswellastheinputandoutputsignals.
module xor_gate(A, B, Y); input A, B; output Y; wire not_a, not_b; wire a_not_b, b_not_a; and(b_not_a, B, not_a); and(a_not_b, A, not_b); or(Y, b_not_a, a_not_b); not(not_A, A); not(not_B, B); endmodule
Modulereview
§ Creatingamodulefollowsafewsimplesteps:1. Declarethemodule(alongwithitsname,itsinput
andoutputsignals,andwhereitends).2. Specifywhichofthemodule’sexternalsignalsare
inputsandwhichareoutputs.3. Providelabelsfortheinternalwiresthatwillbe
neededinthecircuit.4. Specifythecomponentsofthecircuitandhow
they’reconnectedtogether.
AnoteaboutStep#4§ Therearealternatewaystoexpresstheinternallogicofamodule.ú assignstatements.
and(Y, A, B); assign Y = A & B;
or(Y, A, B); assign Y = A | B;
not(Y, A); assign Y = ~A;
Verilogoperators
§ CandPythonhaveoperators,suchas:ú +,-,<,==,etc.
§ Verilogoperatorsú “Bitwise”operations takemulti-bitinput values,andperform theoperationon thecorresponding bitsofeachvalue.
ú Moreoperatorsexist, butthisisenoughfornow.
Operator Operation
~ BitwiseNOT(1’scomplement)
& BitwiseAND
| BitwiseOR
^ BitwiseXOR
! NOT
&& AND
|| OR
== Testequality
ModuleExample,revisited
§ Thisalsoworks,butcanbeeasiertoexpress.
module xor_gate(A, B, Y); input A, B; output Y; assign Y = A & ~B | B & ~A; endmodule
Usingmodules
§ Onceamoduleiscreated,itcanbeusedasacomponentofothermodulesthatyoucreate.ú Example:halfaddercircuit.
module half_adder(X, Y, C, S); input X, Y; output C, S; and(C, X, Y); xor_gate(S, X, Y); endmodule
MakingamuxinVerilog
§ Rememberhowamuxworks:
module mux(X, Y, S, M); input X, Y, S; output M; assign M = X & ~S | Y & S; endmodule
Y M
X
S
0
1 M = X·S + Y·S
3-bitmuxinVerilog
§ Howaremultipleinputs handledbyVerilog?ú e.g.3-inputmultiplexers.
§ Usesquarebracketcharacterstoindicatearangeofvaluesforthatsignal.
Y
M X
S
n
n
n 0
1
module mux(X, Y, S, M); input [2:0] X, Y; // 3-bit input input S; // 1-bit input output [2:0] M; // 3-bit output ...
3-bitmuxinVerilog
§ Continuing3-bitmuxexample:
module mux(X, Y, S, M); input [2:0] X, Y; // 3-bit input input S; // 1-bit input output [2:0] M; // 3-bit output assign M[0] = X[0] & ~S | Y[0] & S; assign M[1] = X[1] & ~S | Y[1] & S; assign M[2] = X[2] & ~S | Y[2] & S; endmodule
Anoteaboutranges
§ Whenindicatingthatalabeledsignalrepresentsseveralinputwires,thenotationfortherangecanvary:ú e.g.input [2:0] X, Y; or
input [0:2] X, Y;
§ Botharelegal;thefirstmeansthatthefirstbitsoftheinputsarereferredtoasX[2]andY[2].ThesecondmeansthatthefirstbitsoftheinputsarereferredtoasX[0]andY[0].
Endofcombinationaldesign
§ Everythingsofarhasbeenaboutspecifyingcombinationalcircuits.ThenextsectionwilldiscusstheelementsofVerilogthatarisewhenyouincorporatesequentialcircuits.
§ Ifyou’vebeenreadingalltheseslidesinonesitting,thisisagoodtimetostandup,getsomethingtoeatordrink,andstretchwhileyouabsorbthethingsyou’vejustread.
ReflectionsonVerilog
§ Bynow,you’veseenseveralelementsoftheVeriloglanguage,butit’sgoodtoputthemintoperspectiveagain.
§ Verilogisusedtospecifycircuitdiagrams.ú Ifyouhadtodescribeacircuitdiagramintextform,theresultwouldstronglyresembleVerilogsyntax.
“IneedtwoANDgates,onewithinputsAandB,theotherwithinputsCandD,withanORgatewhoseinputsaretheoutputsofthetwoANDgatesandwith
anoutputcalledY…”
wire ab, cd; and(ab, A, B); and(cd, C, D); or(Y, ab, cd);
MorereflectionsonVerilog
§ Ifyoucandescribeacircuitdiagram,youhavetheabilitytospecifyyourcircuitinVerilog!
§ Verilogalsotriestoprovideshortersyntaxfordescribingcertaincircuits.ú Example:Simplebooleancircuits:
wire ab, cd; and(ab, A, B); and(cd, C, D); or(Y, ab, cd);
assign Y = A & B | C & D;
*Quartusmakestheseequivalentatcompiletime!
Othersimplificationsyntax§ Whataboutsequentialcircuits?
ú i.e.circuitsinvolvingflip-flops.§ Onewaytospecifythemisusinggatedesign:
// A gated D latch module d_latch (D, Clk, Q); input D, Clk; output Q; wire R, S, Qa, Qb /* synthesis keep */ ; nand (R, D, Clk); nand (S, ~D, Clk); nand (Qa, R, Qb); nand (Qb, S, Qa); assign Q = Qa; endmodule
Othersimplificationsyntax§ Anotherwayofspecifyingthislatchis:
ú “SetQtothevalueofDwheneverClkishigh.” Thisisbasedontheconceptofpolling,wherethesoftwarekeepscheckingthevaluesofDandClktoseeiftheoutputQneedstobeupdated.
Thebetterversionisbasedoninterrupts,wherethecircuitreactswhencertainsignalvalueschange…
ú “WheneverDorClkchange,dothefollowing.”
always @ (D, Clk) begin ... end
Usingalways
§ Thealwayskeywordprovidesevenmoreabstractionthanbooleanequations,butintheend,everythingistranslatedintosimplegates.
§ Otherrelated high-level keywords:ú if/else ú for ú case
Usingalways
§ Besttoshowalwaysthroughexamples.ú Example#1:AnRSlatch.
IfRandSare0and0,outputisunchanged. IfRandSare1and0,QissethighandQissetlow. IfRandSare0and1,QissetlowandQissethigh. IfRandSare1and1,QandQarebothsetlow.
Alwaysexample:SRlatch module sr_latch(R, S, Clk, Q, Q_not); input R, S, Clk; output reg Q, Q_not; always @ (R, S, Clk) if (Clk & (R | S)) begin if (R & ~S) Q_not = 1; else Q_not = 0; if (S & ~R) Q = 1; else Q = 0; end endmodule
R Q
S Q
Usingif,else&elseif
§ Theifandelsekeywordsaremostusefulwithinanalwaysblock.ú Usingthemoutsidethealwaysblockdoesn’twork.ú Theif/elsestatementsaremeanttoturnsignalsonoroffinresponsetocertainconditions.ThealwaysstatementisneededtotelltheVerilogcompilerwhentotestforthoseconditions.
§ Theif,else ifandelsestatementscanbenested,justlikeanyotherlanguage.
if/else,beginandend§ Justlikeinotherlanguages,
theifconditioncanbefollowedbyasinglestatement.
§ Ifyouwantthecircuittoperformmultiplestatementsinresponsetoacondition,usethebeginandendkeywords,likebracesinCorJava.ú Note:Ifyouforgettousebegin
andend,thecompilerwillassumethatonlythenextlinebelongsintheifstatement.
if (S & ~R) Q = 1; else Q = 0;
if (S & ~R) begin Q = 1; Q_not = 0; end
alwaysandinitial
§ Thealwayskeywordtellsthecompilertolistenforconditionsincertainsignals,andmakethecircuitrespondinthosecases.
§ Theinitialkeyworddoessomethingsimilar(makesthecircuitperformasetofoperations),butonlywhenthecircuitstarts.ú Onlyoccursonce,atbeginning.ú Usefulforinitiatingcircuitelements.
forloops
§ Theinitialkeywordandforloopsgowelltogether,asaresult.ú forloopsyntaxissimilartoCandJava:
reg [15:0] memory [255:0]; integer index; initial begin for(index = 0; index < 256; index = index + 1) begin memory [index] = 0; end end
casestatements
§ Onemoreimportantcontrolstatement!§ ThecasestatementworkssimilarlytoitsPython,
CandJavacounterparts:
§ Goodforcreatingdecoders,orreactingtoinputsthatcouldhavemanypossiblevalues.
case (<variable name>) < case1 > : < statement > < case2 > : < statement > ... default : < statement > endcase
caseexample:7-segdecoder
§ Easiertospecifydecodersliketheseven-segmentdecoderusingcasesyntax.ú Resultisthe
sameastheversionobtainedthroughK-mapsandreduction.
module SevenSegmentDisplayDecoder(ss_out, bcd_in); output reg [6:0] ss_out; input [3:0] bcd_in; always @(bcd_in) case (bcd_in) 4'h0: ss_out = 7'b0111111; 4'h1: ss_out = 7'b0000110; 4'h2: ss_out = 7'b1011011; 4'h3: ss_out = 7'b1001111; 4'h4: ss_out = 7'b1100110; 4'h5: ss_out = 7'b1101101; 4'h6: ss_out = 7'b1111101; 4'h7: ss_out = 7'b0000111; 4'h8: ss_out = 7'b1111111; 4'h9: ss_out = 7'b1100111; 4'hA: ss_out = 7'b1110111; 4'hB: ss_out = 7'b1111100; 4'hC: ss_out = 7'b0111001; 4'hD: ss_out = 7'b1011110; 4'hE: ss_out = 7'b1111001; 4'hF: ss_out = 7'b1110001; default: ss_out = 7'b1111001; endcase endmodule
Reflectiontime
§ Remember:Thiscourseisaboutcircuits,notVerilogJ§ However…designingandtestingthesecircuitsis
easierwithtoolsorspecificationlanguages.ú Designingcomplexcircuitsbywiringchipsandgates
togethercantakeforeverandbefullofbugs.ú Designinggate-by-gateinVerilogisfaster,reproducible,
andyieldsfewerbugs.ú Morepowerfulkeywordslikealways,if/elseandcase
createthesamelogicwithlesswork,bysimplyspecifyingthebehaviourthatyouwantinsteadofthespecificcircuit. LikespecifyingstringanddictionarybehaviourinPythonorC,insteadofcreatingyourownobjectsfromscratch.
Reflectiontime
§ Takeamomenttothinkaboutthis!Peopleoftengetundulydistressedabouthigher-levelVerilogstatements.
§ Reallythough,these statementsmakelife aloteasier,onceyou getthehangofusing thesekeywordstosay whatthecircuit’s behaviourshouldbe.
Storingandassigningdata
§ Flip-flopsandsequentialcircuitsallowustodesigncircuitsthatcanstorevalues.ú Someareimplicit,inlatch-stylefeedbackcircuits.ú Otherscanbemadeexplicit,usingregvalues.
§ We’veusedregbefore, intheSRlatchexample.
Storingandassigningdata
§ Labelscanbegiventobothwireandregvalues.ú Maindifference:regvaluescandriveoutput;wire valuescan’t.
module wire_example( a, b, y); input a, b; output y; wire a, b, y; assign y = a & b; endmodule
A B
Y
module reg_example( a, b, y); input a, b; output y; reg y; wire a, b; always @ ( a or b) begin y = a & b; end endmodule
Regversuswire
§ “Drivingoutput”?Whatdoesthatmean?ú RememberthatVerilogisusedtospecifyacircuitlayout.Thewirekeywordspecifieswhereanactualwirewouldbe,andconnectingtwopointswithawire(orwire)justmakesthemlogicallyequivalent.
ú Areg(shortforregister)canactuallystoreavalueanddriveanoutputsignal.Anyalwaysorinitialblocksthatneedtosetavaluemustdosobysettingregvalues. Similarly,wirescan’tbereassignedtoconnectnewpointstogetherpartwaythroughacircuit’soperation.
Literalvalues
§ Sometimesyouneedtoassignasetofwireorregvaluesatthesametime.ú Example:theseven-segmentdisplay.ú Possibletoassigneachsegmentoneatatime,buteasiertoassignthemallatonce.
§ LiteralvaluesinPythonandCarevalueslike42,3.14and“Hello”.
§ Veriloghasliteralvaluesaswell.ú Butexactlywhatdoes101representinVerilog?
Literalvalues
§ 101canrepresentdifferentvalues,dependingonwhattypeofnumberitis.ú Decimal:101=onehundredandone(base10).ú Binary:101base2=5base10ú Hexadecimal:101base16=257base10ú (Octal:101base8=65base10)
§ InVerilog:ú Binary: ‘b101 ú Decimal: ‘d101 ú Hexadecimal: ‘h101
Example:seven-segdecoder
§ Theinstructionsinthe seven-segdecoder codetranslatetothe following:ú “inthecasewherethe four-bitBCDinputhasahexadecimalvalueof0…”
ú “…setthevaluess_outtoa7-digitbinaryvalueof0111111.”
References
§ VerilogLanguageReferenceGuide:ú http://verilog.renerta.com/
§ VerilogPage:ú http://www.asic-world.com/verilog/
§ VerilogTutorial:ú http://www.fullchipdesign.com/verilog_tutorial.htm