Professional Documents
Culture Documents
VHDLPrimer
VHDLTutorial
JanVanderSpiegel
UniversityofPennsylvania
DepartmentofElectricalandSystemsEngineering
VHDLTutorial
1.Introduction
2.Levelsofrepresentationandabstraction
3.BasicStructureofaVHDLfile
Behavioralmodel
Concurrency
Structuraldescription
4.LexicalElementsofVHDL
5.DataObjects:Signals,VariablesandConstants
Constant
Variable
Signal
6.Datatypes
Integertypes
Floatingpointtypes
Physicaltypes
ArrayType
RecordType
Signalattributes
Scalarattributes
Arrayattributes
7.Operators
8.BehavioralModeling:SequentialStatements
BasicLoopstatement
WhileLoopstatement
ForLoopstatement
9.DataflowModelingConcurrentStatements
10.StructuralModeling
11.References
Appendix:IEEEStandardPackageSTD_LOGIC_1164
________________________________________________________________________
http://www.seas.upenn.edu/~ese171/vhdl/vhdl_primer.html#_Toc526061341
1/50
6/3/2016
VHDLPrimer
ThistutorialgivesabriefoverviewoftheVHDLlanguageandismainlyintendedasacompanionfortheDigital
DesignLaboratory.ThiswritingaimstogivethereaderaquickintroductiontoVHDLandtogiveacompleteor
indepthdiscussionofVHDL.Foramoredetailedtreatment,pleaseconsultanyofthemanygoodbooksonthis
topic.Severalofthesebooksarelistedinthereferencelist.
1.Introduction
VHDLstandsforVHSIC(VeryHighSpeedIntegratedCircuits)HardwareDescriptionLanguage.Inthemid
1980stheU.S.DepartmentofDefenseandtheIEEEsponsoredthedevelopmentofthishardwaredescription
languagewiththegoaltodevelopveryhighspeedintegratedcircuit.Ithasbecomenowoneofindustrys
standardlanguagesusedtodescribedigitalsystems.Theotherwidelyusedhardwaredescriptionlanguageis
Verilog.Botharepowerfullanguagesthatallowyoutodescribeandsimulatecomplexdigitalsystems.Athird
HDLlanguageisABEL(AdvancedBooleanEquationLanguage)whichwasspecificallydesignedfor
ProgrammableLogicDevices(PLD).ABELislesspowerfulthantheothertwolanguagesandislesspopularin
industry.ThistutorialdealswithVHDL,asdescribedbytheIEEEstandard10761993.
Althoughtheselanguageslooksimilarasconventionalprogramminglanguages,therearesomeimportant
differences.Ahardwaredescriptionlanguageisinherentlyparallel,i.e.commands,whichcorrespondtologic
gates,areexecuted(computed)inparallel,assoonasanewinputarrives.AHDLprogrammimicsthebehavior
ofaphysical,usuallydigital,system.Italsoallowsincorporationoftimingspecifications(gatedelays)aswellas
todescribeasystemasaninterconnectionofdifferentcomponents.
2.Levelsofrepresentationandabstraction
Adigitalsystemcanberepresentedatdifferentlevelsofabstraction[1].Thiskeepsthedescriptionanddesignof
complexsystemsmanageable.Figure1showsdifferentlevelsofabstraction.
Figure1:Levelsofabstraction:Behavioral,StructuralandPhysical
Thehighestlevelofabstractionisthebehaviorallevelthatdescribesasystemintermsofwhatitdoes(orhowit
http://www.seas.upenn.edu/~ese171/vhdl/vhdl_primer.html#_Toc526061341
2/50
6/3/2016
VHDLPrimer
behaves)ratherthanintermsofitscomponentsandinterconnectionbetweenthem.Abehavioraldescription
specifiestherelationshipbetweentheinputandoutputsignals.ThiscouldbeaBooleanexpressionoramore
abstractdescriptionsuchastheRegisterTransferorAlgorithmiclevel.Asanexample,letusconsiderasimple
circuitthatwarnscarpassengerswhenthedoorisopenortheseatbeltisnotusedwheneverthecarkeyis
insertedintheignitionlockAtthebehaviorallevelthiscouldbeexpressedas,
Warning=Ignition_onAND(Door_openORSeatbelt_off)
Thestructurallevel,ontheotherhand,describesasystemasacollectionofgatesandcomponentsthatare
interconnectedtoperformadesiredfunction.Astructuraldescriptioncouldbecomparedtoaschematicof
interconnectedlogicgates.Itisarepresentationthatisusuallyclosertothephysicalrealizationofasystem.For
theexampleabove,thestructuralrepresentationisshowninFigure2below.
Figure2:Structuralrepresentationofabuzzercircuit.
VHDLallowsonetodescribeadigitalsystematthestructuralorthebehaviorallevel.Thebehaviorallevelcan
befurtherdividedintotwokindsofstyles:DataflowandAlgorithmic.Thedataflowrepresentationdescribes
howdatamovesthroughthesystem.Thisistypicallydoneintermsofdataflowbetweenregisters(Register
Transferlevel).Thedataflowmodelmakesuseofconcurrentstatementsthatareexecutedinparallelassoonas
dataarrivesattheinput.Ontheotherhand,sequentialstatementsareexecutedinthesequencethattheyare
specified.VHDLallowsbothconcurrentandsequentialsignalassignmentsthatwilldeterminethemannerin
whichtheyareexecuted.Examplesofbothrepresentationswillbegivenlater.
3.BasicStructureofaVHDLfile
AdigitalsysteminVHDLconsistsofadesignentitythatcancontainotherentitiesthatarethenconsidered
componentsofthetoplevelentity.Eachentityismodeledbyanentitydeclarationandanarchitecturebody.
Onecanconsidertheentitydeclarationastheinterfacetotheoutsideworldthatdefinestheinputandoutput
signals,whilethearchitecturebodycontainsthedescriptionoftheentityandiscomposedofinterconnected
entities,processesandcomponents,alloperatingconcurrently,asschematicallyshowninFigure3below.Ina
typicaldesigntherewillbemanysuchentitiesconnectedtogethertoperformthedesiredfunction.
http://www.seas.upenn.edu/~ese171/vhdl/vhdl_primer.html#_Toc526061341
3/50
6/3/2016
VHDLPrimer
Figure3:AVHDLentityconsistingofaninterface(entitydeclaration)andabody(architecturaldescription).
VHDLusesreservedkeywordsthatcannotbeusedassignalnamesoridentifiers.Keywordsanduserdefined
identifiersarecaseinsensitive.Lineswithcommentsstartwithtwoadjacenthyphens()andwillbeignored
bythecompiler.VHDLalsoignoreslinebreaksandextraspaces.VHDLisastronglytypedlanguagewhich
impliesthatonehasalwaystodeclarethetypeofeveryobjectthatcanhaveavalue,suchassignals,constants
andvariables.
a.EntityDeclaration
TheentitydeclarationdefinestheNAMEoftheentityandliststheinputandoutputports.Thegeneralform
isasfollows,
entityNAME_OF_ENTITYis[genericgeneric_declarations)]
port(signal_names:modetype
signal_names:modetype
:
signal_names:modetype)
end[NAME_OF_ENTITY]
Anentityalwaysstartswiththekeywordentity,followedbyitsnameandthekeywordis.Nextarethe
portdeclarationsusingthekeywordport.Anentitydeclarationalwaysendswiththekeywordend,optionally
[]followedbythenameoftheentity.
TheNAME_OF_ENTITYisauserselectedidentifier
signal_namesconsistsofacommaseparatedlistofoneormoreuserselectedidentifiersthatspecify
externalinterfacesignals.
mode:isoneofthereservedwordstoindicatethesignaldirection:
oinindicatesthatthesignalisaninput
ooutindicatesthatthesignalisanoutputoftheentitywhosevaluecanonlybereadbyother
entitiesthatuseit.
obufferindicatesthatthesignalisanoutputoftheentitywhosevaluecanbereadinsidethe
entitysarchitecture
oinoutthesignalcanbeaninputoranoutput.
type:abuiltinoruserdefinedsignaltype.Examplesoftypesarebit,bit_vector,Boolean,character,
std_logic,andstd_ulogic.
http://www.seas.upenn.edu/~ese171/vhdl/vhdl_primer.html#_Toc526061341
4/50
6/3/2016
VHDLPrimer
obitcanhavethevalue0and1
obit_vectorisavectorofbitvalues(e.g.bit_vector(0to7)
ostd_logic,std_ulogic,std_logic_vector,std_ulogic_vector:canhave9valuestoindicate
thevalueandstrengthofasignal.Std_ulogicandstd_logicarepreferredoverthebitor
bit_vectortypes.
obooleancanhavethevalueTRUEandFALSE
ointegercanhavearangeofintegervalues
orealcanhavearangeofrealvalues
ocharacteranyprintingcharacter
otimetoindicatetime
generic:genericdeclarationsareoptionalanddeterminethelocalconstantsusedfortimingand
sizing(e.g.buswidths)theentity.Agenericcanhaveadefaultvalue.Thesyntaxforageneric
follows,
generic(
constant_name:type[:=value]
constant_name:type[:=value]
:
constant_name:type[:=value])
FortheexampleofFigure2above,theentitydeclarationlooksasfollows.
comments:exampleofthebuzzercircuitoffig.2
entityBUZZERis
port(DOOR,IGNITION,SBELT:instd_logic
WARNING:outstd_logic)
endBUZZER
TheentityiscalledBUZZERandhasthreeinputports,DOOR,IGNITIONandSBELTandoneoutputport,
WARNING.Noticetheuseandplacementofsemicolons!ThenameBUZZERisanidentifier.Inputsare
denotedbythekeywordin,andoutputsbythekeywordout.SinceVHDLisastronglytypedlanguage,each
porthasadefinedtype.Inthiscase,wespecifiedthestd_logictype.Thisisthepreferredtypeofdigital
signals.Incontrasttothebittypethatcanonlyhavethevalues1and0,thestd_logicandstd_ulogictypes
canhaveninevalues.Thisisimportanttodescribeadigitalsystemaccuratelyincludingthebinaryvalues0and1,
aswellastheunknownvalueX,theuninitializedvalueU,fordontcare,Zforhighimpedance,andseveral
symbolstoindicatethesignalstrength(e.g.Lforweak0,Hforweak1,Wforweakunknownseesectionon
EnumeratedTypes).Thestd_logictypeisdefinedinthestd_logic_1164packageoftheIEEElibrary.Thetype
definesthesetofvaluesanobjectcanhave.Thishastheadvantagethatithelpswiththecreationofmodelsand
helpsreduceerrors.Forinstance,ifonetriestoassignanillegalvaluetoanobject,thecompilerwillflagthe
error.
Afewotherexamplesofentitydeclarationsfollow
http://www.seas.upenn.edu/~ese171/vhdl/vhdl_primer.html#_Toc526061341
5/50
6/3/2016
VHDLPrimer
Fourtoonemultiplexerofwhicheachinputisan8bitword.
entitymux4_to_1is
port(I0,I1,I2,I3:instd_logic_vector(7downto0)
SEL:instd_logic_vector(1downto0)
OUT1:outstd_logic
_vector(7downto0))
endmux4_to_1
AnexampleoftheentitydeclarationofaDflipflopwithsetandresetinputsis
entitydff_sris
port(D,CLK,S,R:instd_logic
Q,Qnot:outstd_logic
)
enddff_sr
b.Architecturebody
Thearchitecturebodyspecifieshowthecircuitoperatesandhowitisimplemented.Asdiscussedearlier,an
entityorcircuitcanbespecifiedinavarietyofways,suchasbehavioral,structural(interconnectedcomponents),
oracombinationoftheabove.
Thearchitecturebodylooksasfollows,
architecturearchitecture_nameofNAME_OF_ENTITYis
Declarations
componentsdeclarations
signaldeclarations
constantdeclarations
functiondeclarations
proceduredeclarations
typedeclarations
begin
Statements
endarchitecture_name
Behavioralmodel
ThearchitecturebodyfortheexampleofFigure2,describedatthebehaviorallevel,isgivenbelow,
architecturebehavioralofBUZZERis
begin
WARNING<=(notDOORandIGNITION)or(notSBELTandIGNITION)
http://www.seas.upenn.edu/~ese171/vhdl/vhdl_primer.html#_Toc526061341
6/50
6/3/2016
VHDLPrimer
endbehavioral
Theheaderlineofthearchitecturebodydefinesthearchitecturename,e.g.behavioral,andassociatesit
withtheentity,BUZZER.Thearchitecturenamecanbeanylegalidentifier.Themainbodyofthearchitecture
startswiththekeywordbeginandgivestheBooleanexpressionofthefunction.Wewillseelaterthata
behavioralmodelcanbedescribedinseveralotherways.The<=symbolrepresentsanassignmentoperator
andassignsthevalueoftheexpressionontherighttothesignalontheleft.Thearchitecturebodyendswithan
endkeywordfollowedbythearchitecturename.
Afewotherexamplesfollow.ThebehavioraldescriptionofatwoinputANDgateisshownbelow.
entityAND2is
port(in1,in2:instd_logic
out1:outstd_logic)
endAND2
architecturebehavioral_2ofAND2is
begin
out1<=in1andin2
endbehavioral_2
AnexampleofatwoinputXNORgateisshownbelow.
entityXNOR2is
port(A,B:instd_logic
Z:outstd_logic)
endXNOR2
architecturebehavioral_xnorofXNOR2is
signaldeclaration(ofinternalsignalsX,Y)
signalX,Y:std_logic
begin
X<=AandB
Y<=(notA)and(notB)
Z<=XorY
Endbehavioral_xnor
Thestatementsinthebodyofthearchitecturemakeuseoflogicoperators.Logicoperatorsthatareallowedare:
and,or,nand,nor,xor,xnorandnot.Inaddition,othertypesofoperatorsincluding
relational,shift,arithmeticareallowedaswell(seesectiononOperators).Formoreinformationonbehavioral
modelingseesectiononBehavioralModeling.
Concurrency
Itisworthpointingoutthatthesignalassignmentsintheaboveexamplesareconcurrentstatements.Thisimplies
thatthestatementsareexecutedwhenoneormoreofthesignalsontherighthandsidechangetheirvalue(i.e.an
eventoccursononeofthesignals).Forinstance,whentheinputAchanges,theinternalsignalsXandYchange
http://www.seas.upenn.edu/~ese171/vhdl/vhdl_primer.html#_Toc526061341
7/50
6/3/2016
VHDLPrimer
valuesthatinturncausesthelaststatementtoupdatetheoutputZ.Theremaybeapropagationdelayassociated
withthischange.Digitalsystemsarebasicallydatadrivenandaneventwhichoccursononesignalwillleadto
aneventonanothersignal,etc.Theexecutionofthestatementsisdeterminedbytheflowofsignalvalues.Asa
result,theorderinwhichthesestatementsaregivendoesnotmatter(i.e.,movingthestatementfortheoutputZ
aheadofthatforXandYdoesnotchangetheoutcome).Thisisincontrasttoconventional,softwareprograms
thatexecutethestatementsinasequentialorproceduralmanner.
Structuraldescription
ThecircuitofFigure2canalsobedescribedusingastructuralmodelthatspecifieswhatgatesareusedandhow
theyareinterconnected.Thefollowingexampleillustratesit.
architecturestructuralofBUZZERis
Declarations
componentAND2
port(in1,in2:instd_logic
out1:outstd_logic)
endcomponent
componentOR2
port(in1,in2:instd_logic
out1:outstd_logic)
endcomponent
componentNOT1
port(in1:instd_logic
out1:outstd_logic)
endcomponent
declarationofsignalsusedtointerconnectgates
signalDOOR_NOT,SBELT_NOT,B1,B2:std_logic
begin
Componentinstantiationsstatements
U0:NOT1portmap(DOOR,DOOR_NOT)
U1:NOT1portmap(SBELT,SBELT_NOT)
U2:AND2portmap(IGNITION,DOOR_NOT,B1)
U3:AND2portmap(IGNITION,SBELT_NOT,B2)
U4:OR2portmap(B1,B2,WARNING)
endstructural
Followingtheheaderisthedeclarativepartthatgivesthecomponents(gates)thataregoingtobeusedinthe
descriptionofthecircuits.Inourexample,weuseatwoinputANDgate,twoinputORgateandaninverter.
Thesegateshavetobedefinedfirst,i.e.theywillneedanentitydeclarationandarchitecturebody(asshownin
thepreviousexample).Thesecanbestoredinoneofthepackagesonereferstointheheaderofthefile(see
LibraryandPackagesbelow).Thedeclarationsforthecomponentsgivetheinputs(e.g.in1,in2)andtheoutput
(e.g.out1).Next,onehastodefineinternalnets(signalnames).Inourexamplethesesignalsarecalled
DOOR_NOT,SBELT_NOT,B1,B2(seeFigure2).Noticethatonealwayshastodeclarethetypeofthe
signal.
http://www.seas.upenn.edu/~ese171/vhdl/vhdl_primer.html#_Toc526061341
8/50
6/3/2016
VHDLPrimer
Thestatementsafterthebeginkeywordgivestheinstantiationsofthecomponentsanddescribeshowtheseare
interconnected.Acomponentinstantiationstatementcreatesanewlevelofhierarchy.Eachlinestartswithan
instancename(e.g.U0)followedbyacolonandacomponentnameandthekeywordportmap.This
keyworddefineshowthecomponentsareconnected.Intheexampleabove,thisisdonethroughpositional
association:DOORcorrespondstotheinput,in1oftheNOT1gateandDOOR_NOTtotheoutput.Similarly,
fortheAND2gatewherethefirsttwosignals(IGNITIONandDOOR_NOT)correspondtotheinputsin1and
in2,respectively,andthesignalB1totheoutputout1.Analternativewayistouseexplicitassociationbetween
theports,asshownbelow.
label:componentnameportmap(port1=>signal1,port2=>signal2,port3=>signaln)
U0:NOT1portmap(in1=>DOOR,out1=>DOOR_NOT)
U1:NOT1portmap(in1=>SBELT,out1=>SBELT_NOT)
U2:AND2portmap(in1=>IGNITION,in2=>DOOR_NOT,out1=>B1)
U3:AND2portmap(in1=>IGNITION,in2=>SBELT_NOT,B2)
U4:OR2portmap(in1=>B1,in2=>B2,out1=>WARNING)
Noticethattheorderinwhichthesestatementsarewrittenhasnobearingontheexecutionsincethese
statementsareconcurrentandthereforeexecutedinparallel.Indeed,theschematicthatisdescribedbythese
statementsisthesameindependentoftheorderofthestatements.
Structuralmodelingofdesignlendsitselftohierarchicaldesign,inwhichonecandefinecomponentsofunitsthat
areusedoverandoveragain.Oncethesecomponentsaredefinedtheycanbeusedasblocks,cellsormacrosin
ahigherlevelentity.Thiscansignificantlyreducethecomplexityoflargedesigns.Hierarchicaldesignapproaches
arealwayspreferredoverflatdesigns.Wewillillustratetheuseofahierarchicaldesignapproachfora4bit
adder,showninFigure4below.EachfulladdercanbedescribedbytheBooleanexpressionsforthesumand
carryoutsignals,
sum=(AB)C
carry=AB+C(AB)
Figure4:Schematicofa4bitadderconsistingoffulladdermodules.
IntheVHDLfile,wehavedefinedacomponentforthefulladderfirst.Weusedseveralinstantiationsofthefull
addertobuildthestructureofthe4bitadder.Wehaveincludedthelibraryanduseclauseaswellastheentity
declarations.
http://www.seas.upenn.edu/~ese171/vhdl/vhdl_primer.html#_Toc526061341
9/50
6/3/2016
VHDLPrimer
FourBitAdderIllustratingahierarchicalVHDLmodel
Exampleofafourbitadder
libraryieee
useieee.std_logic_1164.all
definitionofafulladder
entityFULLADDERis
port(a,b,c:instd_logic
sum,carry:outstd_logic)
endFULLADDER
architecturefulladder_behavofFULLADDERis
begin
sum<=(axorb)xorc
carry<=(aandb)or(cand(axorb))
endfulladder_behav
4bitadder
libraryieee
useieee.std_logic_1164.all
entityFOURBITADDis
port(a,b:instd_logic_vector(3downto0)
Cin:instd_logic
sum:outstd_logic_vector(3downto0)
Cout,V:outstd_logic)
endFOURBITADD
architecturefouradder_structureofFOURBITADDis
signalc:std_logic_vector(4downto0)
componentFULLADDER
port(a,b,c:instd_logic
sum,carry:outstd_logic)
endcomponent
begin
FA0:FULLADDER
portmap(a(0),b(0),Cin,sum(0),c(1))
FA1:FULLADDER
portmap(a(1),b(1),C(1),sum(1),c(2))
FA2:FULLADDER
portmap(a(2),b(2),C(2),sum(2),c(3))
FA3:FULLADDER
portmap(a(3),b(3),C(3),sum(3),c(4))
V<=c(3)xorc(4)
Cout<=c(4)
endfouradder_structure
Noticethatthesameinputnamesaandbfortheportsofthefulladderandthe4bitadderwereused.Thisdoes
notposeaprobleminVHDLsincetheyrefertodifferentlevels.However,forreadability,itmaybeeasiertouse
differentnames.Weneededtodefinetheinternalsignalsc(4:0)toindicatethenetsthatconnecttheoutputcarry
http://www.seas.upenn.edu/~ese171/vhdl/vhdl_primer.html#_Toc526061341
10/50
6/3/2016
VHDLPrimer
totheinputcarryofthenextfulladder.ForthefirstinputweusedtheinputsignalCin.Forthelastcarrywe
definedc(4)asaninternalsignalsincethelastcarryisneededastheinputtothexorgate.Wecouldnotusethe
outputsignalCoutsinceVHDLdoesnotallowtheuseofoutputsasinternalsignals!Forthisreasonwehadto
definetheinternalcarryc(4)andassignc(4)totheoutputcarrysignalCout.
SeealsothesectiononStructuralModeling.
c.LibraryandPackages:libraryandusekeywords
Alibrarycanbeconsideredasaplacewherethecompilerstoresinformationaboutadesignproject.AVHDL
packageisafileormodulethatcontainsdeclarationsofcommonlyusedobjects,datatype,component
declarations,signal,proceduresandfunctionsthatcanbesharedamongdifferentVHDLmodels.
Wementionedearlierthatstd_logicisdefinedinthepackageieee.std_logic_1164intheieeelibrary.Inorderto
usethestd_logiconeneedstospecifythelibraryandpackage.ThisisdoneatthebeginningoftheVHDLfile
usingthelibraryandtheusekeywordsasfollows:
libraryieee
useieee.std_logic_1164.all
The.allextensionindicatestousealloftheieee.std_logic_1164package.
TheXilinxFoundationExpresscomeswithseveralpackages.
ieeeLibrary:
std_logic_1164package:definesthestandarddatatypes
std_logic_arithpackage:providesarithmetic,conversionandcomparisonfunctionsforthesigned,
unsigned,integer,std_ulogic,std_logicandstd_logic_vectortypes
std_logic_unsigned
std_logic_miscpackage:definessupplementaltypes,subtypes,constantsandfunctionsforthe
std_logic_1164package.
Touseanyoftheseonemustincludethelibraryanduseclause:
libraryieee
useieee.std_logic_1164.all
useieee.std_logic_arith.all
useieee.std_logic_unsigned.all
Inaddition,thesynopsislibraryhastheattributespackage:
librarySYNOPSYS
useSYNOPSYS.attributes.all
Onecanaddotherlibrariesandpackages.Thesyntaxtodeclareapackageisasfollows:
http://www.seas.upenn.edu/~ese171/vhdl/vhdl_primer.html#_Toc526061341
11/50
6/3/2016
VHDLPrimer
Packagedeclaration
packagename_of_packageis
packagedeclarations
endpackagename_of_package
Packagebodydeclarations
packagebodyname_of_packageis
packagebodydeclarations
endpackagebodyname_of_package
Forinstance,thebasicfunctionsoftheAND2,OR2,NAND2,NOR2,XOR2,etc.componentsneedtobe
definedbeforeonecanusethem.Thiscanbedoneinapackage,e.g.basic_funcforeachofthesecomponents,
asfollows:
Packagedeclaration
libraryieee
useieee.std_logic_1164.all
packagebasic_funcis
AND2declaration
componentAND2
generic(DELAY:time:=5ns)
port(in1,in2:instd_logicout1:outstd_logic)
endcomponent
OR2declaration
componentOR2
generic(DELAY:time:=5ns)
port(in1,in2:instd_logicout1:outstd_logic)
endcomponent
endpackagebasic_func
Packagebodydeclarations
libraryieee
useieee.std_logic_1164.all
packagebodybasic_funcis
2inputANDgate
entityAND2is
generic(DELAY:time)
port(in1,in2:instd_logicout1:outstd_logic)
endAND2
architecturemodel_concofAND2is
begin
out1<=in1andin2afterDELAY
endmodel_conc
2inputORgate
entityOR2is
generic(DELAY:time)
port(in1,in2:instd_logicout1:outstd_logic)
endOR2
architecturemodel_conc2ofAND2is
begin
out1<=in1orin2afterDELAY
http://www.seas.upenn.edu/~ese171/vhdl/vhdl_primer.html#_Toc526061341
12/50
6/3/2016
VHDLPrimer
endmodel_conc2
endpackagebodybasic_func
Noticethatweincludedadelayof5ns.However,itshouldbenoticedthatdelayspecificationsareignoredby
theFoundationsynthesistool.Wemadeuseofthepredefinedtypestd_logicthatisdeclaredinthepackage
std_logic_1164.Wehaveincludedthelibraryanduseclauseforthispackage.Thispackageneedstobe
compiledandplacedinalibrary.Letscallthislibrarymy_func.Tousethecomponentsofthispackageonehas
todeclareitusingthelibraryanduseclause:
libraryieee,my_func
useieee.std_logic_1164.all,my_func.basic_func.all
Onecanconcatenateaseriesofnamesseparatedbyperiodstoselectapackage.Thelibraryandusestatements
areconnectedtothesubsequententitystatement.Thelibraryandusestatementshavetoberepeatedfor
eachentitydeclaration.
Onehastoincludethelibraryanduseclauseforeachentityasshownfortheexampleofthefourbitadder
above.
4.LexicalElementsofVHDL
a.Identifiers
IdentifiersareuserdefinedwordsusedtonameobjectsinVHDLmodels.Wehaveseenexamplesof
identifiersforinputandoutputsignalsaswellasthenameofadesignentityandarchitecturebody.When
choosinganidentifieroneneedstofollowthesebasicrules:
Maycontainonlyalphanumericcharacters(AtoZ,atoz,09)andtheunderscore(_)character
Thefirstcharactermustbealetterandthelastonecannotbeanunderscore.
Anidentifiercannotincludetwoconsecutiveunderscores.
Anidentifieriscaseinsensitive(ex.And2andAND2orand2refertothesameobject)
Anidentifiercanbeofanylength.
Examplesofvalididentifiersare:X10,x_10,My_gate1.
Someinvalididentifiersare:_X10,my_gate@input,gateinput.
Theaboveidentifiersarecalledbasicidentifiers.Therulesforthesebasicidentifiersareoftentoorestrictiveto
indicatesignals.Forexample,ifonewantstoindicateanactivelowsignalsuchasanactivelowRESET,one
cannotcallit/RESET.Inordertoovercometheselimitations,thereareasetofextendedidentifierruleswhich
allowidentifierswithanysequenceofcharacters.
Anextendedidentifierisenclosedbythebackslash,\,character.
Anextendedidentifieriscasesensitive.
Anextendedidentifierisdifferentfromreservedwords(keywords)oranybasicidentifier(e.g.the
identifier\identity\isallowed)
http://www.seas.upenn.edu/~ese171/vhdl/vhdl_primer.html#_Toc526061341
13/50
6/3/2016
VHDLPrimer
Insidethetwobackslashesonecanuseanycharacterinanyorder,exceptthatabackslashaspartofan
extendedidentifiermustbeindicatedbyanadditionalbackslash.Asanexample,tousetheidentifier
BUS:\data,onewrites:\BUS:\data\
ExtendedidentifiersareallowedintheVHDL93versionbutnotinVHDL87
Someexamplesoflegalidentifiersare:
Input,\Input\,\input#1\,\Rst\\as\
b.Keywords(Reservedwords)
Certainidentifiersareusedbythesystemaskeywordsforspecialusesuchasspecificconstructs.These
keywordscannotbeusedasidentifiersforsignalsorobjectswedefine.Wehaveseenseveralofthesereserved
wordsalreadysuchasin,out,or,and,port,map,end,etc.Keywordsareoftenprintedinboldface,asisdone
inthistutorial.Foralistofallthekeywordsclickoncompletekeywordlist.Extendedidentifierscanmakeuse
ofkeywordssincetheseareconsidereddifferentwords(e.g.theextendedidentifier\end\isallowed.
c.Numbers
Thedefaultnumberrepresentationisthedecimalsystem.VHDLallowsintegerliteralsandrealliterals.Integer
literalsconsistofwholenumberswithoutadecimalpoint,whilerealliteralsalwaysincludeadecimalpoint.
ExponentialnotationisallowedusingtheletterEore.Forintegerliteralstheexponentmustalwaysbe
positive.Examplesare:
Integerliterals:1210256E312e+6
Realliterals:1.2256.243.14E2
Thenumber12isacombinationofanegationoperatorandanintegerliteral.
Toexpressanumberinabasedifferentfromthebase10,oneusesthefollowingconvention:base#number#.A
fewexamplesfollow.
Base2:2#10010#(representingthedecimalnumber18)
Base16:16#12#
Base8:8#22#
Base2:2#11101#(representingthedecimalnumber29)
Base16:16#1D#
Base8:8#35#
Tomakethereadabilityoflargenumberseasier,onecaninsertunderscoresinthenumbersaslongasthe
underscoreisnotusedatthebeginningortheend.
2#1001_1101_1100_0010#
215_123
http://www.seas.upenn.edu/~ese171/vhdl/vhdl_primer.html#_Toc526061341
14/50
6/3/2016
VHDLPrimer
d.Characters,StringsandBitStrings
TouseacharacterliteralinaVHDLcode,oneputsitinasinglequotationmark,asshownintheexamples
below:
a,B,,
Ontheotherhand,astringofcharactersareplacedindoublequotationmarksasshowninthefollowing
examples:
Thisisastring,
Touseadoublequotationmarkinsideastring,usetwodoublequotationmarks
ThisisaString.
Anyprintingcharactercanbeincludedinsideastring.
Abitstringrepresentsasequenceofbitvalues.Inordertoindicatethatthisisabitstring,oneplacestheBin
frontofthestring:B1001.OnecanalsousestringsinthehexagonaloroctalbasebyusingtheXorO
specifiers,respectively.Someexamplesare:
Binary:B1100_1001,b1001011
Hexagonal:XC9,X4b
Octal:O311,o113
Noticethatinthehexadecimalsystem,eachdigitrepresentsexactly4bits.Asaresult,thenumberb1001011
isnotthesameasX4bsincetheformerhasonly7bitswhilethelatterrepresentsasequence8bits.Forthe
samereason,O113(represents9bits)isnotthesamesequenceasX4b(represents8bits).
5.DataObjects:Signals,VariablesandConstants
Adataobjectiscreatedbyanobjectdeclarationandhasavalueandtypeassociatedwithit.Anobjectcan
beaConstant,Variable,SignaloraFile.Uptonowwehaveseensignalsthatwereusedasinputoroutput
portsorinternalnets.Signalscanbeconsideredwiresinaschematicthatcanhaveacurrentvalueandfuture
values,andthatareafunctionofthesignalassignmentstatements.Ontheotherhand,VariablesandConstants
areusedtomodelthebehaviorofacircuitandareusedinprocesses,proceduresandfunctions,similarlyasthey
wouldbeinaprogramminglanguage.Followingisabriefdiscussionofeachclassofobjects.
Constant
Aconstantcanhaveasinglevalueofagiventypeandcannotbechangedduringthesimulation.Aconstantis
declaredasfollows,
constantlist_of_name_of_constant:type[:=initialvalue]
wheretheinitialvalueisoptional.Constantscanbedeclaredatthestartofanarchitectureandcanthenbeused
http://www.seas.upenn.edu/~ese171/vhdl/vhdl_primer.html#_Toc526061341
15/50
6/3/2016
VHDLPrimer
anywherewithinthearchitecture.Constantsdeclaredwithinaprocesscanonlybeusedinsidethatspecific
process.
constantRISE_FALL_TME:time:=2ns
constantDELAY1:time:=4ns
constantRISE_TIME,FALL_TIME:time:=1ns
constantDATA_BUS:integer:=16
Variable
Avariablecanhaveasinglevalue,aswithaconstant,butavariablecanbeupdatedusingavariableassignment
statement.Thevariableisupdatedwithoutanydelayassoonasthestatementisexecuted.Variablesmustbe
declaredinsideaprocess(andarelocaltotheprocess).Thevariabledeclarationisasfollows:
variablelist_of_variable_names:type[:=initialvalue]
Afewexamplesfollow:
variableCNTR_BIT:bit:=0
variableVAR1:boolean:=FALSE
variableSUM:integerrange0to256:=16
variableSTS_BIT:bit_vector(7downto0)
ThevariableSUM,intheexampleabove,isanintegerthathasarangefrom0to256withinitialvalueof16at
thestartofthesimulation.Thefourthexampledefinesabitvectoror8elements:STS_BIT(7),STS_BIT(6),
STS_BIT(0).
Avariablecanbeupdatedusingavariableassignmentstatementsuchas
Variable_name:=expression
Assoonastheexpressionisexecuted,thevariableisupdatedwithoutanydelay.
Signal
Signalsaredeclaredoutsidetheprocessusingthefollowingstatement:
signallist_of_signal_names:type[:=initialvalue]
signalSUM,CARRY:std_logic
signalCLOCK:bit
signalTRIGGER:integer:=0
signalDATA_BUS:bit_vector(0to7)
signalVALUE:integerrange0to100
Signalsareupdatedwhentheirsignalassignmentstatementisexecuted,afteracertaindelay,asillustrated
below,
SUM<=(AxorB)after2ns
http://www.seas.upenn.edu/~ese171/vhdl/vhdl_primer.html#_Toc526061341
16/50
6/3/2016
VHDLPrimer
Ifnodelayisspecified,thesignalwillbeupdatedafteradeltadelay.Onecanalsospecifymultiplewaveforms
usingmultipleeventsasillustratedbelow,
signalwavefrm:std_logic
wavefrm<=0,1after5ns,0after10ns,1after20ns
Itisimportanttounderstandthedifferencebetweenvariablesandsignals,particularlyhowitrelatestowhentheir
valuechanges.Avariablechangesinstantaneouslywhenthevariableassignmentisexecuted.Ontheotherhand,
asignalchangesadelayaftertheassignmentexpressionisevaluated.Ifnodelayisspecified,thesignalwill
changeafteradeltadelay.Thishasimportantconsequencesfortheupdatedvaluesofvariablesandsignals.Lets
comparethetwofilesinwhichaprocessisusedtocalculatethesignalRESULT[7].
ExampleofaprocessusingVariables
architectureVARofEXAMPLEis
signalTRIGGER,RESULT:integer:=0
begin
process
variablevariable1:integer:=1
variablevariable2:integer:=2
variablevariable3:integer:=3
begin
waitonTRIGGER
variable1:=variable2
variable2:=variable1+variable3
variable3:=variable2
RESULT<=variable1+variable2+variable3
endprocess
endVAR
ExampleofaprocessusingSignals
architectureSIGNofEXAMPLEis
signalTRIGGER,RESULT:integer:=0
signalsignal1:integer:=1
signalsignal2:integer:=2
signalsignal3:integer:=3
begin
process
begin
waitonTRIGGER
signal1<=signal2
signal2<=signal1+signal3
signal3<=signal2
RESULT<=signal1+signal2+signal3
endprocess
endSIGN
http://www.seas.upenn.edu/~ese171/vhdl/vhdl_primer.html#_Toc526061341
17/50
6/3/2016
VHDLPrimer
Inthefirstcase,thevariablesvariable1,variable2andvariable3arecomputedsequentiallyandtheirvalues
updatedinstantaneouslyaftertheTRIGGERsignalarrives.Next,theRESULT,whichisasignal,iscomputed
usingthenewvaluesofthevariablesandupdatedatimedeltaafterTRIGGERarrives.Thisresultsinthe
followingvalues(afteratimeTRIGGER):variable1=2,variable2=5(=2+3),variable3=5.SinceRESULTisa
signalitwillbecomputedatthetimeTRIGGERandupdatedatthetimeTRIGGER+Delta.Itsvaluewillbe
RESULT=12.
Ontheotherhand,inthesecondexample,thesignalswillbecomputedatthetimeTRIGGER.Allofthese
signalsarecomputedatthesametime,usingtheoldvaluesofsignal1,2and3.Allthesignalswillbeupdatedat
DeltatimeaftertheTRIGGERhasarrived.Thusthesignalswillhavethesevalues:signal1=2,signal2=4
(=1+3),signal3=2andRESULT=6.
6.Datatypes
Eachdataobjecthasatypeassociatedwithit.Thetypedefinesthesetofvaluesthattheobjectcanhaveandthe
setofoperationsthatareallowedonit.ThenotionoftypeiskeytoVHDLsinceitisastronglytypedlanguage
thatrequireseachobjecttobeofacertaintype.Ingeneraloneisnotallowedtoassignavalueofonetypetoan
objectofanotherdatatype(e.g.assigninganintegertoabittypeisnotallowed).Therearefourclassesofdata
types:scalar,composite,accessandfiletypes.Thescalartypesrepresentasinglevalueandareorderedsothat
relationaloperationscanbeperformedonthem.Thescalartypeincludesinteger,real,andenumeratedtypesof
BooleanandCharacter.Examplesofthesewillbegivenfurtheron.
a.DataTypesdefinedintheStandardPackage
VHDLhasseveralpredefinedtypesinthestandardpackageasshowninthetablebelow.Tousethispackage
onehastoincludethefollowingclause:
librarystd,work
usestd.standard.all
Type
TypesdefinedinthePackageStandardofthestdLibrary
Rangeofvalues
Example
bit
bit_ve ctor
boole an
characte r
0,1
anarraywitheachelementoftype
bit
FALSE,TRUE
anylegalVHDLcharacter(see
packagestandard)printable
charactersmustbeplacedbetween
singlequotes(e.g.#)
read_mode,write_mode,
append_mode
open_ok,status_error,name_error,
mode_error
http://www.seas.upenn.edu/~ese171/vhdl/vhdl_primer.html#_Toc526061341
signalA:bit:=1
signalINBUS:bit_vector(7downto
0)
variableTEST:Boolean:=FALSE
variableVAL:character:=$
18/50
6/3/2016
inte ge r
VHDLPrimer
rangeisimplementationdependent
constantCONST1:integer:=129
butincludesatleast(2311)to+
natural
positive
re al*
(2311)
integerstartingwith0uptothe
maxspecifiedintheimplementation
integerstartingfrom1upthemax
specifiedintheimplementation
floatingpointnumberintherange
of1.0x1038to+1.0x1038(can
beimplementationdependent.Not
supportedbytheFoundation
synthesisprogram.
note,warning,error,failure
se ve rity_le ve l
arrayofwhicheachelementisof
string
thetypecharacter
anintegernumberofwhichthe
time *
rangeisimplementationdefined
unitscanbeexpressedinsec,ms,
us,ns,ps,fs,minandhr..Not
supportedbytheFoundation
synthesisprogram
*NotsupportedbytheFoundationsynthesisprogram
variableVAR1:natural:=2
variableVAR2:positive:=2
variableVAR3:real:=+64.2E12
variableVAR4:string(1to12):=
@$#ABC*()_%Z
variableDELAY:time:=5ns
b.UserdefinedTypes
Onecanintroducenewtypesbyusingthetypedeclaration,whichnamesthetypeandspecifiesitsvaluerange.
Thesyntaxis
typeidentifieristype_definition
Hereareafewexamplesoftypedefinitions,
Integertypes
typesmall_intisrange0to1024
typemy_word_lengthisrange31downto0
subtypedata_wordismy_word_lengthrange7downto0
Asubtypeisasubsetofapreviouslydefinedtype.Thelastexampleaboveillustratestheuseofsubtypes.It
definesatypecalleddata_wordthatisasybtypeofmy_word_lengthofwhichtherangeisrestrictedfrom7to0.
Anotherexampleofasubtypeis,
subtypeint_smallisintegerrange1024to+1024
Floatingpointtypes
typecmos_levelisrange0.0to3.3
http://www.seas.upenn.edu/~ese171/vhdl/vhdl_primer.html#_Toc526061341
19/50
6/3/2016
VHDLPrimer
typepmos_levelisrange5.0to0.0
typeprobabilityisrange0.0to1.0
subtypecmos_low_Viscmos_levelrange0.0to+1.8
NotethatfloatingpointdatatypesarenotsupportedbytheXilinxFoundationsynthesisprogram.
Physicaltypes
Thephysicaltypedefinitionincludesaunitsidentifierasfollows,
typeconductanceisrange0to2E9
units
mho
mmho=1E3mho
umho=1E6mho
nmho=1E9mho
pmho=1E12mho
endunitsconductance
Herearesomeobjectdeclarationsthatusetheabovetypes,
variableBUS_WIDTH:small_int:=24
signalDATA_BUS:my_word_length
variableVAR1:cmos_levelrange0.0to2.5
constantLINE_COND:conductance:=125umho
Noticethataspacemustbeleftbeforetheunitname.
ThephysicaldatatypesarenotsupportedbytheXilinxFoundationExpresssynthesisprogram.
Inordertouseourowntypes,weneedeithertoincludethetypedefinitioninsideanarchitecturebodyorto
declarethetypeinapackage.Thelattercanbedoneasfollowsforapackagecalledmy_types.
packagemy_typesis
typesmall_intisrange0to1024
typemy_word_lengthisrange31downto0
subtypedata_wordismy_word_lengthisrange7downto0
typecmos_levelisrange0.0to3.3
typeconductanceisrange0to2E9
units
mho
mmho=1E3mho
umho=1E6mho
nmho=1E9mho
pmho=1E12mho
endunitsconductance
endpackagemy_types
http://www.seas.upenn.edu/~ese171/vhdl/vhdl_primer.html#_Toc526061341
20/50
6/3/2016
VHDLPrimer
c.EnumeratedTypes
Anenumeratedtypeconsistsoflistsofcharacterliteralsoridentifiers.Theenumeratedtypecanbeveryhandy
whenwritingmodelsatanabstractlevel.Thesyntaxforanenumeratedtypeis,
typetype_nameis(identifierlistorcharacterliteral)
Herearesomeexamples,
typemy_3valuesis(0,1,Z)
typePC_OPERis(load,store,add,sub,div,mult,shiftl,shiftr)
typehex_digitis(0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F)
typestate_typeis(S0,S1,S2,S3)
Examplesofobjectsthatusetheabovetypes:
signalSIG1:my_3values
variableALU_OP:pc_oper
variablefirst_digit:hex_digit:=0
signalSTATE:state_type:=S2
Ifonedoesnotinitializethesignal,thedefaultinitializationistheleftmostelementofthelist.
Enumeratedtypeshavetobedefinedinthearchitecturebodyorinsideapackageasshowninthesectionabove.
Anexampleofanenumeratedtypethathasbeendefinedinthestd_logic_1164packageisthestd_ulogictype,
definedasfollows
typeSTD_ULOGICis(
U,uninitialized
X,forcingunknown
0,forcing0
1,forcing1
Z,highimpedance
W,weakunknown
L,weak0
H.weak1
)dontcare
Inordertousethistypeonehastoincludetheclausebeforeeachentitydeclaration.
libraryieeeuseieee.std_logic_1164.all
Itispossiblethatmultipledriversaredrivingasignal.Inthatcasetherecouldbeaconflictandtheoutputsignal
wouldbeundetermined.Forinstance,theoutputsofanANDgateandNOTgateareconnectedtogetherinto
http://www.seas.upenn.edu/~ese171/vhdl/vhdl_primer.html#_Toc526061341
21/50
6/3/2016
VHDLPrimer
theoutputnetOUT1.Inordertoresolvethevalueoftheoutput,onecancalluparesolutionfunction.These
areusuallyauserwrittenfunctionthatwillresolvethesignal.Ifthesignalisofthetypestd_ulogicandhas
multipledrivers,oneneedstousearesolutionfunction.Thestd_logic_1164packagehassucharesolution
function,calledRESOLVEDpredefined.OnecanthenusethefollowingdeclarationforsignalOUT1
signalOUT1:resolved:std_ulogic
Ifthereiscontention,theRESOLVEDfunctionwillbeusedtointermediatetheconflictanddeterminethevalue
ofthesignal.Alternatively,onecandeclarethesignaldirectlyasastd_logictypesincethesubtypestd_logichas
beendefinedinthestd_logic_1164package.
signalOUT1:std_logic
d.CompositeTypes:ArrayandRecord
Compositedataobjectsconsistofacollectionofrelateddataelementsintheformofanarrayorrecord.Before
wecanusesuchobjectsonehastodeclarethecompositetypefirst.
ArrayType
Anarraytypeisdeclaredasfollows:
typearray_nameisarray(indexingscheme)ofelement_type
typeMY_WORDisarray(15downto0)ofstd_logic
typeYOUR_WORDisarray(0to15)ofstd_logic
typeVARisarray(0to7)ofinteger
typeSTD_LOGIC_1Disarray(std_ulogic)ofstd_logic
Inthefirsttwoexamplesabovewehavedefinedaonedimensionalarrayofelementsofthetypestd_logic
indexedfrom15downto0,and0upto15,respectively.Thelastexampledefinesaonedimensionalarrayof
thetypestd_logicelementsthatusesthetypestd_ulogictodefinetheindexconstraint.Thusthisarraylooksas
follows:
Index:UX01ZWLH
Element:
Wecannowdeclareobjectsofthesedatatypes.Someexamplesaregiven
signalMEM_ADDR:MY_WORD
signalDATA_WORD:YOUR_WORD:=B1101100101010110
constantSETTING:VAR:=(2,4,6,8,10,12,14,16)
Inthefirstexample,thesignalMEM_ADDRisanarrayof16bits,initializedtoall0s.Toaccessindividual
elementsofanarraywespecifytheindex.Forexample,MEM_ACCR(15)accessestheleftmostbitofthe
http://www.seas.upenn.edu/~ese171/vhdl/vhdl_primer.html#_Toc526061341
22/50
6/3/2016
VHDLPrimer
array,whileDATA_WORD(15)accessestherightmostbitofthearraywithvalue0.Toaccessasubrange,
onespecifiestheindexrange,MEM_ADDR(15downto8)orDATA_WORD(0to7).
Multidimensionalarrayscanbedeclaredaswellbyusingasimilarsyntaxasabove,
typeMY_MATRIX3X2isarray(1to3,1to2)ofnatural
typeYOUR_MATRIX4X2isarray(1to4,1to2)ofinteger
typeSTD_LOGIC_2Disarray(std_ulogic,std_ulogic)ofstd_logic
variableDATA_ARR:MY_MATRIX:=((0,2),(1,3),(4,6),(5,7))
ThevariablearrayDATA_ARRwillthenbeinitializedto,
02
13
46
57
Toaccessanelementonespecifiestheindex,e.g.DATA_ARR(3,1)returnsthevalue4.
Thelastexampledefinesa9x9arrayortablewithanindextheelementsofthestd_ulogictype.
Sometimesitismoreconvenientnottospecifythedimensionofthearraywhenthearraytypeisdeclared.Thisis
calledanunconstrainedarraytype.Thesyntaxforthearraydeclarationis,
typearray_nameisarray(typerange<>)ofelement_type
Someexamplesare
typeMATRIXisarray(integerrange<>)ofinteger
typeVECTOR_INTisarray(naturalrange<>)ofinteger
typeVECTOR2isarray(naturalrange<>,naturalrange<>)ofstd_logic
Therangeisnowspecifiedwhenonedeclaresthearrayobject,
variableMATRIX8:MATRIX(2downto8):=(3,5,1,4,7,9,12,14,20,18)
variableARRAY3x2:VECTOR2(1to4,1to3)):=((1,0),(0,),(1,Z))
RecordType
Asecondcompositetypeistherecordstype.Arecordconsistsofmultipleelementsthatmaybeofdifferent
types.Thesyntaxforarecordtypeisthefollowing:
typenameis
record
identifier:subtype_indication
:
identifier:subtype_indication
http://www.seas.upenn.edu/~ese171/vhdl/vhdl_primer.html#_Toc526061341
23/50
6/3/2016
VHDLPrimer
endrecord
Asanexample,
typeMY_MODULEis
record
RISE_TIME:time
FALL_TIME:time
SIZE:integerrange0to200
DATA:bit_vector(15downto0)
endrecord
signalA,B:MY_MODULE
Toaccessvaluesorassignvaluestorecords,onecanuseoneofthefollowingmethods:
A.RISE_TIME<=5ns
A.SIZE<=120
B<=A
e.TypeConversions
SinceVHDLisastronglytypedlanguageonecannotassignavalueofonedatatypetoasignalofadifferent
datatype.Ingeneral,itispreferredtothesamedatatypesforthesignalsinadesign,suchasstd_logic(instead
ofamixofstd_logicandbittypes).Sometimesonecannotavoidusingdifferenttypes.Toallowassigningdata
betweenobjectsofdifferenttypes,oneneedstoconvertonetypetotheother.Fortunatelytherearefunctions
availableinseveralpackagesintheieeelibrary,suchasthestd_logic_1164andthestd_logic_arithpackages.As
anexample,thestd_logic_1164packageallowsthefollowingconversions:
Conversionssupportedbystd_logic_1164package
Conversion
Function
std_ulogictobit
to_bit(expression)
std_logic_vectortobit_vector
to_bitvector(expression)
std_ulogic_vectortobit_vector
to_bitvector(expression)
bittostd_ulogic
To_StdULogic(expression)
bit_vectortostd_logic_vector
To_StdLogicVector(expression)
bit_vectortostd_ulogic_vector
To_StdUlogicVector(expression)
std_ulogictostd_logic_vector
To_StdLogicVector(expression)
std_logictostd_ulogic_vector
To_StdUlogicVector(expression)
TheIEEEstd_logic_unsignedandtheIEEEstd_logic_arithpackagesallowadditionalconversionssuchasfrom
anintegertostd_logic_vectorandviceversa.
http://www.seas.upenn.edu/~ese171/vhdl/vhdl_primer.html#_Toc526061341
24/50
6/3/2016
VHDLPrimer
Anexamplefollows.
entityQUAD_NAND2is
port(A,B:inbit_vector(3downto0)
out4:outstd_logic_vector(3downto0))
endQUAD_NAND2
architecturebehavioral_2ofQUAD_NAND2is
begin
out4<=to_StdLogicVector(AandB)
endbehavioral_2
TheexpressionAandBwhichisofthetypebit_vectorhastobeconvertedtothetypestd_logic_vectorto
beofthesametypeastheoutputsignalout4.
Thesyntaxofatypeconversionisasfollows:
type_name(expression)
Inorderfortheconversiontobelegal,theexpressionmustreturnatypethatcanbeconvertedintothetype
type_name.Herearetheconditionsthatmustbefulfilledfortheconversiontobepossible.
Typeconversionsbetweenintegertypesorbetweensimilararraytypesarepossible
Conversionbetweenarraytypesispossibleiftheyhavethesamelengthandiftheyhaveidentical
elementtypesorconvertibleelementtypes.
Enumeratedtypescannotbeconverted.
f.Attributes
VHDLsupports5typesofattributes.Predefinedattributesarealwaysappliedtoaprefixsuchasasignalname,
variablenameoratype.Attributesareusedtoreturnvarioustypesofinformationaboutasignal,variableor
type.Attributesconsistofaquotemark()followedbythenameoftheattribute.
Signalattributes
Thefollowingtablegivesseveralsignalattributes.
Attribute
Function
signal_nameevent
returnstheBooleanvalueTrueifaneventonthesignal
occurred,otherwisegivesaFalse
signal_nameactive
returnstheBooleanvalueTruetherehasbeena
transaction(assignment)onthesignal,otherwisegivesa
False
signal_nametransaction
returnsasignalofthetypebitthattoggles(0to1or1
http://www.seas.upenn.edu/~ese171/vhdl/vhdl_primer.html#_Toc526061341
25/50
6/3/2016
signal_namelast_event
signal_namelast_active
signal_namelast_value
signal_namedelayed(T)
signal_namestable(T)
signal_namequiet(T)
VHDLPrimer
to0)everytimethereisatransactiononthesignal.
returnsthetimeintervalsincethelasteventonthesignal
returnsthetimeintervalsincethelasttransactiononthe
signal
givesthevalueofthesignalbeforethelasteventoccurred
onthesignal
givesasignalthatisthedelayedversion(bytimeT)ofthe
originalone.[Tisoptional,defaultT=0]
returnsaBooleanvalue,True,ifnoeventhasoccurredon
thesignalduringtheintervalT,otherwisereturnsaFalse.
[Tisoptional,defaultT=0]
returnsaBooleanvalue,True,ifnotransactionhas
occurredonthesignalduringtheintervalT,otherwise
returnsaFalse.[Tisoptional,defaultT=0]
Anexampleofanattributeis
if(CLOCKeventandCLOCK=1)then
Thisexpressionchecksforthearrivalofapositiveclockedge.Tofindouthowmuchtimehaspassedsincethe
lastclockedge,onecanusethefollowingattribute:
CLOCKlast_event
Scalarattributes
Severalattributesofascalartype,scalartype,aresupported.Thefollowingtableshowssomeofthese
attributes.
Attribute
Value
scalar_typeleft
returnsthefirstorleftmostvalueofscalartypein
itsdefinedrange
scalar_typeright
returnsthelastorrightmostvalueofscalartype
initsdefinedrange
scalar_typelow
returnsthelowestvalueofscalartypeinits
definedrange
scalar_typehigh
returnsthegreatestvalueofscalartypeinits
definedrange
scalar_typeascending
TrueifTisanascendingrange,otherwiseFalse
scalar_typevalue(s)
returnsthevalueinTthatisrepresentedbys(s
standsforstringvalue).
Hereareafewexamples.
typeconductanceisrange1E6to1E3
http://www.seas.upenn.edu/~ese171/vhdl/vhdl_primer.html#_Toc526061341
26/50
6/3/2016
VHDLPrimer
unitsmho
endunitsconductance
typemy_indexisrange3to15
typemy_levelsis(low,high,dontcare,highZ)
conductancerightreturns:1E3
conductancehigh1E3
conductancelow1E6
my_indexleft3
my_indexvalue(5)5
my_levelsleftlow
my_levelslowlow
my_levelshighhighZ
my_levelsvalue(dontcare)dontcare
Arrayattributes
Byusingarrayattributesonecanreturnanindexvaluecorrespondingtothearrayrange.
Thefollowingattributesaresupported.
Attribute
Returns
MATRIXleft(N)
leftmostelementindex
MATRIXright(N)
rightmostindex
MATRIXhigh(N)
upperbound
MATRIXlow(N)
lowerbound
MATRIXlength(N)
thenumberofelements
MATRIXrange(N)
range
MATRIXreverse_range(N)
reverserange
MATRIXascending(N)
aBooleanvalueTRUEifindexisanascending
range,otherwiseFALSE
ThenumberNbetweenparenthesesreferstothedimension.Foraonedimensionalarray,onecanomitthe
numberNasshownintheexamplesbelow.Letsassumethefollowingarrays,declaredasfollows:
typeMYARR8x4isarray(8downto1,0to3)ofboolean
typeMYARR1isarray(2to4)ofinteger
MYARR1leftreturns:2
MYARR1right4
MYARR1high4
MYARR1reverse_range4downtoto2
MYARR8x4left(1)8
MYARR8x4left(2)0
http://www.seas.upenn.edu/~ese171/vhdl/vhdl_primer.html#_Toc526061341
27/50
6/3/2016
VHDLPrimer
MYARR8x4right(2)3
MYARR8x4high(1)8
MYARR8x4low(1)1
MYARR8x4ascending(1)False
7.Operators
VHDLsupportsdifferentclassesofoperatorsthatoperateonsignals,variablesandconstants.Thedifferent
classesofoperatorsaresummarizedbelow.
Class
1.Logicaloperators
2.Relational
operators
3.Shiftoperators
4.Additionoperators
5.Unaryoperators
6.Multiplyingop.
7.Miscellaneousop.
and
=
or
/=
nand
<
nor
<=
xor
>
xnor
>=
sll
+
+
*
**
srl
=
/
abs
sla
&
sra
rol
ror
mod
not
rem
Theorderofprecedenceisthehighestfortheoperatorsofclass7,followedbyclass6withthelowest
precedenceforclass1.Unlessparenthesesareused,theoperatorswiththehighestprecedenceareappliedfirst.
Operatorsofthesameclasshavethesameprecedenceandareappliedfromlefttorightinanexpression.Asan
example,considerthefollowingstd_ulogic_vectors,X(=010),Y(=10),andZ(10101).Theexpression
notX&YxorZrol1
isequivalentto((notX)&Y)xor(Zrol1)=((101)&10)xor(01011)=(10110)xor(01011)=11101.
Thexorisexecutedonabitperbitbasis.
a.Logicoperators
Thelogicoperators(and,or,nand,nor,xorandxnor)aredefinedforthebit,boolean,std_logicand
std_ulogictypesandtheirvectors.TheyareusedtodefineBooleanlogicexpressionortoperformbitperbit
operationsonarraysofbits.Theygivearesultofthesametypeastheoperand(BitorBoolean).These
operatorscanbeappliedtosignals,variablesandconstants.
Noticethatthenandandnoroperatorsarenotassociative.Oneshoulduseparenthesesinasequenceofnandor
noroperatorstopreventasyntaxerror:
XnandYnandZwillgiveasyntaxerrorandshouldbewrittenas(XnandY)nandZ.
b.Relationaloperators
http://www.seas.upenn.edu/~ese171/vhdl/vhdl_primer.html#_Toc526061341
28/50
6/3/2016
VHDLPrimer
TherelationaloperatorstesttherelativevaluesoftwoscalartypesandgiveasresultaBooleanoutputof
TRUEorFALSE.
Operator
Description
OperandTypes
ResultType
=
Equality
anytype
Boolean
/=
Inequality
anytype
Boolean
<
Smallerthan
scalarordiscretearray
Boolean
types
<=
Smallerthanorequal
scalarordiscretearray
Boolean
types
>
Greaterthan
scalarordiscretearray
Boolean
types
>=
Greaterthanorequal
scalarordiscretearray
Boolean
types
Noticethatsymboloftheoperator<=(smallerorequalto)isthesameoneastheassignmentoperatorusedto
assignavaluetoasignalorvariable.Inthefollowingexamplesthefirst<=symbolistheassignmentoperator.
Someexamplesofrelationaloperationsare:
variableSTS:Boolean
constantA:integer:=24
constantB_COUNT:integer:=32
constantC:integer:=14
STS<=(A<B_COUNT)willassignthevalueTRUEtoSTS
STS<=((A>=B_COUNT)or(A>C))willresultinTRUE
STS<=(std_logic(1,0,1)<std_logic(0,1,1))makesSTSFALSE
typenew_std_logicis(0,1,Z,)
variableA1:new_std_logic:=1
variableA2:new_std_logic:=Z
STS<=(A1<A2)willresultinTRUEsince1occurstotheleftofZ.
Fordiscretearraytypes,thecomparisonisdoneonanelementperelementbasis,startingfromthelefttowards
theright,asillustratedbythelasttwoexamples.
c.Shiftoperators
Theseoperatorsperformabitwiseshiftorrotateoperationonaonedimensionalarrayofelementsofthetype
bit(orstd_logic)orBoolean.
Operator
Description
OperandType
ResultType
sll
Shiftleftlogical(fillright
vacatedbitswiththe0)
Left:Anyonedimensional
arraytypewithelementsof
typebitorBooleanRight:
integer
http://www.seas.upenn.edu/~ese171/vhdl/vhdl_primer.html#_Toc526061341
Sameaslefttype
29/50
6/3/2016
srl
sla
sra
rol
ror
VHDLPrimer
Shiftrightlogical(fillleft
vacatedbitswith0)
Shiftleftarithmetic(fillright
vacatedbitswithrightmostbit)
Shiftrightarithmetic(fillleft
vacatedbitswithleftmostbit)
Rotateleft(circular)
Rotateright(circular)
sameasabove
Sameaslefttype
sameasabove
Sameaslefttype
sameasabove
Sameaslefttype
sameasabove
sameasabove
Sameaslefttype
Sameaslefttype
Theoperandisontheleftoftheoperatorandthenumber(integer)ofshiftsisontherightsideoftheoperator.
Asanexample,
variableNUM1:bit_vector:=10010110
NUM1srl2
willresultinthenumber00100101.
Whenanegativeintegerisgiven,theoppositeactionoccurs,i.e.ashifttotheleftwillbeashifttotheright.Asan
example
NUM1srl2wouldbeequivalenttoNUM1sll2andgivetheresult01011000.
Otherexamplesofshiftoperationsareforthebit_vectorA=101001
variableA:bit_vector:=101001
Asll2resultsin100100
Asrl2resultsin001010
Asla2resultsin100111
Asra2resultsin111010
Arol2resultsin100110
Aror2resultsin011010
d.Additionoperators
Theadditionoperatorsareusedtoperformarithmeticoperation(additionandsubtraction)onoperandsofany
numerictype.Theconcatenation(&)operatorisusedtoconcatenatetwovectorstogethertomakealongerone.
Inordertousetheseoperatorsonehastospecifytheieee.std_logic_unsigned.allorstd_logic_arithpackage
packageinadditiontotheieee.std_logic_1164package.
Operator
Description
LeftOperandType RightOperandType ResultType
+
&
Addition
Subtraction
Concatenation
Numerictype
Numerictype
Arrayorelement
type
http://www.seas.upenn.edu/~ese171/vhdl/vhdl_primer.html#_Toc526061341
Sameasleftoperand
Sameasleftoperand
Sameasleftoperand
Sametype
Sametype
Samearraytype
30/50
6/3/2016
VHDLPrimer
Anexampleofconcatenationisthegroupingofsignalsintoasinglebus[4].
signalMYBUS:std_logic_vector(15downto0)
signalSTATUS:std_logic_vector(2downto0)
signalRW,CS1,CS2:std_logic
signalMDATA:std_logic_vector(0to9)
MYBUS<=STATUS&RW&CS1&SC2&MDATA
Otherexamplesare
MYARRAY(15downto0)<=1111_1111&MDATA(2to9)
NEWWORD<=VHDL&93
Thefirstexampleresultsinfillingupthefirst8leftmostbitsofMYARRAYwith1sandtherestwiththe8
rightmostbitsofMDATA.ThelastexampleresultsinanarrayofcharactersVHDL93.
e.Unaryoperators
Theunaryoperators+andareusedtospecifythesignofanumerictype.
Operator
Description
OperandType
+
Identity
Anynumerictype
Negation
Anynumerictype
f.Multiplyingoperators
ResultType
Sametype
Sametype
Themultiplyingoperatorsareusedtoperformmathematicalfunctionsonnumerictypes(integerorfloatingpoint).
Operator
Description
LeftOperand
Type
RightOperand
Type
ResultType
Multiplication
Anyintegeror
floatingpoint
Anyphysicaltype
Anyintegerorreal
type
Anyintegeror
floatingpoint
Anyphysicaltype
Sametype
Sametype
Integerorrealtype
Anyphysicaltype
Sameasleft
Sameasright
Anyintegeror
floatingpoint
Anyintegerorrealt
ype
Sametype
Sametype
mod
rem
Division
Modulus
Remainder
Anyphysicaltype
Anyintegertype
Anyintegertype
Sameasleft
Integer
Sametype
Sametype
Themultiplicationoperatorisalsodefinedwhenoneoftheoperandsisaphysicaltypeandtheotheranintegeror
realtype.
http://www.seas.upenn.edu/~ese171/vhdl/vhdl_primer.html#_Toc526061341
31/50
6/3/2016
VHDLPrimer
Theremainder(rem)andmodulus(mod)aredefinedasfollows:
Are mB=A(A/B)*B(inwhichA/Binaninteger)
AmodB=AB*N(inwhichNisaninteger)
Theresultofthere moperatorhasthesignofitsfirstoperandwhiletheresultofthemodoperatorshasthesignof
thesecondoperand.
Someexamplesoftheseoperatorsaregivenbelow.
11re m4resultsin3
(11)re m4resultsin3
9mod4resultsin1
7mod(4)resultsin1(74*2=1).
g.Miscellaneousoperators
Thesearetheabsolutevalueandexponentationoperatorsthatcanbeappliedtonumerictypes.Thelogical
negation(not)resultsintheinversepolaritybutthesametype.
Ope rator
De scription
**
Exponentiation
abs
not
Absolutevalue
Logicalnegation
Le ftOpe rand
RightOpe rand
Type
Type
Integertype
Integertype
Floatingpoint
Integertype
Anynumerictype
AnybitorBooleantype
Re sultType
Sameasleft
Sameasleft
Sametype
Sametype
Delaysortiminginformation
Packages(liststandard,1164packages).
8.BehavioralModeling:SequentialStatements
Asdiscussedearlier,VHDLprovidesmeanstorepresentdigitalcircuitsatdifferentlevelsofrepresentationof
abstraction,suchasthebehavioralandstructuralmodeling.Inthissectionwewilldiscussdifferentconstructsfor
describingthebehaviorofcomponentsandcircuitsintermsofsequentialstatements.Thebasisforsequential
modelingistheprocessconstruct.Asyouwillsee,theprocessconstructallowsustomodelcomplexdigital
systems,inparticularsequentialcircuits.
a.Process
Aprocessstatementisthemainconstructinbehavioralmodelingthatallowsyoutousesequentialstatementsto
describethebehaviorofasystemovertime.Thesyntaxforaprocessstatementis
[process_label:]process[(sensitivity_list)][is]
[process_declarations]
begin
http://www.seas.upenn.edu/~ese171/vhdl/vhdl_primer.html#_Toc526061341
32/50
6/3/2016
VHDLPrimer
listofsequentialstatementssuchas:
signalassignments
variableassignments
casestatement
exitstatement
ifstatement
loopstatement
nextstatement
nullstatement
procedurecall
waitstatement
endprocess[process_label]
AnexampleofapositiveedgetriggeredDflipflopwithasynchronousclearinputfollows.
libraryieee
useieee.std_logic_1164.all
entityDFF_CLEARis
port(CLK,CLEAR,D:instd_logic
Q:outstd_logic)
endDFF_CLEAR
architectureBEHAV_DFFofDFF_CLEARis
begin
DFF_PROCESS:process(CLK,CLEAR)
begin
if(CLEAR=1)then
Q<=0
elsif(CLKeventandCLK=1)then
Q<=D
endif
endprocess
endBEHAV_DFF
Aprocessisdeclaredwithinanarchitectureandisaconcurrentstatement.However,thestatementsinsidea
processareexecutedsequentially.Likeotherconcurrentstatements,aprocessreadsandwritessignalsand
valuesoftheinterface(inputandoutput)portstocommunicatewiththerestofthearchitecture.Onecanthus
makeassignmentstosignalsthataredefinedexternally(e.g.interfaceports)totheprocess,suchastheQoutput
oftheflipflopintheaboveexample.TheexpressionCLKeventandCLK=1checksforapositive
clockedge(clockeventANDclockhigh).
Thesensitivitylistisasetofsignalstowhichtheprocessissensitive.Anychangeinthevalueofthesignalsinthe
sensitivitylistwillcauseimmediateexecutionoftheprocess.Ifthesensitivitylistisnotspecified,onehasto
includeawaitstatementtomakesurethattheprocesswillhalt.Noticethatonecannotincludebothasensitivity
listandawaitstatement.Variablesandconstantsthatareusedinsideaprocesshavetobedefinedinthe
process_declarationspartbeforethekeywordbegin.Thekeywordbeginsignalsthestartofthecomputational
partoftheprocess.Thestatementsaresequentiallyexecuted,similarlyasaconventionalsoftwareprogram.It
http://www.seas.upenn.edu/~ese171/vhdl/vhdl_primer.html#_Toc526061341
33/50
6/3/2016
VHDLPrimer
shouldbenotedthatvariableassignmentsinsideaprocessareexecutedimmediatelyanddenotedbythe:=
operator.Thisisincontrasttosignalassignmentsdenotedby<=andwhichchangesoccurafteradelay.Asa
result,changesmadetovariableswillbeavailableimmediatelytoallsubsequentstatementswithinthesame
process.Foranexamplethatillustratesthedifferencebetweensignalandvariableassignmentsseethesectionon
DataTypes(differencebetweensignalsandvariables).
ThepreviousexampleoftheDflipflopillustrateshowtodescribeasequentialcircuitwiththeprocessstatement.
Althoughtheprocessismainlyusedtodescribesequentialcircuits,onecanalsodescribecombinationalcircuits
withtheprocessconstruct.ThefollowingexampleillustratesthisforaFullAdder,composedoftwoHalf
Adders.Thisexamplealsoillustrateshowoneprocesscangeneratesignalsthatwilltriggerotherprocesseswhen
eventsonthesignalsinitssensitivitylistoccur[3].WecanwritetheBooleanexpressionofaHalfAdderandFull
Adderasfollows:
S_ha=(AB)andC_ha=AB
FortheFullAdder:
Sum=(AB)Cin=S_haCin
Cout=(AB)Cin+AB=S_ha.Cin+C_ha
Figure5illustrateshowtheFullAdderhasbeenmodeled.
Figure5:FullAddercomposedoftwoHalfAdders,modeledwithtwoprocessesP1andP2.
libraryieee
useieee.std_logic_1164.all
entityFULL_ADDERis
port(A,B,Cin:instd_logic
Sum,Cout:outstd_logic)
endFULL_ADDER
architectureBEHAV_FAofFULL_ADDERis
signalint1,int2,int3:std_logic
begin
ProcessP1thatdefinesthefirsthalfadder
P1:process(A,B)
begin
http://www.seas.upenn.edu/~ese171/vhdl/vhdl_primer.html#_Toc526061341
34/50
6/3/2016
VHDLPrimer
int1<=AxorB
int2<=AandB
endprocess
ProcessP2thatdefinesthesecondhalfadderandtheORgate
P2:process(int1,int2,Cin)
begin
Sum<=int1xorCin
int3<=int1andCin
Cout<=int2orint3
endprocess
endBEHAV_FA
Ofcourse,onecouldsimplifythebehavioralmodelsignificantlybyusingasingleprocess.
b.IfStatements
Theifstatementexecutesasequenceofstatementswhosesequencedependsononeormoreconditions.The
syntaxisasfollows:
ifconditionthen
sequentialstatements
[elsifconditionthen
sequentialstatements]
[else
sequentialstatements]
endif
EachconditionisaBooleanexpression.Theifstatementisperformedbycheckingeachconditionintheorder
theyarepresenteduntilatrueisfound.Nestingofifstatementsisallowed.Anexampleofanifstatementwas
givenearlierforaDFlipflopwithasynchronousclearinput.Theifstatementcanbeusedtodescribe
combinationalcircuitsaswell.Thefollowingexampleillustratesthisfora4to1multiplexerwithinputsA,B,C
andD,andselectsignalsS0andS1.Thisstatementmustbeinsideaprocessconstruct.Wewillseethatother
constructs,suchastheConditionalSignalAssignment(Whenelse)orSelectconstructmaybemore
convenientforthesetypeofcombinationalcircuits.
entityMUX_4_1ais
port(S1,S0,A,B,C,D:instd_logic
Z:outstd_logic)
endMUX_4_1a
architecturebehav_MUX41aofMUX_4_1ais
begin
P1:process(S1,S0,A,B,C,D)
begin
if((notS1andnotS0)=1)then
Z<=A
elsif((notS1andS0)=1)then
Z<=B
elsif((S1andnotS0)=1)then
Z<=C
http://www.seas.upenn.edu/~ese171/vhdl/vhdl_primer.html#_Toc526061341
35/50
6/3/2016
VHDLPrimer
else
Z<=D
endif
endprocessP1
endbehav_MUX41a
Aslightlydifferentwayofmodelingthesamemultiplexerisshownbelow,
ifS1=0andS0=0then
Z<=A
elsifS1=0andS0=1then
Z<=B
elsifS1=1andS0=0then
Z<=C
elsifS1=1andS0=1then
Z<=D
endif
Ifstatementsareoftenusedtoimplementstatediagrams.ForanexampleofaMealymachineseeExample
MealyMachinelateron.
c.Casestatements
Thecasestatementexecutesoneofseveralsequencesofstatements,basedonthevalueofasingleexpression.
Thesyntaxisasfollows,
caseexpressionis
whenchoices=>
sequentialstatements
whenchoices=>
sequentialstatements
branchesareallowed
[whenothers=>sequentialstatements]
endcase
Theexpressionmustevaluatetoaninteger,anenumeratedtypeofaonedimensionalarray,suchasabit_vector.
Thecasestatementevaluatestheexpressionandcomparesthevaluetoeachofthechoices.Thewhenclause
correspondingtothematchingchoicewillhaveitsstatementsexecuted.Thefollowingrulesmustbeadheredto:
notwochoicescanoverlap(i.e.eachchoicecanbecoveredonlyonce)
ifthewhenothers"choiceisnotpresent,allpossiblevaluesoftheexpressionmustbecoveredby
thesetofchoices.
Anexampleofacasestatementusinganenumeratedtypefollows.ItgivesanoutputD=1whenthesignal
GRADEShasavaluebetween51and60,C=1forgradesbetween61and70,thewhenotherscoversallthe
othergradesandresultinanF=1.
libraryieee
http://www.seas.upenn.edu/~ese171/vhdl/vhdl_primer.html#_Toc526061341
36/50
6/3/2016
VHDLPrimer
useieee.std_logic_1164.all
entityGRD_201is
port(VALUE:inintegerrange0to100
A,B,C,D:outbit)
endGRD_201
architecturebehav_grdofGRD_201is
begin
process(VALUE)
A<=0
B<=0
C<=0
D<=0
F<=0
begin
caseVALUEis
when51to60=>
D<=1
when61to70|71to75=>
C<=1
when76to85=>
B<=1
when86to100=>
A<=1
whenothers=>
F<=1
endcase
endprocess
endbehav_grd
Weusedtheverticalbar(|)whichisequivalenttotheoroperator,toillustratehowtoexpressarangeof
values.Thisisausefuloperatortoindicaterangesthatarenotadjacent(e.g.0to4|6to10).
Anotherexampleusingthecaseconstructisa4to1MUX.
entityMUX_4_1is
port(SEL:instd_logic_vector(2downto1)
A,B,C,D:instd_logic
Z:outstd_logic)
endMUX_4_1
architecturebehav_MUX41ofMUX_4_1is
begin
PR_MUX:process(SEL,A,B,C,D)
begin
caseSELis
when00=>Z<=A
when01=>Z<=B
when10=>Z<=C
when11=>Z<=D
whenothers=>Z<=X
endcase
endprocessPR_MUX
http://www.seas.upenn.edu/~ese171/vhdl/vhdl_primer.html#_Toc526061341
37/50
6/3/2016
VHDLPrimer
endbehav_MUX41
ThewhenotherscoversthecaseswhenSEL=0X,0Z,XZ,UX,etc.Itshouldbenotedthatthese
combinationalcircuitscanbeexpressedinotherways,usingconcurrentstatementssuchastheWithSelect
construct.Sincethecasestatementisasequentialstatement,onecanhavenestedcasestatements.
d.Loopstatements
Aloopstatementisusedtorepeatedlyexecuteasequenceofsequentialstatements.Thesyntaxforaloopisas
follows:
[loop_label:]iteration_schemeloop
sequentialstatements
[next[label][whencondition]
[exit[label][whencondition]
endloop[loop_label]
Labelsareoptionalbutareusefulwhenwritingnestedloops.Thenextandexitstatementaresequential
statementsthatcanonlybeusedinsidealoop.
Thenextstatementterminatestherestofthecurrentloopiterationandexecutionwillproceedtothenext
loopiteration.
Theexitstatementskipstherestofthestatements,terminatingtheloopentirely,andcontinueswiththe
nextstatementaftertheexitedloop.
Therearethreetypesofiterationschemes:
basicloop
whileloop
forloop
BasicLoopstatement
Thisloophasnoiterationscheme.Itwillbeexecutedcontinuouslyuntilitencountersanexitornextstatement.
[loop_label:]loop
sequentialstatements
[next[label][whencondition]
[exit[label][whencondition]
endloop[loop_label]
Thebasicloop(aswellasthewhileloop)musthaveatleastonewaitstatement.Asanexample,letsconsidera
5bitcounterthatcountsfrom0to31.Whenitreaches31,itwillstartoverfrom0.Awaitstatementhasbeen
includedsothattheloopwillexecuteeverytimetheclockchangesfrom0to1.
Exampleofabasiclooptoimplementacounterthatcountsfrom0to31
entityCOUNT31is
http://www.seas.upenn.edu/~ese171/vhdl/vhdl_primer.html#_Toc526061341
38/50
6/3/2016
VHDLPrimer
port(CLK:instd_logic
COUNT:outinteger)
endCOUNT31
architecturebehav_COUNTofCOUNT31is
begin
P_COUNT:process
variableintern_value:integer:=0
begin
COUNT<=intern_value
loop
waituntilCLK=1
intern_value:=(intern_value+1)mod32
COUNT<=intern_value
endloop
endprocessP_COUNT
endbehav_COUNT
Wedefinedavariableintern_valueinsidetheprocessbecauseoutputportscannotbereadinsidetheprocess.
WhileLoopstatement
ThewhileloopevaluatesaBooleaniterationcondition.WhentheconditionisTRUE,thelooprepeats,
otherwisetheloopisskippedandtheexecutionwillhalt.Thesyntaxforthewhileloopisasfollows,
[loop_label:]whileconditionloop
sequentialstatements
[next[label][whencondition]
[exit[label][whencondition]
endloop[loop_label]
Theconditionoftheloopistestedbeforeeachiteration,includingthefirstiteration.Ifitisfalse,theloopis
terminated.
ForLoopstatement
Theforloopusesanintegeriterationschemethatdeterminesthenumberofiterations.Thesyntaxisasfollows,
[loop_label:]foridentifierinrangeloop
sequentialstatements
[next[label][whencondition]
[exit[label][whencondition]
endloop[loop_label]
Theidentifier(index)isautomaticallydeclaredbytheloopitself,soonedoesnotneedtodeclareit
separately.Thevalueoftheidentifiercanonlybereadinsidetheloopandisnotavailableoutsideitsloop.
Onecannotassignorchangethevalueoftheindex.Thisisincontrasttothewhileloopwhosecondition
caninvolvevariablesthataremodifiedinsidetheloop.
http://www.seas.upenn.edu/~ese171/vhdl/vhdl_primer.html#_Toc526061341
39/50
6/3/2016
VHDLPrimer
Therangemustbeacomputableintegerrangeinoneofthefollowingforms,inwhichinteger_expression
mustevaluatetoaninteger:
integer_expressiontointeger_expression
integer_expressiondowntointeger_expression
e.NextandExitStatement
Thenextstatementskipsexecutiontothenextiterationofaloopstatementandproceedswiththenextiteration.
Thesyntaxis
next[label][whencondition]
ThewhenkeywordisoptionalandwillexecutethenextstatementwhenitsconditionevaluatestotheBoolean
valueTRUE.
Theexitstatementskipstherestofthestatements,terminatingtheloopentirely,andcontinueswiththenext
statementaftertheexitedloop.Thesyntaxisasfollows:
exit[label][whencondition]
ThewhenkeywordisoptionalandwillexecutethenextstatementwhenitsconditionevaluatestotheBoolean
valueTRUE.
Noticethatthedifferencebetweenthenextandexitstatement,isthattheexitstatementterminatestheloop.
f.Waitstatement
Thewaitstatementwillhaltaprocessuntilaneventoccurs.Thereareseveralformsofthewaitstatement,
waituntilcondition
waitfortimeexpression
waitonsignal
wait
TheXilinxFoundationExpresshasimplementedonlythefirstformofthewaitstatement.Thesyntaxisas
follows,
waituntilsignal=value
waituntilsignaleventandsignal=value
waituntilnotsignalstableandsignal=value
TheconditioninthewaituntilstatementmustbeTRUEfortheprocesstoresume.Afewexamples
follow.
waituntilCLK=1
waituntilCLK=0
http://www.seas.upenn.edu/~ese171/vhdl/vhdl_primer.html#_Toc526061341
40/50
6/3/2016
VHDLPrimer
waituntilCLKeventandCLK=1
waituntilnotCLKstableandCLK=1
Forthefirstexampletheprocesswillwaituntilapositivegoingclockedgeoccurs,whileforthesecond
example,theprocesswillwaituntilanegativegoingclockedgearrives.Thelasttwoexamplesareequivalentto
thefirstone(positiveedgeor01transitions).Thehardwareimplementationforthesethreestatementswillbe
identical.
Itshouldbenotedthataprocessthatcontainsawaitstatementcannothaveasensitivitylist.Ifaprocessuses
oneormorewaitstatements,theFoundationExpresssynthesizerwillusesequentiallogic.Theresultsofthe
computationsarestoredinflipflops.
g.Nullstatement
Thenullstatementstatesthatnoactionwilloccur.Thesyntaxisasfollows,
null
Itcanbeusefulinacasestatementwhereallchoicesmustbecovered,evenifsomeofthemcanbeignored.As
anexample,consideracontrolsignalCNTLintherange0to31.WhenthevalueofCNTLis3or15,the
signalsAandBwillbexored,otherwisenothingwilloccur.
entityEX_WAITis
port(CNTL:inintegerrange0to31
A,B:instd_logic_vector(7downto0)
Z:outstd_logic_vector(7downto0))
endEX_WAIT
architecturearch_waitofEX_WAITis
begin
P_WAIT:process(CNTL)
begin
Z<=A
caseCNTLis
when3|15=>
Z<=AxorB
whenothers=>
null
endcase
endprocessP_WAIT
endarch_wait
h.ExampleofaMealyMachine
ThesequencefollowingdetectorrecognizestheinputbitsequenceX:"1011".Themachinewillkeepchecking
fortheproperbitsequenceanddoesnotresettotheinitialstateafteritrecognizesthestring.Incaseweare
implementingaMealymachine,theoutputisassociatedwiththetransitionsasindicatedonthefollowingstate
diagram(Figure6).
http://www.seas.upenn.edu/~ese171/vhdl/vhdl_primer.html#_Toc526061341
41/50
6/3/2016
VHDLPrimer
Figure6:Sequencedetector(1011),realizedasaMealyMachine.
TheVHDLfileisgivenbelow.
VHDLfileforasequencedetector(1011)implementedasaMealyMachine
libraryieee
useieee.std_logic_1164.all
entitymyvhdlis
port(CLK,RST,X:inSTD_LOGIC
Z:outSTD_LOGIC)
end
architecturemyvhdl_archofmyvhdlis
SYMBOLICENCODEDstatemachine:Sreg0
typeSreg0_typeis(S1,S2,S3,S4)
signalSreg0:Sreg0_type
begin
concurrentsignalassignments
Sreg0_machine:process(CLK)
begin
ifCLK'eventandCLK='1'then
ifRST='1'then
Sreg0<=S1
else
caseSreg0is
whenS1=>
ifX='0'then
Sreg0<=S1
elsifX='1'then
Sreg0<=S2
endif
whenS2=>
ifX='1'then
Sreg0<=S2
elsifX='0'then
Sreg0<=S3
endif
whenS3=>
ifX='1'then
http://www.seas.upenn.edu/~ese171/vhdl/vhdl_primer.html#_Toc526061341
42/50
6/3/2016
VHDLPrimer
Sreg0<=S4
elsifX='0'then
Sreg0<=S1
endif
whenS4=>
ifX='0'then
Sreg0<=S3
elsifX='1'then
Sreg0<=S2
endif
whenothers=>
null
endcase
endif
endif
endprocess
signalassignmentstatementsforcombinatorialoutputs
Z_assignment:
Z<='0'when(Sreg0=S1andX='0')else
'0'when(Sreg0=S1andX='1')else
'0'when(Sreg0=S2andX='1')else
'0'when(Sreg0=S2andX='0')else
'0'when(Sreg0=S3andX='1')else
'0'when(Sreg0=S3andX='0')else
'0'when(Sreg0=S4andX='0')else
'1'when(Sreg0=S4andX='1')else
'1'
endmyvhdl_arch
9.DataflowModelingConcurrentStatements
Behavioralmodelingcanbedonewithsequentialstatementsusingtheprocessconstructorwithconcurrent
statements.Thefirstmethodwasdescribedintheprevioussectionandisusefultodescribecomplexdigital
systems.Inthissection,wewilluseconcurrentstatementstodescribebehavior.Thismethodisusuallycalled
dataflowmodeling.Thedataflowmodelingdescribesacircuitintermsofitsfunctionandtheflowofdata
throughthecircuit.Thisisdifferentfromthestructuralmodelingthatdescribesacircuitintermsofthe
interconnectionofcomponents.
Concurrentsignalassignmentsareeventtriggeredandexecutedassoonasaneventononeofthesignalsoccurs.
Intheremainderofthesectionwewilldescribeseveralconcurrentconstructsforuseindataflowmodeling.
a.SimpleConcurrentsignalassignments.
Wehavediscussedseveralconcurrentexamplesearlierinthetutorial.Inthissectionwewillreviewthedifferent
http://www.seas.upenn.edu/~ese171/vhdl/vhdl_primer.html#_Toc526061341
43/50
6/3/2016
VHDLPrimer
typesofconcurrentsignalassignments.
Asimpleconcurrentsignalassignmentisgiveninthefollowingexamples,
Sum<=(AxorB)xorCin
Carry<=(AandB)
Z<=(notX)orYafter2ns
Thesyntaxisasfollows:
Target_signal<=expression
inwhichthevalueoftheexpressiontransferredtothetarget_signal.Assoonasaneventoccursononeofthe
signals,theexpressionwillbeevaluated.Thetypeofthetarget_signalhastobethesameasthetypeofthevalue
oftheexpression.
Anotherexampleisgivenbelowofa4bitaddercircuit.Noticethatwespecifiedthepackage:
IEEE.std_logic_unsignedinordertobeabletousethe+(addition)operator.
ExampleofaFourbitAdderusingconcurrent/behavioralmodeling
libraryieee
useIEEE.std_logic_1164.all
useIEEE.std_logic_unsigned.all
entityADD4is
port(
A:inSTD_LOGIC_VECTOR(3downto0)
B:inSTD_LOGIC_VECTOR(3downto0)
CIN:inSTD_LOGIC
SUM:outSTD_LOGIC_VECTOR(3downto0)
COUT:outSTD_LOGIC
)
endADD4
architectureADD4_concurntofADD4is
defineinternalSUMsignalincludingthecarry
signalSUMINT:STD_LOGIC_VECTOR(4downto0)
begin
<<enteryourstatementshere>>
SUMINT<=('0'&A)+('0'&B)+("0000"&CIN)
COUT<=SUMINT(4)
SUM<=SUMINT(3downto0)
endADD4_concurnt
http://www.seas.upenn.edu/~ese171/vhdl/vhdl_primer.html#_Toc526061341
44/50
6/3/2016
VHDLPrimer
b.ConditionalSignalassignments
Thesyntaxfortheconditionalsignalassignmentisasfollows:
Target_signal<=expressionwhenBoolean_conditionelse
expressionwhenBoolean_conditionelse
:
expression
ThetargetsignalwillreceivethevalueofthefirstexpressionwhoseBooleanconditionisTRUE.Ifnocondition
isfoundtobeTRUE,thetargetsignalwillreceivethevalueofthefinalexpression.Ifmorethanoneconditionis
true,thevalueofthefirstconditionthatisTRUEwillbeassigned.
Anexampleofa4to1multiplexerusingconditionalsignalassignmentsisshownbelow.
entityMUX_4_1_Concis
port(S1,S0,A,B,C,D:instd_logic
Z:outstd_logic)
endMUX_4_1_Conc
architectureconcurr_MUX41ofMUX_4_1_Concis
begin
Z<=AwhenS1=0andS0=0else
BwhenS1=0andS0=1else
CwhenS1=1andS0=0else
D
endconcurr_MUX41
Theconditionalsignalassignmentwillbereevaluatedassoonasanyofthesignalsintheconditionsor
expressionchange.Thewhenelseconstructisusefultoexpresslogicfunctionintheformofatruthtable.An
exampleofthesamemultiplexerasaboveisgivenbelowinamorecompactform.
entityMUX_4_1_funcTabis
port(A,B,C,D:instd_logic
SEL:instd_logic_vector(1downto0)
Z:outstd_logic)
endMUX_4_1_funcTab
architectureconcurr_MUX41ofMUX_4_1_funcTabis
begin
Z<=AwhenSEL=00else
BwhenSEL=01else
CwhenSEL=10else
D
endconcurr_MUX41
NoticethatthisconstructissimplerthantheIfthenelseconstructusingtheprocessstatementorthecase
statement.Analternativewaytodefinethemultiplexeristhecaseconstructinsideaprocessstatement,as
discussedearlier.
http://www.seas.upenn.edu/~ese171/vhdl/vhdl_primer.html#_Toc526061341
45/50
6/3/2016
VHDLPrimer
c.SelectedSignalassignments
Theselectedsignalassignmentissimilartotheconditionalonedescribedabove.Thesyntaxisasfollows,
withchoice_expressionselect
target_name<=expressionwhenchoices,
target_name<=expressionwhenchoices,
:
target_name<=expressionwhenchoices
Thetargetisasignalthatwillreceivethevalueofanexpressionwhosechoiceincludesthevalueofthe
choice_expression.Theexpressionselectedisthefirstwithamatchingchoice.Thechoicecanbeastatic
expression(e.g.5)orarangeexpression(e.g.4to9).Thefollowingrulesmustbefollowedforthechoices:
Notwochoicescanoverlap
Allpossiblevaluesofchoice_expressionmustbecoveredbythesetofchoices,unlessanotherschoiceis
present.
Anexampleofa4to1multiplexerisgivenbelow.
entityMUX_4_1_Conc2is
port(A,B,C,D:instd_logic
SEL:instd_logic_vector(1downto0)
Z:outstd_logic)
endMUX_4_1_Conc2
architectureconcurr_MUX41bofMUX_4_1_Conc2is
begin
withSELselect
Z<=Awhen00,
Bwhen01,
Cwhen10,
Dwhen11
endconcurr_MUX41b
Theequivalentprocessstatementwouldmakeuseofthecaseconstruct.Similarlytothewhenelseconstruct,the
selectedsignalassignmentisusefultoexpressafunctionasatruthtable,asillustratedabove.
Thechoicescanexpressasinglevalue,arangeorcombinedchoicesasshownbelow.
target<=value1when000,
value2when001|011|101,
value3whenothers
Intheaboveexample,alleightchoicesarecoveredandonlyonce.Theotherschoicemustthelastoneused.
http://www.seas.upenn.edu/~ese171/vhdl/vhdl_primer.html#_Toc526061341
46/50
6/3/2016
VHDLPrimer
NoticethattheXilinxFoundationExpressdoesnotallowavectoraschoice_expressionsuchas
std_logic_vector(A,B,C).
Asanexample,letsconsiderafulladderwithinputsA,BandCandoutputssumandcout,
entityFullAdd_Concis
port(A,B,C:instd_logic
sum,cout:outstd_logic)
endFullAdd_Conc
architectureFullAdd_ConcofFullAdd_Concis
defineinternalsignal:vectorINSoftheinputsignals
signalINS:std_logic_vector(2downto0)
begin
definethecomponentsofvectorINSoftheinputsignals
INS(2)<=A
INS(1)<=B
INS(0)<=C
withINSselect
(sum,cout)<=std_logic_vector(00)when000,
std_logic_vector(10)when001,
std_logic_vector(10)when010,
std_logic_vector(01)when011,
std_logic_vector(10)when100,
std_logic_vector(01)when101,
std_logic_vector(01)when110,
std_logic_vector(11)when111,
std_logic_vector(11)whenothers
endFullAdd_Conc]
Notice:IntheexampleabovewehadtodefineaninternalvectorINS(A,B,C)oftheinputsignalstouseaspart
ofthewithselectwhenstatement.ThiswasdonebecausetheXilinxFoundationdoesnotsupportthe
constructstd_logic_vector(A,B,C).
10.StructuralModeling
StructuralmodelingwasdescribedbrieflyinthesectionStructuralModelinginBasicStructureofaVHDLfile.
Astructuralwayofmodelingdescribesacircuitintermsofcomponentsanditsinterconnection.Eachcomponent
issupposedtobedefinedearlier(e.g.inpackage)andcanbedescribedasstructural,abehavioralordataflow
model.Atthelowesthierarchyeachcomponentisdescribedasabehavioralmodel,usingthebasiclogic
operatorsdefinedinVHDL.Ingeneralstructuralmodelingisverygoodtodescribecomplexdigitalsystems,
thoughasetofcomponentsinahierarchicalfashion.
Astructuraldescriptioncanbestbecomparedtoaschematicblockdiagramthatcanbedescribedbythe
componentsandtheinterconnections.VHDLprovidesaformalwaytodothisby
http://www.seas.upenn.edu/~ese171/vhdl/vhdl_primer.html#_Toc526061341
47/50
6/3/2016
VHDLPrimer
Declarealistofcomponentsbeingused
Declaresignalswhichdefinethenetsthatinterconnectcomponents
Labelmultipleinstancesofthesamecomponentsothateachinstanceisuniquelydefined.
Thecomponentsandsignalsaredeclaredwithinthearchitecturebody,
architecturearchitecture_nameofNAME_OF_ENTITYis
Declarations
componentdeclarations
signaldeclarations
begin
Statements
componentinstantiationandconnections
:
endarchitecture_name
a.Componentdeclaration
Beforecomponentscanbeinstantiatedtheyneedtobedeclaredinthearchitecturedeclarationsectionorinthe
packagedeclaration.Thecomponentdeclarationconsistsofthecomponentnameandtheinterface(ports).The
syntaxisasfollows:
componentcomponent_name[is]
[port(port_signal_names:modetype
port_signal_names:modetype
:
port_signal_names:modetype)]
endcomponent[component_name]
Thecomponentnamereferstoeitherthenameofanentitydefinedinalibraryoranentityexplicitlydefinedinthe
VHDLfile(seeexampleofthefourbitadder).
Thelistofinterfaceportsgivesthename,modeandtypeofeachport,similarlyasisdoneintheentity
declaration.
Afewexamplesofcomponentdeclarationfollow:
componentOR2
port(in1,in2:instd_logic
out1:outstd_logic)
endcomponent
componentPROC
port(CLK,RST,RW,STP:instd_logic
ADDRBUS:outstd_logic_vector(31downto0)
DATA:inoutintegerrange0to1024)
componentFULLADDER
http://www.seas.upenn.edu/~ese171/vhdl/vhdl_primer.html#_Toc526061341
48/50
6/3/2016
VHDLPrimer
port(a,b,c:instd_logic
sum,carry:outstd_logic)
endcomponent
Asmentionedearlier,thecomponentdeclarationhastobedoneeitherinthearchitecturebodyorinthepackage
declaration.Ifthecomponentisdeclaredinapackage,onedoesnothavetodeclareitagaininthearchitecture
bodyaslongasoneusesthelibraryanduseclause.
b.ComponentInstantiationandinterconnections
Thecomponentinstantiationstatementreferencesacomponentthatcanbe
Previouslydefinedatthecurrentlevelofthehierarchyor
Definedinatechnologylibrary(vendorslibrary).
Thesyntaxforthecomponentsinstantiationisasfollows,
instance_name:componentname
portmap(port1=>signal1,port2=>signal2,port3=>signaln)
Theinstancenameorlabelcanbeanylegalidentifierandisthenameofthisparticularinstance.Thecomponent
nameisthenameofthecomponentdeclaredearlierusingthecomponentdeclarationstatement.Theportnameis
thenameoftheportandsignalisthenameofthesignaltowhichthespecificportisconnected.Theaboveport
mapassociatestheportstothesignalsthroughnamedassociation.Analternativemethodisthepositional
associationshownbelow,
portmap(signal1,signal2,signaln)
inwhichthefirstportinthecomponentdeclarationcorrespondstothefirstsignal,thesecondporttothesecond
signal,etc.Thesignalpositionmustbeinthesameorderasthedeclaredcomponentsports.Onecanmixnamed
andpositionalassociationsaslongasoneputsallpositionalassociationsbeforethenamedones.Thefollowing
examplesillustratesthis,
componentNAND2
port(in1,in2:instd_logic
out1:outstd_logic)
endcomponent
signalint1,int2,int3:std_logic
architecturestructofEXAMPLEis
U1:NAND2portmap(A,B,int1)
U2:NAND2portmap(in2=>C,in2=>D,out1=>int2)
U3:NAND3portmap(in1=>int1,int2,Z)
..
AnotherexampleistheBuzzercircuitofFigure2.
http://www.seas.upenn.edu/~ese171/vhdl/vhdl_primer.html#_Toc526061341
49/50
6/3/2016
VHDLPrimer
11.References
1.D.GajskiandR.Khun,Introduction:NewVLSITools,IEEEComputer,Vol.16,No.12,pp.1114,
Dec.1983.
2.M.ManoandC.Kime,LogicandComputerDesignFundamentals,2ndEdition,PrenticeHall,Upper
SaddleRiver,2001.
3.S.Yalamanchili,VHDLStartersGuide,PrenticeHall,UpperSaddleRiver,1998.
4.J.Bhasker,VHDLPrimer,3rdEdition,PrenticeHall,UpperSaddleRiver,1998.
5.P.J.Ashenden,TheStudentsGuidetoVHDL,MorganKaufmannPublishers,Inc,SanFrancisco,
1998.
6.A.Dewey,AnalysisandDesignofDigitalSystems,PWSPublishingCompany,NewYork,1997.
7.C.H.Roth,DigitalSystemDesignusingVHDL,PWSPublishingCompany,NewYork,1998.
8.D.PellerinandD.Taylor,VHDLMadeEasy!,,PrenticeHall,UpperSaddleRiver,1997.
9.VHDLReferenceGuide,Xilinx,Inc.,1999(availableonline:http://toolbox.xilinx.com/docsan/(select
FoundationSeries)
Copyright2001CreatedbyJanVanderSpiegel,Sept.28,2001UpdatedAugust6,2006
GotoESE201
http://www.seas.upenn.edu/~ese171/vhdl/vhdl_primer.html#_Toc526061341
50/50