laboratory experiment – mastering digital design (part ii) she… · mastering digital design...

8
Mastering Digital Design Department of EEE with Verilog on FPGAs Imperial College London v5.0 - PYK Cheung, 9 Oct 2017 Part 2 - 1 MSc Course on Analogue and Digital IC Design Laboratory Experiment – Mastering Digital Design (Part II) (webpage: http://www.ee.ic.ac.uk/pcheung/teaching/MSc_Experiment/) PART 2 – Counters and FSMs 1.0 Learning Outcomes Part 2 of the experiment teaches you: how to design different types of counters and timers; how to use the Modelsim simulator to verify the correct function of your design and the use of testbenches; how to predict the maximum operating clock frequency of your circuit sequential circuits; how to design some useful timing and counting components for later part of the experiment. 1.1 Experiment 5: Designing a Counter Step 1: Create the project for an 8-bit counter Create in your directory a folder named part_2. Click file>New Project Wizard, and create project ex5 and top level file ex5_top. Then click Finish. Create the Verilog file: “counter_8.v” which contains your design in Verilog. I suggest you use convention of using “_n” to indicate the number of bits in a module. Click File > New … and select Verilog as the new file. An edit window will appear. Step 2: Enter the Verilog specification of the 8-bit binary counter Enter the Verilog module as shown below (next page). Although you can miss out the comments, I recommend that you to retain them because the code is deliberately verbose in order to explain the meaning of the Verilog language. The line `timescale 1ns / 100ps tells the system to use 1 ns as the unit time step with a time resolution of 100ps. Make sure that you fully understand this Verilog code before proceeding to the next step. Save the file as counter_8.v. (I recommend that you use module name as the file name to avoid confusion.) Step 3: Enter the Verilog specification of the 8-bit binary counter While is opened in the Editor window, click Project > Add Current File to Project, then click Project > Set as Top Level Entity. This command tells Quartus that this module is the top-level of your design. Normally we use …_top.v as the top-level module, which connects to physical pins of the FPGA. However, for this experiment, the counter module is verified through simulation. So we don’t need to create pin connects. The “Set as Top Level Entity” is very useful if you want to use the simulator to verify different modules in a large design. You can move up and down the module hierarchy and verify them from the lowest level up.

Upload: others

Post on 04-Apr-2020

8 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Laboratory Experiment – Mastering Digital Design (Part II) She… · Mastering Digital Design Department of EEE with Verilog on FPGAs Imperial College London v5.0 - PYK Cheung,

MasteringDigitalDesign DepartmentofEEEwithVerilogonFPGAs ImperialCollegeLondon

v5.0-PYKCheung,9Oct2017 Part2-1

MScCourseonAnalogueandDigitalICDesign

LaboratoryExperiment–MasteringDigitalDesign(PartII)

(webpage:http://www.ee.ic.ac.uk/pcheung/teaching/MSc_Experiment/)

PART2–CountersandFSMs

1.0LearningOutcomes

Part2oftheexperimentteachesyou:

• howtodesigndifferenttypesofcountersandtimers;• howtousetheModelsimsimulatortoverifythecorrectfunctionofyourdesignand

theuseoftestbenches;• how to predict themaximum operating clock frequency of your circuit sequential

circuits;• how to design some useful timing and counting components for later part of the

experiment.

1.1 Experiment5:DesigningaCounterStep1:Createtheprojectforan8-bitcounter

• Createinyourdirectoryafoldernamedpart_2.• Click file>New ProjectWizard, and create projectex5 and top level fileex5_top.

ThenclickFinish.• Create the Verilog file: “counter_8.v” which contains your design in Verilog. I

suggestyouuseconventionofusing“_n”toindicatethenumberofbitsinamodule.• ClickFile>New…andselectVerilogasthenewfile.Aneditwindowwillappear.

Step2:EntertheVerilogspecificationofthe8-bitbinarycounter

• EntertheVerilogmoduleasshownbelow(nextpage). Althoughyoucanmissoutthe comments, I recommend that you to retain them because the code isdeliberatelyverboseinordertoexplainthemeaningoftheVeriloglanguage.

• The line `timescale1ns / 100ps tells the systemtouse1nsas theunit timestepwithatimeresolutionof100ps.

• MakesurethatyoufullyunderstandthisVerilogcodebeforeproceedingtothenextstep.Savethefileascounter_8.v.(Irecommendthatyouusemodulenameasthefilenametoavoidconfusion.)

Step3:EntertheVerilogspecificationofthe8-bitbinarycounter

• WhileisopenedintheEditorwindow,click Project>AddCurrentFiletoProject,thenclickProject>SetasTopLevelEntity. ThiscommandtellsQuartusthatthismoduleisthetop-levelofyourdesign.

Normally we use …_top.v as the top-level module, which connects tophysical pins of the FPGA. However, for this experiment, the countermodule is verified through simulation. So we don’t need to create pinconnects.The“SetasTopLevelEntity”isveryusefulifyouwanttousethesimulatortoverifydifferentmodulesinalargedesign.Youcanmoveupanddownthemodulehierarchyandverifythemfromthelowestlevelup.

Page 2: Laboratory Experiment – Mastering Digital Design (Part II) She… · Mastering Digital Design Department of EEE with Verilog on FPGAs Imperial College London v5.0 - PYK Cheung,

MasteringDigitalDesign DepartmentofEEEwithVerilogonFPGAs ImperialCollegeLondon

v5.0-PYKCheung,9Oct2017 Part2-2

• ClickProcessing>AnalyzeCurrentFile.Thisisthefastestwaytocheckifthis.vfilehasanysyntaxerror.

• ThenClickProcessing>Start>StartAnalysisandSynthesis.ThistakesthecurrentVerilogmodule (andallothermodulesthat ituses ifany),andproducearegister-levelmodelofyourdesignreadyforregister-transferlevel(RTL)simulation.Unlikefullcompilation,thisstepdoesnotrequirepinassignmentandotherdevicespecificsteps,butissufficientforyoutosimulatethecircuitasspecifiedinVerilog.

Verilogcode:8-bitcounter(Notethatthefirstcharacteronline1before

‘timescale’isabackquote`-noteasytofindonmanykeyboards!)

Step4:Simulatethebinarycounter

• ClickTools>RunSimulationTools>RTL Simulation. This commandstarts up Modelsim simulatorprogramme as a separate process.NowyouhaveenteredtheModelsimenvironment.

• ClickSimulate>StartSimulation….Thenselectwork -> counter_8 fromthe popup window. This tellsModelsimtosimulatethismodule.

• NotethatModelsimprovidesanumberofwindowpanes.ThemostimportantistheTranscriptpane– this iswhereyouenter commands1todrive the simulator. Thewavepaneiswhereresultsaredisplayedaswaveforms.Youarerecommendedtoun-dockthispaneasshownbelowsothatitisinaseparatewindowandspansthewholewidthofyourmonitor.Finally,thereistheobjectpane,whichshowsallthesignals(objects)ofyourdesign.

1ModelsimusesascriptinglanguageknownasTclinordertocontrolhowitisdriven.YouonlyneedtolearnTclifyouwanttodoadvancestuffwithModelsimforyourpersonalinterest.

Page 3: Laboratory Experiment – Mastering Digital Design (Part II) She… · Mastering Digital Design Department of EEE with Verilog on FPGAs Imperial College London v5.0 - PYK Cheung,

MasteringDigitalDesign DepartmentofEEEwithVerilogonFPGAs ImperialCollegeLondon

v5.0-PYKCheung,9Oct2017 Part2-3

Step 5: Add waveforms to the Wave window and drivesignals

• Inthetranscriptwindow,entertwocommands:“addwave clock enable” and “add wave –hexadecimalcount”. Thiswill add these signals aswaveforms inthe wave pane and show count values ashexadecimal.

• Nowwewanttodriveclockwitha50MHzsymmetricalsignal.Todothis,enter:• Enter:“forceenable1”toenablethecounter.• Enter:“run100ns”torunthesimulatorfor5clockcycles(5x20ns=100ns).• Youwill see thewaveformpane showing the counter counting from0 to 5.Now

forceenablelowandrunforanother100ns.Thenhighagainandrunfor100ns.

• Clickonthewaveformputacursorataspecifictimeforinspectingthesignalvalues.The icons above thewaveforms (as labeled) allow you to zoom in andout of thewaveform.Trythisyourself.

Page 4: Laboratory Experiment – Mastering Digital Design (Part II) She… · Mastering Digital Design Department of EEE with Verilog on FPGAs Imperial College London v5.0 - PYK Cheung,

MasteringDigitalDesign DepartmentofEEEwithVerilogonFPGAs ImperialCollegeLondon

v5.0-PYKCheung,9Oct2017 Part2-4

Step6:CreateaTestbenchasaDO-file

• Interactively specifying the drivingsignals is very tedious and prone toerror. Therefore thepreferredmethodistocreatea“do”filewhichisatextfilecontainingasequenceofcommands(asyou have previously entered in thetranscriptwindow).

• Click File > new > source and selectnew“do”file.Thenenterthecommandlinesasshownontheright. Thensavethisas“tb_counter.do”.

• Deleteallsignalsfromthewavewindow,andentercommandvsim>restartvsim>do./tb_counter.do

• This should provide exactly the same waveform results as in step 5. However,the .do file can be reused and modified far easier than typing them into thetranscriptwindow.Itactsasasimpleformofatest-harness(ortestbench)foryourdesign. Generally speaking, you must produce testbenches for all your designsinsteadofusinginteractivemeanstotestyourcircuit.Notonlybecausethissavestime, it alsoallowsyou to change the codeandverify its correctness in the samewayforeachversionofyourdesign.

Step7:Singlestepping

• Modelsimisverypowerful.YoucanuseittodebugyourVerilogdesignalmostlikesoftware.However,dorememberthatwearedealingwithahardwaredescriptionthatoperatesinparallel. Incontrast,softwarecodesaregenerallyproceduralandoperatesequentially.

• Trythevsim>stepcommandorclickonthestep-commandpane towatchhowyoucanstepthroughyourVerilogcode. Signalvalues intheobjectandthewavewindowsareupdatedaccordingly.

• Modelsimhasmanyusefulfeaturestohelpyoudebugyourdesign.DetailsofallthecommandscanbefoundintheModelsimReferenceManual.ThisiseasilyavailableunderHelp>PDFDocumentations>ReferenceManual.Bewarethatthismanualisverythick!DONOTprintthisout.

2.0Experiment6:Implementinga16-bitcounteronDE1

Inthispartoftheexperiment,youwilltestyourcounterdesignontheDE1board.Youwillalsolearnhowtofindthemaximumclockfrequencythatyourdesignwillworkcorrectly.

Step1: Createanewprojectex6,andcopytothisdirectlyyourfilescounter_8.v.Modifycounter_8.vtocounter_16.vandmakeita16-bitcounter.Furthermore,addaresetinputtoresetthecountvaluetozerosynchronouslytotheclock.Downloadfromtheexperimentwebpagethecomponentbin2bcd_16.v,amoduleIhavedesignedtoconverta16-bitbinarynumber to 5 BCDdigits. Youwill also need the add3_ge5.vmodule. Put thesemodule inthe../mylibfolder,whichshouldalsocontainedthehex_to_7seg.vyoudesignedinPart1.

Step2:Createatop-levelmoduleex6_top.v inVerilogtospecifythecircuitshownbelow.MakesurethatyouhaveaddedalltherelevantVerilogmodulestotheprojectusingProject> Add/Remove Files in Project: counter_16.v, ex6_top.v and finally add hex_to_7seg.v,

Page 5: Laboratory Experiment – Mastering Digital Design (Part II) She… · Mastering Digital Design Department of EEE with Verilog on FPGAs Imperial College London v5.0 - PYK Cheung,

MasteringDigitalDesign DepartmentofEEEwithVerilogonFPGAs ImperialCollegeLondon

v5.0-PYKCheung,9Oct2017 Part2-5

add3_ge5.v and bin2bcd_16.v from your library folder ../mylib/. Go to the ex6_top.vwindowandsetthisfileasyourtop-levelmodule.

Step3:UseProcessing>AnalyzeCurrentFilecheckyournewlycreateVerilogfiles.Thisisthequickestwayto find thebasicsyntaxerrors inyourVerilogcode. Onceall thesimpleerrorsarefixed,useProcessing>StartAnalysisandElaborationtoperformfullercheckofthe “ex6_top.v” tomake sure that files are consistent and correct. There is no need tosimulatethiscircuit.

Step4: Selecting theFPGADevice–ClickAssignments>Device….andselectthecorrectCycloneVFPGA:5CSEMA5F31C6.

Step5:PinAssignment–Opentheex6_top.qsffile.Examineitscontent.Youwillfindthatnopinsarebeingassignedyet.Insertintothisfileallthepinassignments.Theeasiestwaytodothisisclickon:Edit>Insertfile..thenselect../pin_assignment.txt(youshouldhavedownloadedthisfilefromtheExperimentwebpage).Notethatyouarecurrentlynotusingall thepinsassigned in thepin_assignment.txt file. Don’tworry.Thiswillonlyproduceafewmorewarningmessages.Fullcompilationcanstillgoaheadwithouterrors.

Step6: Set clock frequency–Createanewfile“ex6_top.sdc”2whichshouldcontainonesingleline:

create_clock-name"CLOCK_50"-period20.000ns[get_ports{CLOCK_50}]

Withthis,QuartuswillknowthatthesignalCLOCK_50isa50MHzclock.

Step 7: Full Compilation – Click: Processing > StartCompilation. This will go through the entire compilationprocess.ExaminetheTaskswindowontheleftandseeallthestepsbeingtakeninordertogeneratethefinalbit-stream.

Step 8: Maximum clock frequency – As part of thecompilation process, TimeQuest timing analyzer is used topredict various timing information. In the “CompilationReport” window, you should see a list of reports resultingfrom the compilation. Double-click TimeQuest TimingAnalyzer entry, and you should see a list similar to the oneshownhere. Clickingonvariousentriesunderthiswill showthevarioustimingspecifications.Answerthefollowingquestions:

2SynopsisDelayConstraint(.sdc)filesarestandardformattedfilesintroducedbySynopsis,awell-knowncompanyspecializingonICdesignCADtools.Withthis,adesignercanspecifyvarioustimingconstraintsfortheCADtoolsthecheckagainst.Hereweareonlyusingthistodefineclockfrequency.

Page 6: Laboratory Experiment – Mastering Digital Design (Part II) She… · Mastering Digital Design Department of EEE with Verilog on FPGAs Imperial College London v5.0 - PYK Cheung,

MasteringDigitalDesign DepartmentofEEEwithVerilogonFPGAs ImperialCollegeLondon

v5.0-PYKCheung,9Oct2017 Part2-6

Whatarethepredictedmaximumfrequenciesforthiscircuitunderthehighestandlowesttemperatures?Whataretheotherinterestingtimingdatathatyoucandiscoverwiththesereports?WhyistheTimeQuestentryred,indicatingthattheremaybeaproblem?

Step9: TestyourdesignonDE1–programtheDE1andcheckthatyourdesignworks.

Step10:ExaminetheamountofFPGAresourcesbeingusedbythis16-bitcounter.Explaintheresults.

Test-yourselfTask(compulsory)–Cascadecounter

You are now required to create something yourself. In the previous exercise, the 16-bitcounteriscountinga20MHzclock.Thisismuchtoofastforustoseethecounterchanging.This part of the experiment requires you use the counter to count the number ofmillisecond elapsed. You would need to do this by having two counters cascaded (i.e.connectedinseries)witheachother.Theoverallblockdiagramisshownbelow.

The divide-by-50000 circuit generates a 1 cycle high pulse every 50,000 clock cycles.Thereforetheoutputsignaltickprovidesoneenablepulseeverymillisecond.(Seenotes.)

ModifyyourcircuittoimplementthisandtestthenewcircuitontheDE1board.

3.0Experiment7:LinearFeedbackShiftRegister(LFSR)andPRBS

You will have encountered a 4-bit LFSR in my introductory talks, which implements theprimitive polynomial: 1 + X3 + X4. You are now required to implement a 7-bit LFSRimplementingthepolynomial:1+X+X7.Assumingthatyouinitializetheshiftregisterto7’d1,workoutmanuallythefirst10sequencevaluesoftheoutputsequence.(Theoutputsequence should be 127 long without repetition, is known as a pseudo-random binarysequenceorPRBS.)

ConnecttheshiftregisterclocktoKEY[3]andusethemomentarykeytocyclethroughthefirst ten valuesof thePRBS. The randomoutput shouldbedisplayed as twohexadecimaldigits.

Checkpoint:Youshouldgettothispointbytheendofthesecondweek.

Page 7: Laboratory Experiment – Mastering Digital Design (Part II) She… · Mastering Digital Design Department of EEE with Verilog on FPGAs Imperial College London v5.0 - PYK Cheung,

MasteringDigitalDesign DepartmentofEEEwithVerilogonFPGAs ImperialCollegeLondon

v5.0-PYKCheung,9Oct2017 Part2-7

4.0Experiment8(Optionalchallenge):Startinglinedelaycircuit

Thenexttwoexperimentsareoptional.Theyaredesignedtoprovideachallengetothosewhofinishearly,orforthosewhowanttolearnmoreaboutdigitaldesign,VerilogandFPGAs.Thetwoexperimentsarelinked–whatyoudesignedinExperiment8willbeusedinExperiment9.

ThegoalhereistodesignaFormula1styleofracestartinglights.Thespecificationofyourcircuitis:

1. Thecircuitistriggered(orstarted)bypressingKEY[3](don’tforgetKEY[3]islowactive);

2. The10LEDs(belowthe7-segmentdisplays)willthenstartlightingupfromlefttorightat0.5secondinterval,untilallLEDsareON;

3. Thecircuitthenwaitsforarandomperiodoftimebetween0.25and16secondsbeforeallLEDsturnOFF;

4. Youshouldalsodisplaytherandomdelayperiodinmillisecondsonfive7-segmentdisplays.

Inordertoassistyouindesigningthiscircuitwithoutspendingtoomuchtime,thefollowingoverallblockdiagramofthecircuitisprovided.Youshouldalsodownloadthesolutionbit-streamforthisexperimentfromtheexperimentwebpage(ex8sol.sof)andtryitoutbeforeattemptityourself.

Intheabovediagram,allsignalsontheleftoftheblockareinputsandthesignalsontherightareoutputs.

Thetwoclockdividercircuitsprovideclockticksonceevery1msand0.5secrespectively.EachclocktickshouldbeapositivepulselastingoneperiodofCLOCK_50(i.e.20ns).Thesystemthenusethetick_mssignalastheclockoftheremainingcircuit.

TheLFSRmoduleproducesapseudo-randombinarysequence(PRBS),whichisusedtodeterminetherandomdelayrequired.TheenablesignaltotheLFSRallowsthistocyclethroughanumberofclockcyclesbeforeitisstoppedatarandomvalue.

Thedelaymoduleistriggeredafterall10LEDsarelid,andthenprovidesadelayofNclockcycles(at1msperiod)beforeassertingthetime_outsignal(for1ms).

ThedelayvalueNisfedtothebinarytoBCDconverter,whichthendrivesthe7-segmentdisplays.

Thereareanumberofdesigndecisionstobemade:

Page 8: Laboratory Experiment – Mastering Digital Design (Part II) She… · Mastering Digital Design Department of EEE with Verilog on FPGAs Imperial College London v5.0 - PYK Cheung,

MasteringDigitalDesign DepartmentofEEEwithVerilogonFPGAs ImperialCollegeLondon

v5.0-PYKCheung,9Oct2017 Part2-8

1. HowmanybitsLFSRisrequired?2. Howmanybitsshouldyouuseinthedelaymodule?

TheFSMmoduleisthekeymoduletotheentiresystem.Youhavetodecidewhatarethestatesthatarerequired,drawthestatediagramandthenmapthattoVerilog.

5.0Experiment9(Optionalchallenge):AReactionMeter

ExtendyourcircuitinExperiment8byaddingareactioncounter.ThisshouldcountthetimebetweenalltheLEDsturningOFFandyoupressingKEY[0].Thereactiontime,insteadoftherandomdelay,shouldbedisplayedonthe7-segmentdisplaysinmilliseconds.