Laboratory Experiment – Mastering Digital Design · Quartus provides a complete environment for...

32
Mastering Digital Design Department of EEE with Verilog on FPGAs Imperial College London V5.0 - PYK Cheung, 9 Oct 2017 Part 1 - 1 MSc Course on Analogue and Digital IC Design Imperial College London Laboratory Experiment – Mastering Digital Design (webpage: http://www.ee.ic.ac.uk/pcheung/teaching/MSc_Experiment/) This Laboratory Experiment is intended to ensure all students on the ADIC MSc course reach an expected level of competence in digital design using a hardware description language (such as Verilog) implemented on an FPGA. Those students with limited or no prior experience in both Verilog and/or FPGA may need to devote time outside the scheduled period to complete the experiment. The experiment is organized in four parts, each with clearly defined learning outcomes. See the document entitled: “Mastering Digital Design – Experiment Specification Document”. Objectives By the end of this experiment, you should have learned: How to design digital circuits using Intel/Altera’s Quartus II Design software; How to design digital circuits targeting Altera’s Cyclone V FPGA using Terasic’s DE1- SoC Board; How to design digital circuits in efficient, synthesizable Verilog HDL; How to evaluate your design in terms of resource utilization and clock speed; How to use the DE1-SoC FPGA board with its custom daughter board for analogue I/O functions; Have designed something yourself for the Cyclone V FPGA. Before you start Before you come to the laboratory, you are expected to: Have understood the lectures on Verilog Be familiar with the basic architecture inside the FPGA Have read through this Laboratory instructions

Transcript of Laboratory Experiment – Mastering Digital Design · Quartus provides a complete environment for...

Page 1: Laboratory Experiment – Mastering Digital Design · Quartus provides a complete environment for you to implement your design on an Altera FPGA. It supports all aspects of the design

MasteringDigitalDesign DepartmentofEEEwithVerilogonFPGAs ImperialCollegeLondon

V5.0-PYKCheung,9Oct2017 Part1-1

MScCourseonAnalogueandDigitalICDesign

ImperialCollegeLondon

LaboratoryExperiment–MasteringDigitalDesign

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

ThisLaboratoryExperimentisintendedtoensureallstudentsontheADICMSccoursereachanexpectedlevelofcompetenceindigitaldesignusingahardwaredescriptionlanguage(suchasVerilog)implementedonanFPGA.ThosestudentswithlimitedornopriorexperienceinbothVerilogand/orFPGAmayneedtodevotetimeoutsidethescheduledperiodtocompletetheexperiment.

Theexperimentisorganizedinfourparts,eachwithclearlydefinedlearningoutcomes.Seethedocumententitled:“MasteringDigitalDesign–ExperimentSpecificationDocument”.

Objectives

Bytheendofthisexperiment,youshouldhavelearned:

• HowtodesigndigitalcircuitsusingIntel/Altera’sQuartusIIDesignsoftware;• HowtodesigndigitalcircuitstargetingAltera’sCycloneVFPGAusingTerasic’sDE1-

SoCBoard;• Howtodesigndigitalcircuitsinefficient,synthesizableVerilogHDL;• Howtoevaluateyourdesignintermsofresourceutilizationandclockspeed;• HowtousetheDE1-SoCFPGAboardwith itscustomdaughterboard foranalogue

I/Ofunctions;• HavedesignedsomethingyourselffortheCycloneVFPGA.

Beforeyoustart

Beforeyoucometothelaboratory,youareexpectedto:

• HaveunderstoodthelecturesonVerilog• BefamiliarwiththebasicarchitectureinsidetheFPGA• HavereadthroughthisLaboratoryinstructions

Page 2: Laboratory Experiment – Mastering Digital Design · Quartus provides a complete environment for you to implement your design on an Altera FPGA. It supports all aspects of the design

MasteringDigitalDesign DepartmentofEEEwithVerilogonFPGAs ImperialCollegeLondon

V5.0-PYKCheung,9Oct2017 Part1-2

BoththeexperimentalboardandaPCwouldbemadeavailabletoyouduringyourallottedperiodinthelaboratory.Inaddition,youmayalsoborrowaDE1-SoCboardtouseathomeforthedurationofthisexperiment.

Thisinstructionmanualisdividedintofourparts,oneforeachweek.Eachparthasitsowngoalsandlearningoutcomes.

Somestudentswill findthisexperimentharderoreasier thanaverage,dependingonyourpriorexperiencewithdigitallogic.Therefore,thefourLabsessionscontainthecompulsoryswellasoptionalexercisers.Ifyoufallbehindthisexperimentduringanyweek, it iswisetofind a bit of spare time to catch up outside the official laboratory sessions and restrictyourselftothecompulsorypartsonly.

PARTI–SchematictoVerilog(LearningOutcomes)

BasiccompetenceinusingIntel/Altera’sQuartusdesignsystemsforCyclone-VFPGA;appreciatethesuperiorityofhardwaredescriptionlanguageoverschematiccapturefordigitaldesign;useofcasestatementtospecifycombinatorialcircuit;usehigherlevelconstructsinVerilogtospecifycomplexcombinatorialcircuits;developcompetenceintakingadesignfromdescriptiontohardware.

1.0Introduction

You should have done some background reading before attending thelaboratorysessionassuggestedattheLecture.

FPGAs is a type of programmable logic devices introduced by Xilinx in1985. It is now the predominant technology for implementing digitallogic in lowtomoderatevolumeproduction. Thebasic structureofanFPGA is shown below. It consists of threemain types of resources: 1)LogicBlocks (orElements);2)RoutingResources;3) I/OPad. Formore

Page 3: Laboratory Experiment – Mastering Digital Design · Quartus provides a complete environment for you to implement your design on an Altera FPGA. It supports all aspects of the design

MasteringDigitalDesign DepartmentofEEEwithVerilogonFPGAs ImperialCollegeLondon

V5.0-PYKCheung,9Oct2017 Part1-3

LogicBlocks (orElements);2)RoutingResources;3) I/OPad. Formore informationaboutFPGA,seeLecture1notesavailableontheE2DigitalElectronicscoursewebpage.

1.1 QuartusDesignSuite

Quartus provides a complete environment for you to implement your design on anAlteraFPGA. It supportsallaspectsof thedesign flow,which is typically followingtheflowdiagramshownhere.ThebestwaytolearnQuartusistogothroughthisexperimentstep-by-step.Afteryouhavelearnedthebasics,youcanstarttoexploreotheraspectsoftheQuartussystem.

1.2 DE1-SoCBoard

DE1-SoCBoardisdesignedandmadebyTerasic.ItisbasedaroundaCycloneVFPGAfromAltera.IncludeontheDE1boardarevariousI/Odevicessuchas7-segmentLEDdisplays,LED,switches,VGAport,RS232port,SDcardslotetc.Ablockdiagramof theDE1board is shownbelow. Although theCycloneVincludes adual-coreARMprocessor,wewill onlybeusing the FPGApartoftheFPGAforthisexperiment.

1.4 VerilogHardwareDescriptionLanguage

Oneof thekey learningobjectiveof thisexperiment is foryou to learn theVerilogHardwareDescriptionLanguage(HDL),which iscommonlyusedtospecifyFPGAandothertypesofchipdesigns.Anexcellenttutorialcanbefoundon:

http://www.asic-world.com/verilog/veritut.html. A Verilog Syntax Summary sheet isprovidedinAppendixA.

1.5 UsingQuartusPrimesoftwareandDE1athome

Ifyourownlaptopissufficientlypowerful(atleast4GBofRAM)andhasplentyoffreediskspace(atleast1GBoffreediskspace),youmaywanttoinstallacopyoftheQuartusdesignsoftwareonyourowncomputer.ThelatestversionisQuartusversion17.

YourclassisdividedintoGroupsoftwostudents.Youmaychooseyourowngrouppartner.If youdon’t find anyone toworkwith, letme knowand Iwill pair youupwith someone.Each pair of students will be issued with your own DE1-SoC board with an analogue I/Oboardforthedurationofthisexperiment.YoumaytaketheboardhomewithyouoruseitinRoom909(MScLab).However,youareresponsiblefortheboarduntilitisreturned.

To install your own copy of Quartus, you should go to Altera’s website to register, thendownload the free Quartus Prime Light Edition from: http://dl.altera.com/?edition=web.NotethatQuartusandtheDE1boardonlyworkswithMSWindowsorLinux. IfyouareaMacuser,youwouldneedto runavirtualmachine (e.g.VirtualBox,ParallelsorVMware),loadaversionofWindowsorLinux,andthenrunQuartusunderthatenvironment.

PlugtheDE1boardtoaUSBportonyourcomputerandturnitON(redbutton).Itwillaskyouforadevicedriver,whichcanbefoundintheQuartussoftwaredirectory….\drivers.See“DE1-SoCGettingStartedGuide”fromtheexperimentwebpage.

Page 4: Laboratory Experiment – Mastering Digital Design · Quartus provides a complete environment for you to implement your design on an Altera FPGA. It supports all aspects of the design

MasteringDigitalDesign DepartmentofEEEwithVerilogonFPGAs ImperialCollegeLondon

V5.0-PYKCheung,9Oct2017 Part1-4

BlockDiagramoftheDE1-SoCBoard

Experiment1:SchematiccaptureusingQuartus–7-SegmentDisplay

Ifyouhavecometothelaboratorysessionprepared,PartIofexperimentVERIshouldtakenomorethanONE3-hoursession.Itwillleadyouthroughtheentiredesignofa7-segmentdecoderusingschematicentrymethod.Itwillusefourslideswitchesontheright(SW3toSW0)ontheDE1boardasinput,anddisplaythe4-bitbinarynumberasahexadecimaldigitontheright-most7-segmentdisplay(HEX0).

Page 5: Laboratory Experiment – Mastering Digital Design · Quartus provides a complete environment for you to implement your design on an Altera FPGA. It supports all aspects of the design

MasteringDigitalDesign DepartmentofEEEwithVerilogonFPGAs ImperialCollegeLondon

V5.0-PYKCheung,9Oct2017 Part1-5

Step1:Creatingagooddirectorystructure

Before you start carrying out any design for thisexercise,itwouldbeveryhelpfulifyoufirstcreateinyour home directory a directory structure on theh:\driveforthisexperiment.Shownontheright isapossible directory structure that youmay choose tocreate. Each folder is empty for now, but as youprogress through the four Lab Sessions, you will becreatingeachdesignineachofthefolders.

Step2:SeewhatyouareaimingforGototheExperimentwebpage(seeabove)anddownloadacopyofthesolutionforExercise1:“ex1sol.sof”toyourhomedirectory (orwherever that is). Now turnON theDE1board.

Step3:ProgrammetheFPGA

Start up Quartus software on your computer. Clickcommand:Tools > Programmer. In the popupwindow,click:HardwareSetup…. Youshouldseesomething likethe diagram on the right. Then select:DE-SOC [USB-1].ThisistotellQuartussoftwarethatyouareusingtheDE1-SoCUSBinterfacetoprogram(orblast)theFPGA.ThenclickAutoDetectbuttonontheleft.AwindowwillpopupandyouneedtoselectSCSEMA5radiobuttontotellthesystemwhichtypeofCycloneVFPGAchipyouareusing(whichis5CSEMA5).

Youwillnowsee two lines in theProgrammerwindowas shownon theright.Sinceweareonlyconfiguring(i.e.sendingabit-streamto)theFPGApart of the CycloneV chip,we need todelete the SOCVHPS (stands forSystem-on-ChipVHighPerformanceSystem,whichistheARMprocessor)fromtheprogrammersetup.

Next click the AddFile button. Navigate to the folder containing theex1sol.soffile.Selectthis.FinallyclicktheStartbutton.

The ex1sol.sof file contains the solution to Exercise 1designed by me. It has the bit-stream to configure (orprogramme)theFPGApartofCycloneV.Oncethebit-streamissuccessfullysenttotheFPGAchip,thisdesignwilltakeoverthe function of the chip. You should be able to change theleast significant four switches and see a hexadecimal number displayed on rightmost 7-segmentdisplay.

You should leave the programmer utility running in the background for ease of sendinganotherdesigntotheFPGAlater.ReturntoQuartussoftwarebyclickingitswindow.

Step4:PaperDesign

Theoverallblockdiagramforthedecoder isshownbelow. Thedecoderoutputsout[6..0]drive the seven segments on the display. Note that the LED segments are low active,meaningthattheLEDwilllightup(ON)ifthecorrespondingdigitalsignalisat0V.

Page 6: Laboratory Experiment – Mastering Digital Design · Quartus provides a complete environment for you to implement your design on an Altera FPGA. It supports all aspects of the design

MasteringDigitalDesign DepartmentofEEEwithVerilogonFPGAs ImperialCollegeLondon

V5.0-PYKCheung,9Oct2017 Part1-6

Thetruth-tableforthedecoderisshownhere:

Withwhatyouhave learned inthefirstyear,you should be able to design the decoder inthe form of seven Boolean equations, andthen use K-map to minimise the logic. Inorder to save time, only derive the Booleanequation for out[4] as a Boolean function ofin[3..0].

YoualsoshouldnotuseK-maptoperformanyoptimization. Quartus (andothermodernCADdesignsoftware)willperformlogicminimizationforyouandwilldoamuchbetterjob,takingintoaccountthearchitectureoftheFPGAchip.

Step5:Createtheproject“ex1”

• Createinyourhomedirectorythefolder../part_1/ex1.

• Clickfile>NewProjectWizard,completetheform.Useex1astheprojectnameandex1_topastop-designname.

• SelecttheFPGAdeviceasCycloneV5CSEMA5F31C6.ThenclickFinish.

Step6:Specifythe7-segmentdecoderasschematic

• Download from the website the file:My7Seg_incomplete.bdf.zip and unzip in thefolder ../part_1/ex1. This is a partially completedschematic for the 7-segment decoder circuit withcircuitforout[4]missing.Youarenowreadytoenterthe circuit to produce out[4] as gates using theschematic editor. This is shown on the right and itimplementstheequation:

out4=/in3*in0+/in3*in2*/in1+/in2*/in1*in0

TheGraphicEditorprovidesanumberoflibrarieswhichincludecircuitelementsthatcanbeimportedintoaschematic.Double-clickontheblankspaceintheGraphicEditorwindow,or

clickon the icon in the toolbar that looks likeanANDgate.Apop-upboxwillappear.ExpandthehierarchyintheLibrariesboxasshowninthefigure.Firstexpandlibraries,thenexpand the libraryprimitives, followedbyexpanding the library logicwhichcomprises thelogic gates. Select “and2”, which is a two-input AND gate, and click OK. Now, the ANDsymbolwillappear in theGraphicEditorwindow.Using themouse,movethesymbol toadesirablelocationandclicktoplaceitthere.

• Repeat andplace two “and3” andone “or3” gateson the schematic. Change thenamesofalltheinputandoutputnodesaccordingly.(Itisquickesttoputdownallthegatesfirstbeforewiringthemuplater.)

• Nowwireupthegatesbyclickanddragontheinputnodesofthegatestoextendawireout,andthensimplytypethenameofthenodeonthekeyboard.

• Whencompleted,youwillseetheentireschematicdiagramforthedecodercircuitasshownhere:

Page 7: Laboratory Experiment – Mastering Digital Design · Quartus provides a complete environment for you to implement your design on an Altera FPGA. It supports all aspects of the design

MasteringDigitalDesign DepartmentofEEEwithVerilogonFPGAs ImperialCollegeLondon

V5.0-PYKCheung,9Oct2017 Part1-7

Step7:Includethisfileinproject

Everytimeyoucreateanewentityormoduleaspartofyourdesign,youmustincludethefileintheproject.

• Click:Project>AddCurrentFilestoProject….,

Step7:Makeasymbolforthedecoder

It is often convenient to encapsulate a circuit into a module (sometimes known as an“entity”),whichisthenusedmultipletimesinadesign.Forustodoso,weneedtocreateasymbolforMy7segdecodermodule.

ClickFile>Creat/Update>CreateSymbol…

Step8:Usethismoduleatthetop-leveldesignschematic

• NowwewillusethenewlycreatedentityMy7seginthetop-leveldesign.• ClickFile>New….andselectBlockDiagram/SchematicFileasshownhere:

Page 8: Laboratory Experiment – Mastering Digital Design · Quartus provides a complete environment for you to implement your design on an Altera FPGA. It supports all aspects of the design

MasteringDigitalDesign DepartmentofEEEwithVerilogonFPGAs ImperialCollegeLondon

V5.0-PYKCheung,9Oct2017 Part1-8

• Use the button to select and place the My7seg module, input port andoutputportontheschematic.

• Double click the port symbol to edit the input and output pin names asSW[3..0]andHEX0[6..0]respectively.

• Usethebuswiring tool towireup theports to themoduleas twobussesasshownbelow.

• Savethisfile.

Step9:Pinassignment&Compilation

YouneedtoassociateyourdesignwiththephysicalpinsoftheCycloneVFPGAontheDE1-SOCboard.

• Check that the device is corrected assigned as5CSEMA5F31C6using:Assignments>Device…

• Click:Processing>Start>StartAnalysisandElaboration.Thiswillwork out the input/output port names for yourdesign. This should completewithouterror. Otherwise,fixallerrorsandre-analyse.(Therewillbemanywarnings–generallywarningsarenot important.But thereMUSTnotbeerrors,whichwillbeshowninRED.)

• ClickAssignment>PinPlannerandanewwindowwiththe chip package diagram. You should also see the top-levelinput/outputportsshownasalist.

Page 9: Laboratory Experiment – Mastering Digital Design · Quartus provides a complete environment for you to implement your design on an Altera FPGA. It supports all aspects of the design

MasteringDigitalDesign DepartmentofEEEwithVerilogonFPGAs ImperialCollegeLondon

V5.0-PYKCheung,9Oct2017 Part1-9

• Clickontheappropriatepinsonebyone,andselectthecorrespondinglocationfromadropdownlistaccordingtothelistshowninthepinassignmenttableabove.TheI/Ostandard(i.e.interfacevoltages)shouldbe“3.3VLVTTL”.

• Click:Processing>StartCompilation,tobuildtheentiredesign,andtogenerateallthenecessaryfiles.ThereshouldbeNOerror,buttherewillbemanywarnings.

Step10:ProgramtheFPGAontheDE1Board

• Youhavenowcreatedinthe../part_1/ex1/output_files/folderthefileex1_top.sof,whichcontainyourdesign.(ThisshouldbethesamedesignastheoneIgaveyoutotryoutinStep2ofthisexercise.)

• ProgramtheDE1boardwithyourversionofex1_top.sofandtestthatitisworkingproperly.

Step11:PropagationDelayfrominputstooutputs

• Click:Tools > TimeQuest TimingAnalyzer to invoke thebuilt in timinganalyzerofQuartus.AnewTimeQuestwindowwillappear.

• Click:Netlist>CreateTimingNetlist.Thenselectpost-fitandslow-corner,thenOK.• Inthe“SetOperatingConditions”window,select“Slow1100mV0°Cmodel”.• Now click: Netlist > Update Timing Netlist … This will use the specified timing

modelandconditiontoproduceasetoftimingdata.• Click:Report>Datasheet>ReportDatasheet.Thiswillproduceatableshowingthe

input-to-outputpropagationdelayforvariouscombinationofriseandfalltimes(RR,RF,FRandFF).Makesurethatyouunderstandingwhatthistablemeans.

Page 10: Laboratory Experiment – Mastering Digital Design · Quartus provides a complete environment for you to implement your design on an Altera FPGA. It supports all aspects of the design

MasteringDigitalDesign DepartmentofEEEwithVerilogonFPGAs ImperialCollegeLondon

V5.0-PYKCheung,9Oct2017 Part1-10

• Repeat the procedcure again but for “Slow 1100mV85°CModel”.What is thedelaydifferenceat thesetwotemperatureextremes?Why?

Step12:Examinetheresourcesused

• Now examine the Compilation Report. You shouldseesomethingasshownhere.

• It shows that this design used only 4 out of 32,070ALMs(AdaptiveLogicModules),11ofthe457I/Opinsandnoneoftheotherresources.

Congratulations!YouhavenowcompletedyourfirstFPGAdesign!

Experiment2:7-SegmentdecoderinVerilogHDL

I hope you now appreciate how limiting and slow it is to enter a design as a schematicdiagram.ModerndigitaldesignersDONOTUSEschematicasamethodofentryanymore.Instead a designer would either use Verilog or VHDL hardware description language, orsome high level language such as OpenCL or Vivaldo HLS to specify the design. In thisexperiment, you will design the Verilog version of what you have done in Experiment 1.Hopefullythiswillconvinceyounevertouseschematiccapturefordigitaldesignagain!§

Step1:hex_to_7seg.v

• Create a new project ex2 as before and a top-levelmoduleex2_topasbeforeinex2folder.

• In Quartus, create a design file in Verilog HDLknownashex_to_7seg.vusing:

File > New …. and select Verilog HDLfromthelist.

• Type the Verilog source file as shown below.(You should have seen this during one of theLectures earlier). Make sure you pay attentiontothesyntaxofVerilog.Saveyourfile.

• A full compilation can take a long time. A farmore efficient way to check the syntax of yourcodebyclicking:Process>Analyzecurrentfile.You should get into ahabit ofALWAYSperformthis step to make sure that the new Verilogmodule you have created is as error free as

possible.Itwillsaveyoualotoftime.

Step2:CreateTop-LevelSpecificationinVerilog

• Instead of using schematic capture for the top-level module (that connects to physical pins onthe FPGA), we will do this also in Verilog bycreatingthefile:“ex2_top.v”asshownhere.SetthisasTop-Levelentity.

• Click: Project > Add/Remove Files, and removethe.bdffileaspartofthisproject.

Page 11: Laboratory Experiment – Mastering Digital Design · Quartus provides a complete environment for you to implement your design on an Altera FPGA. It supports all aspects of the design

MasteringDigitalDesign DepartmentofEEEwithVerilogonFPGAs ImperialCollegeLondon

V5.0-PYKCheung,9Oct2017 Part1-11

• Thisallowsyoutoremovethe.bdffileandreplaceitwiththe.vfileforthetop-levelspecification.

• Verify that everything works properly with: Process > Start > Start analysis &elaboration.Make sure that there is no error. (Warnings often capture potentialerrors. However, theQuartus system generatesmanywarnings, and nearly all ofwhicharenot important. Onceyouhavegainconfidenceonthesystem,youmaystartignoringthewarning,butneverignoreanyerror.)

YouwillsavealotoftimeifyouALWAYSusethesetwosteps:analyze,andanalysis&elaboration,andensurethatALLerrorsaredealtwith(andwarningunderstood).

Step3:PinAssignment–thequickway

• Earlieryouusedthepinassignmenteditortoassociatepinsonthepackagetoyoursignals.Thisisatediousprocess.Inex1,ifyouhavecorrectlycompletedthedesign,thepinassignmentwouldhavebeenstoredinafile:“ex1_top.qsf”file.

• Openthis file,eitherusingQuartus’built-ineditorbyclicking:File>Open file…oruseyourownfavouriteeditonyourPC.

• Youwillfindlinesofstatementsuchas:

• ThefirstlinedefinesthevoltagestandardusedbytheHEX0[4]signal(3.3Vlogic).• ThesecondlinedefinesthephysicalpinlocationofHEX0[4]isPIN_AF28.• Nowopentheex2_top.qsffile.Youwillseethatthereisnopinassignmentforthis

designyet.Beforefullcompilation,weneedtotellQuartuswhichsignalisconnecttowhichphysicalpinontheFPGA.

• Instead of using the tedious pin assignment editor in ex1, we will modify theex2_top.qsffilewithourtexteditortoincludethepinassignmentinformation.Todothis,firstdownloadfromtheexperimentwebpagethefile:pin_assignment.txttotheVERIdirectory.

• Thenuse:Edit>InsertFile…inQuartustoinsertthewholeofpin_assignment.txtinex2_top.qsf.

• Notethatweonlyuse7pins inex2_top.v,butpin_assignment.txtdefinesallpinsusedbythefourpartsofExperimentVERI. Quartuswillgenerate lotsofwarningswhichyoumayignoreabouttheseunusedpinsnotbeingdriven. Itwillnotcreateanyerrorandthepinassignmentsforunusedpinswillbeignored.

Step5:Testyourdesign

• Recompileyourdesign.• Go to the Programmer window (assuming that you still have it opened). Delete

the.soffileentryandaddthecurrent.soffile.• Testyourdesignontheboard.

Step6:Putmoduleinmylib

OverthefourweeksintheLab,youwilldesignandverifyvariousVerilogmoduleswhichyouwill reuse. Youshouldcopy these to the“mylib” folderand includethem inyournewdesignasnecessary.

Note:Whenyouperformacompilation,theremaybeapopupwindowinformingyouthatsome“Chain_x.cdf”filehasbeenmodified,andaskifyouwishtosaveit.JustclickNO.

Page 12: Laboratory Experiment – Mastering Digital Design · Quartus provides a complete environment for you to implement your design on an Altera FPGA. It supports all aspects of the design

MasteringDigitalDesign DepartmentofEEEwithVerilogonFPGAs ImperialCollegeLondon

V5.0-PYKCheung,9Oct2017 Part1-12

Experiment 3: Test yourself - 10-bit binary switch values on three 7-segmentdisplays

Here is a “test yourself” exercise. Create your own design to display all 10-bit slidingswitchesashexadecimalonthreeofthe7-segmentLEDdisplays.

Checkpoint:Youshouldgettothispointbytheendofthe3-hourLabSessionorearlier.

Experiment4:Displaying10-bitbinaryasBCDdigitsonthe7-segmentdisplays

Inoneofthelectures,youhavebeentaughthowtoconvertbinarynumberstobinary-code-decimal digits using the “shift and add 3” algorithm. You have been shown how toimplementan8-bitbinarytoBCDconverterusingVerilog.Furthermoreinproblemsheet1,youhavebeenaskedtoextendthistoa10-bitconverter(bin2bcd_10.v).

Forthisoptionalexercise,youarerequiredtodisplaythe10-bitbinarynumberasspecifiedbythe10slidingswitchesSW[9:0]asadecimalnumberusingyour10-bitconvertermoduleandthe7-segmentdecoder.Recordtheresourceusageofyourdesign.

• Now download from the experiment website a 16-bit binary to BCD convertermoduleprovided(bin2bcd_16.v),andreplaceyour10-bitconverterwiththisone.

• Wheninstantiatingthe16-bitconverter,butonlyusing10ofthe16bits,youshouldspecifytheinputportsas:{6’b0,SW[9:0]}.(Rememberthatthe{…}operatorisforbit-concatenation.)

• TestyourdesignontheDE1Board.• Comparetheresourceusagebythisdesign(withbin2bcd_16.v)withthatusingthe

10-bitversion (bin2bcd_10.v). Youwill find that in fact thenumberofALMsusedwillbethesame.

• BasicallyQuartusoptimizer removesunused resources. Themodulebin2bcd_16.vhas sixof its input connected to0, andonly12of itsoutput connected tooutputpins.TheCADsoftwarewilleliminatealltheredundantlogic.ThisshouldresultinthesamenumberofALMbeingusedasthatwitha10-bitconverter.Inotherwords,for such combinational circuit, you only need to keep the 16-bit version for anynumberswith16bitsorlower.

BeforeyoumoveontoPart IIoftheexperiment,youshouldcopythecomponents(modules)youhavedesignedtothe“mylib”folder.Inthefollowing sessions, you will be using the various .v files from thisrepositoryofyourowndesign.Youwillalsobeaddingtoitlater.

Page 13: Laboratory Experiment – Mastering Digital Design · Quartus provides a complete environment for you to implement your design on an Altera FPGA. It supports all aspects of the design

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 14: Laboratory Experiment – Mastering Digital Design · Quartus provides a complete environment for you to implement your design on an Altera FPGA. It supports all aspects of the design

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 15: Laboratory Experiment – Mastering Digital Design · Quartus provides a complete environment for you to implement your design on an Altera FPGA. It supports all aspects of the design

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 16: Laboratory Experiment – Mastering Digital Design · Quartus provides a complete environment for you to implement your design on an Altera FPGA. It supports all aspects of the design

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 17: Laboratory Experiment – Mastering Digital Design · Quartus provides a complete environment for you to implement your design on an Altera FPGA. It supports all aspects of the design

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 18: Laboratory Experiment – Mastering Digital Design · Quartus provides a complete environment for you to implement your design on an Altera FPGA. It supports all aspects of the design

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 19: Laboratory Experiment – Mastering Digital Design · Quartus provides a complete environment for you to implement your design on an Altera FPGA. It supports all aspects of the design

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 20: Laboratory Experiment – Mastering Digital Design · Quartus provides a complete environment for you to implement your design on an Altera FPGA. It supports all aspects of the design

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.

Page 21: Laboratory Experiment – Mastering Digital Design · Quartus provides a complete environment for you to implement your design on an Altera FPGA. It supports all aspects of the design

MasteringDigitalDesign DepartmentofEEEwithVerilogonFPGAs ImperialCollegeLondon

v5.0-PYKCheung,9Oct2017 Part3- 1

MScCourseonAnalogueandDigitalICDesign

LaboratoryExperiment–MasteringDigitalDesign(PartIII)

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

PART3–AnalogueI/OandSPIserialInterface

1.0 TheAdd-onCard

Thispartoftheexperimentintroducesyoutotheadd-oncardtotheDE1board.Theadd-oncard consists of a 10-bit ADC and a 10-bit DAC, a quad op-amp, sockets for earphone(analogue output) and sound source (analogue input), and a potentiometer. The overallblockdiagramoftheadd-oncard isshownbelow. Itshouldbeplugged intotheexpansionsocket furthestaway fromtheedgeof theDE1board. Bewareof thealignmentbetweentheplugandthesocket.Iftheadd-onboardisinsertedcorrectly,thegreenLEDwilllightupwhentheDE1boardisturnedON.

Youdonotneedtounderstandall thecircuitryonthisboard indetails. Nevertheless, theschematicdiagramandadetailexplanationonhowthisboardworks,togetherwithallthedatasheetsofthecomponentsused,areprovidedontheExperimentwebpage.

Forthispartoftheexperiment,youwouldneedtobringyourpersonalearphone,andfromtheLab,geta3.5mmleadandadigitalvoltmeter.

Bytheendofthispartoftheexperiment,youwillhave:

• UnderstoodandverifiedtheoperationoftheSerial-to-ParallelInterface(SPI)ofthedigital-to-analogueconverter(DAC)MCP4911usingModelsim;

• TestedtheDACandmeasureditsoutputvoltagerange;• Learned how to use a ROM (read-only memory) and a constant coefficient

multiplier;• Usetheanalogue-to-digitalconverter(ADC)MCP3002toconvertdcvoltages;• (Finally), designed a sinewave tone generator with variable frequency which is

controlled with the slide switches, and the frequency value showed on the7-segmentdisplaysindecimalformat.

Page 22: Laboratory Experiment – Mastering Digital Design · Quartus provides a complete environment for you to implement your design on an Altera FPGA. It supports all aspects of the design

MasteringDigitalDesign DepartmentofEEEwithVerilogonFPGAs ImperialCollegeLondon

v5.0-PYKCheung,9Oct2017 Part3- 2

2.0 Experiment10:InterfacewiththeMCP4911Digital-to-AnalogueConverter

Step 1: Understanding Datasheet - Go to the Experiment website and download thedatasheet for the MCP4911 DAC and the file spi2dac.v, which is a Verilog module thatimplements the SPI interface circuit to communicate with the DAC. Make sure that youunderstandfromreadingthedatasheet:

• thepurposeofeachpinontheDAC(Section3.0,page17ofdatasheet);• howinformationissenttotheDACthroughtheserialdata input(SDI)pin(Section

5.0,page23-24);• howtoconfiguretheDAC’sinternalfunction(page25);• DAC’stimingspecificationsandtimingdiagram(pages4and7).

ThereisnoneedforyoutoknowhowexactlytheDACworksinternally.However,youneedtohavesufficientappreciationoftheserialinterfacetoconductthispartoftheexperiment.Furthermore,don’tworry ifyoudon’t fullyunderstandtheVerilogcode inspi2dac.v. ThiswillbeexplainedintheLabeitherbeforeorafterthepracticalsession..

Step2: Timingdiagram–Thespi2dacmoduletakesa10-bitnumber in parallel (controlled through the load signalwhichmustbehigh for at least 20ns) and generates thenecessaryserial signals to drive the MCP4911 DAC. Based on theinformation from the Datasheet, draw in your logbook theexpected timing diagramof the SPI interface signalswhen aword10’h23bissenttotheDAC.

Step3:Verifytimingofspi2dac.vusingModelsim–Thestepsare:

1. Createaprojectex10andatop-levelmoduleex10_top.v2. Copytothedirectoryex10thefilespi2dac.vdownloadedfromthewebpage3. Makethisfiletop-levelmodule(fornow)4. Click:…>Process>Start>AnalyzeandSynthesise5. StartModelsim(Tools>RunSimulationTools>RTLSimulation)6. Designado-fileasatestbenchtoexercisetheinputsignalscorrectly7. Runthedo-fileandmatchthewaveformgeneratedwithyourprediction

Step4:TestingtheDAConDE1

Inorder to test thespi2dac.vmoduleandverify thatDACworksproperly, create the top-leveldesignex10_top.vthatimplementsthecircuitshowninthefollowingdiagram.

Thedata_invaluedeterminedbythe10switches(SW[9:0])isloadedtothespi2dacmoduleatarateof10ksamplespersecondasgovernedbytheloadsignal.Thestepsforthispartare:

Page 23: Laboratory Experiment – Mastering Digital Design · Quartus provides a complete environment for you to implement your design on an Altera FPGA. It supports all aspects of the design

MasteringDigitalDesign DepartmentofEEEwithVerilogonFPGAs ImperialCollegeLondon

v5.0-PYKCheung,9Oct2017 Part3- 3

1. Downloadfromtheexperimentwebsitethefilespi2dac.v.2. Checkthattheclktick_16.vmodulethatyouusedlastweekisinthe“mylib”folder.3. Createatop-levelmoduleex10_top.vtoconnectallmodulestogetherasshownin

thediagram.4. Click:Project>Add/RemoveFilesinProject…,andselectalltherelevantfilesused

here. This step is important– it allowsyou to selectwhichmodules to include inyourdesign.

5. Whenex1__top.visthecurrentfile,click:Project>SetasTop-LevelEntity.Thisisanotherusefulstep,whichdefinesthetopmodule,andallthosemodulesbelowthisone, for compilation. With steps 4 and 5, you canmove up or down the designhierarchyinaprojectforcompilation.

6. Edittheex10_top.qsffiletoincludepin_assignment.txt.7. Compileandcorrecterrorsasnecessary.

Oncethedesign iscompiledwithouterror,downloadthebit-streamfiletotheDE1board.Using theDVM,measure theDACoutputvoltageatTP9 forSW[9:0]=0and10’h3ff. (ThevoltagerangeoftheDACoutputshouldbefrom0Vto3.3V.)

Step5:Verifythesignalsonanoscilloscope

ConfirmthatthesignalsproducedbytheFPGAwiththespi2dac.vmoduleagreewiththosefromModelsim. Set SW[9:0] to 10’h23b andmeasureDAC_SCK (TP3) andDAC_SDI (TP1)usinganoscilloscope.YoumayneedtotriggerthescopeexternallywiththeDAC_CSsignal(TP2).ComparethewaveformstothosepredictedbyModelsim. (Therearetwoscopes inthe909LabforyoutoborrowforthispartoftheLab.)

3.0 Experiment11:D-to-Aconversionusingpulse-widthmodulation

Instead of using a DAC chip (and SPI serial interface to communicate with the chip), analternativemethod toproducean analogueoutput fromadigital number is tousepulse-widthmodulation(PWM). TheVerilogcodeforapwm.vmodule isgiventoyou inoneofmylecturesdeliveredearlierintheLab..

Createadesignex11_top.vaccordingtothecircuitshownbelow.UsethescopetoexaminethesignalsatTP5andTP8.ComparetheoutputvoltagerangesatTP8andTP9.

Page 24: Laboratory Experiment – Mastering Digital Design · Quartus provides a complete environment for you to implement your design on an Altera FPGA. It supports all aspects of the design

MasteringDigitalDesign DepartmentofEEEwithVerilogonFPGAs ImperialCollegeLondon

v5.0-PYKCheung,9Oct2017 Part3- 4

4.0 Experiment12:DesigningandtestingasinewavetableinROM

Thispartoftheexperimentleadsyouthroughthedesignofa1Kx10bitROM,whichstoresatableofsinevaluessuitabletodriveourDAC.TherelationshipbetweenthecontentoftheROMD[9:0]anditsaddressA[9:0]is:

D[9:0]=int(511*sin(A[9:0]*2*pi/1024)+512) for1023≥A[9:0]≥0

Since theDAC accepts an input range of 0 to 1023,wemust add an offset of 512 in thisequation.(Thisnumberrepresentationisknowasoff-setbinarycode.)

Before generating the ROM inQuartus using the “MemoryCompiler”tool,weneedto firstcreateatext filespecifyingthecontentsoftheROM.Thiscanbedoneindifferentways.IncludedontheExperimentwebpageare:1)aPythonscriptto do this; 2) a Matlab script to do the same thing; 3) amemory initialization file rom_data.mif created by eithermethod.Downloadthesefilesandexaminethem.

ClickTools>IPCatalogtobringupatoolwhichhelpstocreatea1-PortROM.Acatalogwindowwillpopup.Selectfromthewindow>Library>BasicFunctions>OnchipMemory>ROM1-Port.Completetheon-screenformtocreateROM.v.

ToverifytheROM,createthedesignex12_top.v,thatusestheswitchesSW[9:0]to specify the address to the ROM, and display the contents stored at thespecifiedlocationonthefour7-segmentdisplay.Oncethisisdoneandloadedonto theDE1, verify that the contents stored in the ROMmatches those specified in therom_data.miffile.

5.0 Experiment13:Afixedfrequencysinewavegenerator

Let us now replace the slide switcheswith a 10-bit binary counter and connect the ROMdata output to spi2dac andpwmmodules as shown in the figure below. Since the ROMcontainsonecycleof sinewaveandtheaddress to theROMis incrementedeverycycleofthe10kHzclock,aperfectsinewaveisproducedattheleftandrightoutputsofthe3.5mmjacksocket.

ImplementthiscircuitandverifythatthesignalsproducedbyboththeDACandthePWMareasexpected.Whatisthefrequencyofthesinewave?

Page 25: Laboratory Experiment – Mastering Digital Design · Quartus provides a complete environment for you to implement your design on an Altera FPGA. It supports all aspects of the design

MasteringDigitalDesign DepartmentofEEEwithVerilogonFPGAs ImperialCollegeLondon

v5.0-PYKCheung,9Oct2017 Part3- 5

6.0 Experiment14:Avariablesinewavegenerator

Combine everything together to produce a designex14_top.v, which produces a variablefrequencysinewaveusingtable-lookupmethod.Thesamplingfrequencyis10kHz,andthesine value is read from the ROM that is preloadedwith one-cycle of a sinewave (i.e. theaddressoftheROMisthephaseandthecontentisthesinevalue).Oneverysampleperiod,advance the address (i.e. the phase) by an amount determined by SW[9:0]. Derive therelationshipbetweentheoutputsignalfrequencyandtheswitchsetting.

Theoverallblockdiagramisshownbelow.TheswitchsettingismultipliedbyaconstantktoconvertthephaseincrementSW[9:0]tofrequency.

You canproducea10-bit x 14-bit constant coefficientmultiplierusing the IP catalog tool.The14-bitconstantis14’h2710(whichis14’d10000).Theproductisa24-bitnumber,andthe frequency is the top 14-bits (Why?). The frequency can then be displayed on the 7-segmentdisplays.

Produce a 439Hz sinewave, which is close to 440Hz, the frequency commonly found intuning forks. Makesure that this is indeedcorrect (through listeningormeasuringwithafrequencycounter).

7. Experiment15(OptionalChallenge):UsingtheA-to-Dconverter

Inthisexperiment,youwilllearntouseA-to-DconverterMCP3002ontheadd-onboardtoconvert analogue voltages to digital signals. Again, download from the webpage thespi2adc.vmodule,whichisalreadywrittenforyoutouse.

Instead of using the slide switches to control the frequency, use the A-to-D converter toconvert the dc voltage of the potentiometer (which is between 0v and 3.3v) and use thisconvertervalueinstead.

Tohelpyouknowwhatyoushouldaimfor,thesolutionsforex14sol.sofandex15sol.sofareavailabletodownload.

Page 26: Laboratory Experiment – Mastering Digital Design · Quartus provides a complete environment for you to implement your design on an Altera FPGA. It supports all aspects of the design

MasteringDigitalDesign DepartmentofEEEwithVerilogonFPGAs ImperialCollegeLondon

v5.0-PYKCheung,9Oct2017 Part4- 1

LaboratoryExperiment–MasteringDigitalDesign(PartIV)

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

PART4–Real-timeAudioSignalProcessing

1.0 Puttingeverythingtogether

Inthispartoftheexperiment,youwilllearntocombinetheADCwiththeDAContheAdd-oncard,andusetheDE1toperformsomesimpleaudioprocessing.

The goal of the final week’s laboratory session is to implement a speech echo effectsynthesizer.Youneedtobringyourearphonetothelabtolistentotheaudiooutput.

2.0 Experiment16:Anaudioin-and-out(allpass)loop

Download from the Experiment webpage the file ex16_proto.zip, which contains theprototypefolderforthisexperiment.

• Examinethecontentswithinthisfolder.YoushouldfindthefollowingVerilogfiles:

Module Functionex16_top.v Top-leveldesign;interfacetopinsspi2dac.v SPIinterfacecircuittoDACfromPart3spi2adc.v SPIinterfacecircuittoADCpwm.v Pulse-widthmodulationDACfromPart3clktick_16.v Clockdividertogeneratesamplingclockticksat10kHzfromPart2Pulse_gen.v Generateaone-cyclepulseonrisingedgeofatriggersignal(new)hex_to_7seg.v Hexto7-segmentdecoderfromPart1allpass.v “processor”module–thisperformsprocessing,whichispassinginputto

outputfornow.

• Studyex16_top.v. This specifies a system as shown in thefollowingdiagram(thepartinsidetheCycloneV).Makesureyouunderstandhowthisworks.

• Note how the spi2adc.v module is used. ExplicitlyassociatingthesignalnamesINSIDEthemoduletoOUTSIDEallow connections to be defined independent of the order.This is a more verbose but is much safer way in makingconnectstomodules.

• The ADC has two analogue input channels: CH0 and CH1. They connected to thepotentiometerandtothe3.5mmsocketrespectively.WealwaysuseCH1forex16.

• Nowexaminethemoduleallpass.v.Thenameofthismoduleis“processor”andisdifferentfromthenameoftheVerilogfile.Thereisnoneedtousethesamenameexceptthatnormallyitismoreconvenienttodoso.However,inthiscase,wehavedeliberatelyusedthefilename“allpass”todescribeitsfunction,whileusingamoreuniversal name for themodule. You can choose “allpass.v” as the source of themodule “processor” now. Later, you can have a differentVerilog file to define adifferent “processor”. Which version of “processor” you use in your design isspecifiedinProject>Add/RemoveFileinProject.

Page 27: Laboratory Experiment – Mastering Digital Design · Quartus provides a complete environment for you to implement your design on an Altera FPGA. It supports all aspects of the design

MasteringDigitalDesign DepartmentofEEEwithVerilogonFPGAs ImperialCollegeLondon

v5.0-PYKCheung,9Oct2017 Part4- 2

• Make sure that you understand fully what the Verilog file “allpass.v” does. It

actuallydoesverylittle.It:

1. Corrects the ADC converter data (which uses offset binary with 0Vrepresented by a value of ~385), but subtracting the offset fromdata_out[9:0]toobtaina2’scomplementvaluex[9:0].

2. ConnectsXtoY,i.e.doesnothingandhence“allpass”.3. ConvertstheYvaluefrom2’scomplementtooffsetbinaryfortheDAC.The

offsetnowisat512asshownbelow.

• BuildyourdesignfortestingontheDE1Board.Todothis,youshould:1. Open each .v file, and use Processing >

Analyze Current File on each of theVerilog file to ensure that there is notsyntaxerror.

2. UseProject>Add/RemoveFileinProjectto includeall the .v filesyouneed. Herewe select allpass.v to supply the“processor” module. In the future, youcould substitute allpass.v with anotherfileforadifferentprocessor.

3. Whileex16_top.visthecurrentfileintheeditorwindow,useProject>SetasTop-level Entity todefine top is the top-levelmodule.

4. Use Project > Start > Analysis and Synthesize … to check for errors andwarningswithoutcompilingeverything.

Page 28: Laboratory Experiment – Mastering Digital Design · Quartus provides a complete environment for you to implement your design on an Altera FPGA. It supports all aspects of the design

MasteringDigitalDesign DepartmentofEEEwithVerilogonFPGAs ImperialCollegeLondon

v5.0-PYKCheung,9Oct2017 Part4- 3

5. CheckthatDevice,PinandTimeQuestclockperiodareallassignedcorrectly.6. Compile thewholedesignanddownload thebit-stream file “ex16_top.sof” to

DE1.7. Test that it is working properly. You can use the PC to play some music or

speechfiles(downloadablefromExperimentwebpage),anduseanearphonetolistentotheDACoutput. Whennosignal issenttotheDE1board,thedisplayshouldshowahexvalueof181to188.

Whenyougettothispart,theexperimentframeworkisshowntobeworking.Ittakesaudiosamples at 10kHz from the ADC, passes it through a processor module and output theprocessedsampletotheDAC.

Testyourself

NowcreateanewVerilogfilemult4.vwhichisaprocessormodule(i.e.modulenameisstill“processor”),thatamplifiestheinputbyafactoroffour. Testthatthis isworking(i.e.thesignaltotheearphoneshouldbelouderordistorted).

3.0 Experiment17:EchoSynthesizerwithfixeddelay

In thispartof theexperiment,youwilldesign, implementandtestacircuit thatsimulatesthe effect of simple echo. Thediagrambelow shows two components of a sound sourcereachingitslistener:thedirectpathsignalx(t)andtheechosignalbx(t-T)whichisaweakerversion of x(t) attenuated by a factor b, bounced off the floor. The echo signal is alsodelayedbyTrelativetothedirect-pathsignalx(t).

Suchsimpleechocanbe implementedassignal flowgraphasshownbelow. This involvesthree components: a delay block that delays x(t) by K sample periods; a gain blockwhichmultipliesthedelayedsignalbythefactorb;andtheadder.

Thedelayblockcanbe implementedwitha first-in-first-out (FIFO)buffer. AFIFOisfoundinallformsofdigitalsystems.Theruleissimple:receivingdataarestoredinsequenceinsuchawaythattheycanberetrievedintheorderthat theyarrive.Whenanewdata itemarrivesand theFIFO isnot full, it iswrittentotheFIFO.Asastoreddataitemisretrieved,itisremovedfromtheFIFO.Thisallowsthesendandretrieveratestobedifferentintheshortterm.Ifthesendrateishigherthanretrieverate,eventuallythebufferwillgetfull.Ifthebufferisfull,itshouldnotreceiveanymoredata(otherwiseexistingstoredatawouldbecorrupted).A“full” statussignal isasserted to tell thesendernotsendanymoredata.

Page 29: Laboratory Experiment – Mastering Digital Design · Quartus provides a complete environment for you to implement your design on an Altera FPGA. It supports all aspects of the design

MasteringDigitalDesign DepartmentofEEEwithVerilogonFPGAs ImperialCollegeLondon

v5.0-PYKCheung,9Oct2017 Part4- 4

Similarly,ifthebufferisempty,itcannotprovideanydataforretrieval.An“empty”statussignalisusedtoindicatethattheFIFOhasnomoredatatoprovide.CreateanewprojectusingthefilesfromExperiment16asyourprototype.WithIPCatalogtool, generate a FIFO component of size 8192 x 10-bit as shown here. You only need toprovideonlythe“full”statussignal.ThisFIFOisusedtostorethemostrecent8192samples,henceprovidingadelayof0.8192msecsincethesamplingfrequency is10KHz. Beforetheechosimulationcircuitstartstoprovidetheecho,theFIFOmustfirstbefilled(i.e.waituntilthe“full”signal isasserted). Thereafter,thewritingoftheADCsampleandDACsampleissynchronous,andtheFIFOremains full.Thereaddata isalwaysthewritedatadelayedby8192sampleperiod.

Theattenuationfactorbshouldbe½or¼,whichcaneasilybeimplementedwithasimplybinaryshift.

Deliverable

Implement the simple echo simulator and test that it works. For the purpose of test,downloadthreedifferentsoundfiles:clapping.mp3,hello.mp3andhitchhiker.mp3,andplaythemonthePCorphone ina loop. Useyourearphoneto listentotheeffectoftheechosynthesizer.

4.0 Experiment18:Multipleechoes

The design in Experiment 17 produces a single echo. The signal flow graph only hasfeedforwardpaths.Multipleechoescanbeproducewithaslightmodificationofthesignalflowgraphtotheoneshownbelow.

The delay block now stores theoutput sample y(t) instead of theinput sample x(t). The attenuatedanddelayedy(t)isSUBTRACTEDfromx(t)toproducethenextoutput.(Whymust this be a subtract and not anadd?)

Provide a design to implement thisarchitectureandtestit.

Page 30: Laboratory Experiment – Mastering Digital Design · Quartus provides a complete environment for you to implement your design on an Altera FPGA. It supports all aspects of the design

MasteringDigitalDesign DepartmentofEEEwithVerilogonFPGAs ImperialCollegeLondon

v5.0-PYKCheung,9Oct2017 Part4- 5

5.0 Experiment19:EchoSynthesizerwithVariabledelay

Inthisexperiment,youwilldesign,implementandtestasystemwithvariabledelay.Abit-stream (echo.sof) that implements a solution can be downloaded from the Experimentwebpage.YoualsoneedtodownloadthethreeMP3testfiles.Connecttheaudioinputtothe speaker of thePC andplay the audio files in a loop. ProgramDE1with echo.sof andlistento theoutputwithyourearphone.Changethedelayof theechowithSW[8:0]. Theamountofdelayinmillisecondisdisplayedonthe7-segmentdisplaysasadecimalnumber.Thedesignofthisexperimentisshownintheblockdiagrambelow.Itconsistsofanumberofmodules:

• RAMDelayBock - Inplaceof theFIFO to implement thedelayblock, itusesa2-portRAMblock(8192x9-bit)–onewriteport(tostoretheADCsamples)andonereadport.

• AddressGenerator-A13-bitcounterisusedtogeneratethereadaddresstotheRAM.(Why13-bits?)Thecountervalueisincrementedonthenegativeedgeofthedata_validsignal at a frequency of 10KHz. In this way, the address generator computes theaddressusedonthenextreadandwritecycle.ThewriteaddressisgeneratedfromthereadaddressbyaddingthevaluetakenfromSW[8:0].Sincetheaddressis13-bitswide,the9-bitdelayvalue is zero-padded in its lower4bits. Therefore, thedelaybetweenthereadandwritesamplesis:SW[8:0]x16x0.1msec.

• Thereadandwriteenablesignalsarecommon,anditisgeneratedfromthedata_validsignalwiththepulse_genmodule.

• The write data value y[9:1] is 9-bit instead of 10-bit wide. This is because theembeddedmemory in theCyclone III FPGA is configurableas9-bit indatawidth,butnot10-bit. Thereforetheoutputdatavalueistruncatedto9-bitbeforestoringinthedelayblock.

• The read data value is of course also 9-bit wide. Therefore the x0.5 can easily beimplementedbysign-extendingthe9-bitvalueto10-bit:{q[8],q[8:0]}.

• Theimplementationofthefeedbacklooptogeneratetheechoeffectisidenticaltothatfromthepreviousexperiment.

• To display the delay value inmilliseconds, the value of SW[8:0] is firstmultiplied by1638(why)withaconstantmultiplier.Thisgivesa20-bitproduct,themostsignificant10-bitsofwhichisthedelayinmilliseconds.(Why?)ThisisthenconvertedfrombinarytoBCDanddecodedfordisplayonthe7-segmentdisplays.

Page 31: Laboratory Experiment – Mastering Digital Design · Quartus provides a complete environment for you to implement your design on an Altera FPGA. It supports all aspects of the design

MasteringDigitalDesign DepartmentofEEEwithVerilogonFPGAs ImperialCollegeLondon

v5.0-PYKCheung,9Oct2017 Part4- 6

6.0 Experiment20:VoiceCorruptor(AGrandChallengeforthemoreable)

Thispartoftheexperimentisoutsidethescopeoftheexperiment.Itisdesignedtoprovideyou with an open problem so that you can explore designing digital systems andimplementingdigital circuitsusing theDE1and theadd-oncardat yourown leisure. Youneedtocheckoutasetofkitstotakehomefromstores. Forexample,youmightwanttotrythisoutovertheChristmasbreak.You are now equippedwith all the tools and knowledge to design a reasonably complexaudio processing system. The idea here is to design something that will take a humanspeechsignalandthen“corrupt” inawaythattheidentityofthespeaker ismaskedwhilethespeechremainsintelligible.

Oneway todo this is to change thepitchof the speaker (e.g.make it sounds likeDonaldDuck). There aremanyways to perform pitch change of speech. Onemethod,which islinked to the previous experiments, is to employ a technique based on cross fading (i.e.combining) of two separately delayed version of the speech signal. The technique isdepictedintheblockdiagrambelow.

The sound source is delayed through two separate blocks, providing KA and KB sampledelays,whichvarywithtime. ThedelayedsignalsarethenattenuatedbyGAandGB,andcombinedwiththeadder.Tominimizetheartifactsanddiscontinuitiesintheoutputsignalandtomaintainaconstantvolume, thegainvaluesGAandGBaredesignedtocross fadewitheachother–i.e.whenoneisrampingup(from0to1),theotherisrampingdown.Aplotofthefourparameters,KA,KB,GAandGB,vstimeisshownbelow.

Page 32: Laboratory Experiment – Mastering Digital Design · Quartus provides a complete environment for you to implement your design on an Altera FPGA. It supports all aspects of the design

MasteringDigitalDesign DepartmentofEEEwithVerilogonFPGAs ImperialCollegeLondon

v5.0-PYKCheung,9Oct2017 Part4- 7

Therearefourregions.1. RegionA(t1tot2)-OnlychannelAiscontributingtotheoutput.ThedelayKA

is gradually decreasing linearly from 25.5ms to 12.7ms (255 to 127 x 100µs).ThegainGAisconstantat1.

2. RegionAB(t2tot3)–BothchannelscontributetotheoutputwithAdecreasingand B increasing their respective contributions. The two channels are crossfadedbeforeGAdropsfrom1to0whileGBincreasesintheotherdirection.

3. RegionB(t3tot4)–ThisislikeRegionA,butthebehaviorappliestochannelBinsteadofchannelA.

4. RegionsBA(t4tot5)–LikeRegionAB,butthetwochannelsarereversed.

Thepattern repeats itself indefinitely. Note that the“don’t care”portionofKAandKB isbecauseduringthisperiod,thegainGAorGBiszero.

Hints:

• Initially, try the delay ramping gradient of 0.5, i.e. the delay is droppedby k overtime2*k.

• Youcanusea9-bitdowncountertodefineboththedelayKAandthefourregions.• Youcanderiveallothervalues:KB,GAandGB,fromthecountervalues.• You can design a four-state synchronous state machine to control the corruptor

circuit.• Instead of delay varying ramping high to 0, you can reverse the direction of the

ramping.Alternativeyoucandesignthedelaytovaryupandthendown.• Inadditiontopitchchanges,youmayexploreotheraudioeffects.