Sei sulla pagina 1di 5

MATLABtoFPGAusingHDLCoder(TM)

fromMathWorks:LorenShure11thApril2013
Theopinionsexpressedbythisbloggerandthoseprovidingcommentsaretheirsalone,thisdoesnotreflecttheopinionofAutomatedTraderoranyemployeethereof.AutomatedTraderisnotresponsibleforthe
accuracyofanyoftheinformationsuppliedbythisarticle.

It'smypleasuretointroduceguestbloggerKiranKintali.KiranistheproductdevelopmentleadforHDLCoderatMathWorks.Inthispost,Kiranintroducesanew
capabilityinHDLCoderthatgeneratessynthesizableVHDL/VerilogcodedirectlyfromMATLABandhighlightssomeofthekeyfeaturesofthisnewMATLABbased
workflow.

Contents
IntroductiontoHDLCodeGenerationfromMATLAB
MATLABtoHardwareWorkflow
ExampleMATLABAlgorithm
ExampleMATLABTestBench
HDLWorkflowAdvisor
DesignSpaceExplorationandOptimizationOptions
BestPractices
Conclusion

IntroductiontoHDLCodeGenerationfromMATLAB
IfyouareusingMATLABtomodeldigitalsignalprocessing(DSP)orvideoandimageprocessingalgorithmsthateventuallyendupinFPGAsorASICs,readon...
FPGAsprovideagoodcompromisebetweengeneralpurposeprocessors(GPPs)andapplicationspecificintegratedcircuits(ASICs).GPPsarefullyprogrammablebutare
lessefficientintermsofpowerandperformanceASICsimplementdedicatedfunctionalityandshowthebestpowerandperformancecharacteristics,butrequire
extremelyexpensivedesignvalidationandimplementationcycles.FPGAsarealsousedforprototypinginASICworkflowsforhardwareverificationandearlysoftware
development.
Duetotheorderofmagnitudeperformanceimprovementwhenrunninghighthroughput,highperformanceapplications,algorithmdesignersareincreasinglyusing
FPGAstoprototypeandvalidatetheirinnovationsinsteadofusingtraditionalprocessors.However,manyofthealgorithmsareimplementedinMATLABduetothe
simpletouseprogrammingmodelandrichanalysisandvisualizationcapabilities.WhentargetingFPGAsorASICstheseMATLABalgorithmshavetobemanually
translatedtoHDL.
Formanyalgorithmdeveloperswhoarewellversedwithsoftwareprogrammingparadigms,masteringtheFPGAdesignworkflowisachallenge.Unlikesoftwarealgorithm
development,hardwaredevelopmentrequiresthemtothinkparallel.Otherobstaclesinclude:learningtheVHDLorVeriloglanguage,masteringIDEsfromFPGA
vendors,andunderstandingesoterictermslike"multicyclepath"and"delaybalancing".
Inthispost,IdescribeaneasierpathfromMATLABtoFPGAs.IwillshowhowyoucanautomaticallygenerateHDLcodefromyourMATLABalgorithm,implementthe
HDLcodeonanFPGA,anduseMATLABtoverifyyourHDLcode.

MATLABtoHardwareWorkflow
TheprocessoftranslatingMATLABdesignstohardwareconsistsofthefollowingsteps:
1.ModelyouralgorithminMATLABuseMATLABtosimulate,debug,anditerativelytestandoptimizethedesign.
2.GenerateHDLcodeautomaticallycreateHDLcodeforFPGAprototyping.
3.VerifyHDLcodereuseyourMATLABtestbenchtoverifythegeneratedHDLcode.
4.CreateandverifyFPGAprototypeimplementandverifyyourdesignonFPGAs.

TherearesomeuniquechallengesintranslatingMATLABtohardware.MATLABcodeisproceduralandcanbehighlyabstractitcanusefloatingpointdataandhasno
notionoftime.Complexloopscanbeinferredfrommatrixoperationsandtoolboxfunctions.
ImplementingMATLABcodeinhardwareinvolves:
ConvertingfloatingpointMATLABcodetofixedpointMATLABcodewithoptimizedbitwidthssuitableforefficienthardwaregeneration.
Identifyingandmappingproceduralconstructstoconcurrentareaandspeedoptimizedhardwareoperations.
Introducingtheconceptoftimebyaddingclocksandclockratestoscheduletheoperationsinhardware.
Creatingresourcesharedarchitecturestoimplementexpensiveoperatorslikemultipliersandforloopbodies.
MappinglargepersistentarraystoblockRAMinhardware

HDLCodersimplifiestheabovetasksthoughworkflowautomation.

ExampleMATLABAlgorithm
Let'stakeaMATLABfunctionimplementinghistogramequalizationandgothroughthisworkflow.Thisalgorithm,implementedinMATLAB,enhancesimagecontrastby
transformingthevaluesinanintensityimagesothatthehistogramoftheoutputimageisapproximatelyflat.
typemlhdlc_heq.m
%HistogramEqualizationAlgorithm
function[pixel_out]=mlhdlc_heq(x_in,y_in,pixel_in,width,height)
persistenthistogram
persistenttransferFunc
persistenthistInd
persistentcumSum
ifisempty(histogram)
histogram=zeros(1,2^8);
transferFunc=zeros(1,2^8);
histInd=0;

cumSum=0;
end
%Figureoutindicesbasedonwhereweareintheframe
ify_in<height&&x_in<width%validpixeldata
histInd=pixel_in+1;
elseify_in==height&&x_in==0%firstcolumnofheight+1
histInd=1;
elseify_in>=height%verticalblankingperiod
histInd=min(histInd+1,2^8);
elseify_in<height%horizontalblankingdonothing
histInd=1;
end
%Readhistogram
histValRead=histogram(histInd);
%Readtransferfunction
transValRead=transferFunc(histInd);
%Ifvalidpartofframeaddonetopixelbinandkeeptransferfuncval
ify_in<height&&x_in<width
histValWrite=histValRead+1;%Addpixeltobin
transValWrite=transValRead;%Writebacksamevalue
cumSum=0;
elseify_in>=height%Inblankingtimeindexthroughallbinsandresettozero
histValWrite=0;
transValWrite=cumSum+histValRead;
cumSum=transValWrite;
else
histValWrite=histValRead;
transValWrite=transValRead;
end
%Writehistogram
histogram(histInd)=histValWrite;
%Writetransferfunction
transferFunc(histInd)=transValWrite;
pixel_out=transValRead;

ExampleMATLABTestBench
Hereisthetestbenchthatverifiesthatthealgorithmworkswithanexampleimage.(NotethatthistestbenchusesImageProcessingToolboxfunctionsforreadingthe
originalimageandplottingthetransformedimageafterequalization.)
typemlhdlc_heq_tb.m
%%TestbenchforHistogramEqualizationAlgorithm
clearmlhdlc_heq;
testFile='office.png';
RGB=imread(testFile);
%Getintensitypartofcolorimage
YCBCR=rgb2ycbcr(RGB);
imgOrig=YCBCR(:,:,1);
[height,width]=size(imgOrig);
imgOut=zeros(height,width);
hBlank=20;
%makesurewehaveenoughverticalblankingtofilterthehistogram
vBlank=ceil(2^14/(width+hBlank));
forframe=1:2
disp(['workingonframe:',num2str(frame)]);
fory_in=0:height+vBlank1
%disp(['frame:',num2str(frame),'of2,row:',num2str(y_in)]);
forx_in=0:width+hBlank1
ifx_in<width&&y_in<height
pixel_in=double(imgOrig(y_in+1,x_in+1));
else
pixel_in=0;
end
[pixel_out]=mlhdlc_heq(x_in,y_in,pixel_in,width,height);
ifx_in<width&&y_in<height
imgOut(y_in+1,x_in+1)=pixel_out;
end
end
end
end
%Makecolorimagefromequalizedintensityimage
%Rescaleimage
imgOut=double(imgOut);
imgOut(:)=imgOut/max(imgOut(:));
imgOut=uint8(imgOut*255);
YCBCR(:,:,1)=imgOut;
RGBOut=ycbcr2rgb(YCBCR);
figure(1)
subplot(2,2,1);imshow(RGB,[]);

title('OriginalImage');
subplot(2,2,2);imshow(RGBOut,[]);
title('EqualizedImage');
subplot(2,2,3);hist(double(imgOrig(:)),2^141);
title('HistogramoforiginalImage');
subplot(2,2,4);hist(double(imgOut(:)),2^141);
title('HistogramofequalizedImage');

Let'ssimulatethisalgorithmtoseetheresults.
mlhdlc_heq_tb
workingonframe:1
workingonframe:2

HDLWorkflowAdvisor
TheHDLWorkflowAdvisor(seethesnapshotbelow)helpsautomatethestepsandprovidesaguidedpathfromMATLABtohardware.Youcanseethefollowingkeystepsof
theworkflowintheleftpaneoftheworkflowadvisor:
1.FixedPointConversion
2.HDLCodeGeneration
3.HDLVerification
4.HDLSynthesisandAnalysis

Let'slookateachworkflowstepindetail.

FixedPointConversion
SignalprocessingapplicationsaretypicallyimplementedusingfloatingpointoperationsinMATLAB.However,forpower,cost,andperformancereasons,thesealgorithms
needtobeconvertedtousefixedpointoperationswhentargetinghardware.Fixedpointconversioncanbeverychallengingandtimeconsuming,typicallydemanding25
to50percentofthetotaldesignandimplementationtime.TheautomaticfloatingpointtofixedpointconversionworkflowinHDLCodercangreatlysimplifyand
acceleratethisconversionprocess.
Thefloatingpointtofixedpointconversionworkflowconsistsofthefollowingsteps:
1.Verifythatthefloatingpointdesigniscompatiblewithcodegeneration.
2.Proposefixedpointtypesbasedoncomputedranges,eitherthroughthesimulationofthetestbenchorthroughstaticanalysisthatpropagatesdesignrangestocomputederivedrangesforallthe
variables.
3.GeneratefixedpointMATLABcodebyapplyingproposedfixedpointtypes.
4.Verifythegeneratedfixedpointcodeandcomparethenumericalaccuracyofthegeneratedfixedpointcodewiththeoriginalfloatingpointcode.

Notethatthisstepisoptional.YoucanskipthisstepifyourMATLABdesignisalreadyimplementedinfixedpoint.
HDLCodeGeneration
TheHDLCodeGenerationstepgeneratesHDLcodefromthefixedpointMATLABcode.YoucangenerateeitherVHDLorVerilogcodethatimplementsyourMATLAB
design.InadditiontogeneratingsynthesizableHDLcode,HDLCoderalsogeneratesvariousreports,includingatraceabilityreportthathelpsyounavigatebetweenyour
MATLABcodeandthegeneratedHDLcode,andaresourceutilizationreportthatshowsyou,atthealgorithmlevel,approximatelywhathardwareresourcesareneededto
implementthedesign,intermsofadders,multipliers,andRAMs.
Duringcodegeneration,youcanspecifyvariousoptimizationoptionstoexplorethedesignspacewithouthavingtomodifyyouralgorithm.IntheDesignSpaceExploration
andOptimizationOptionssectionbelow,youcanseehowyoucanmodifycodegenerationoptionsandoptimizeyourdesignforspeedorarea.
HDLVerification
StandaloneHDLtestbenchgeneration:
HDLCodergeneratesVHDLandVerilogtestbenchesfromyourMATLABscriptsforrapidverificationofgeneratedHDLcode.YoucancustomizeanHDLtestbench
usingavarietyofoptionsthatapplystimulitotheHDLcode.YoucanalsogeneratescriptfilestoautomatetheprocessofcompilingandsimulatingyourcodeinHDL
simulators.ThesestepshelptoensuretheresultsofMATLABsimulationmatchtheresultsofHDLsimulation.
HDLCoderalsoworkswithHDLVerifiertoautomaticallygeneratetwotypesofcosimulationtestbenches:
HDLcosimulationbasedverificationworkswithMentorGraphicsModelSimandQuestaSim,whereMATLABandHDLsimulationhappeninlockstep.
FPGAintheLoopsimulationallowsyoutorunaMATLABsimulationwithanFPGAboardinstrictsynchronization.YoucanuseMATLABtofeedrealworlddataintoyourdesignonthe
FPGA,andensurethatthealgorithmwillbehaveasexpectedwhenimplementedinhardware.

HDLSynthesis
Apartfromthelanguagerelatedchallenges,programmingforFPGAsrequirestheuseofcomplexEDAtools.GeneratingabitstreamfromtheHDLdesignand
programmingtheFPGAcanbedauntingtasks.HDLCoderprovidesautomationhere,bycreatingprojectfilesforXilinxandAlterathatareconfiguredwiththe
generatedHDLcode.YoucanusetheworkflowstepstosynthesizetheHDLcodewithintheMATLABenvironment,seetheresultsofsynthesis,anditerateontheMATLAB
designtoimprovesynthesisresults.

DesignSpaceExplorationandOptimizationOptions
HDLCoderprovidesthefollowingoptimizationstohelpyouexplorethedesignspacetradeoffsbetweenareaandspeed.Youcanusetheseoptionstoexplorevarious
architecturesandtradeoffswithouthavingtomanuallyrewriteyouralgorithm.
SpeedOptimizations
Pipelining:Toimprovethedesign'sclockfrequency,HDLCoderenablesyoutoinsertpipelineregistersinvariouslocationswithinyourdesign.Forexample,youcaninsertregistersatthe
designinputsandoutputs,andalsoattheoutputofagivenMATLABvariableinyouralgorithm.
DistributedPipelining:HDLCoderalsoprovidesanoptimizationbasedonretimingtoautomaticallymovepipelineregistersyouhaveinsertedtomaximizeclockfrequency,by
minimizingthedelaythroughcombinationalpathsinyourdesign.

AreaOptimizations
RAMmapping:HDLCodermapsmatricestowiresorregistersinhardware.Ifpersistentmatrixvariablesaremappedtoregisters,theycantakeupalargeamountofFPGAarea.HDL
CoderautomaticallymapspersistentmatricestoblockRAMtoimproveareaefficiency.ThechallengeinmappingMATLABmatricestoblockRAMisthatblockRAMinhardware
typicallyhasalimitedsetofreadandwriteports.HDLCodersolvesthisproblembyautomaticallypartitioningandschedulingthematrixreadsandwritestohonortheblockRAM'sport
constraints,whilestillhonoringtheothercontrolanddatadependenciesinthedesign.
Resourcesharing:ThisoptimizationidentifiesfunctionallyequivalentmultiplieroperationsinMATLABcodeandsharesthem.Youcancontroltheamountofmultipliersharinginthe
design.
Loopstreaming:AMATLABforloopcreatesaFOR_GENERATEloopinVHDL.Thebodyoftheloopisreplicatedasmanytimesinhardwareasthenumberofloopiterations.This
resultsinaninefficientuseofarea.Theloopstreamingoptimizationcreatesasinglehardwareinstanceoftheloopbodythatistimemultiplexedacrossloopiterations.
Constantmultiplieroptimization:Thisdesignleveloptimizationconvertsconstantmultipliersintoshiftandaddoperationsusingcanonicalsigneddigit(CSD)techniques.

BestPractices
Now,let'slookatfewbestpracticesrelatedtowritingMATLABcodewhentargetingFPGAs.
WhenwritingaMATLABdesign:
UsethecodegenerationsubsetofMATLABsupportedforHDLcodegeneration.
Keepthetoplevelinterfaceassimpleaspossible.Thetoplevelfunctionsize,types,andcomplexitydeterminetheinterfaceofthechipimplementedinhardware.
Donotpassinabigchunkofparalleldataintothedesign.ParalleldatarequiresalargenumberofIOpinsonthechip,andwouldprobablynotbesynthesizable.Inatypicalimage
processingdesign,youshouldserializethepixelsasinputsandbuffertheminternallyinthealgorithm.

WhenwritingaMATLABtestbench:
Callthedesignfromthetestbenchfunction.
Exercisethedesignthoroughly.Thisisparticularlyimportantforfloatingpointtofixedpointconversion,whereHDLCoderdeterminestherangesofthevariablesinthealgorithmbased
onthevaluesthetestbenchassignstothevariables.YoucanreusethistestbenchtogenerateanHDLtestbenchfortestingthegeneratedhardware.
Simulatethedesignwiththetestbenchpriortocodegenerationtomakesuretherearenosimulationerrors,andtomakesurealltherequiredfilesareonthepath.

Conclusion
HDLCoderprovidesaseamlessworkflowwhenyouwanttoimplementyouralgorithminanFPGA.Inthispost,Ihaveshownyouhowtotakeanimageprocessing
algorithmwritteninMATLAB,convertittofixedpoint,generateHDLcode,verifythegeneratedHDLcodeusingthetestbench,andfinally,synthesizethedesignand
implementitinhardware.
SeethisarticleabouthowoneoftheHDLCodercustomers,FLIRhasusedMATLABtoHDLworkflowtoachievegoodresults.Youcanalsolearnmoreaboutthisworkflow
usingtheproductexampleslocatedhere.
WehopethisbriefintroductiontotheHDLCoderandMATLABtoHDLcodegeneration,verificationframeworkhasshownhowyoucanquicklygetstartedon
implementingyourMATLABdesignsandtargetFPGAs.Pleaseletusknowinthecommentsforthisposthowyoumightusethisnewfunctionality.Or,ifyou'vealready
triedusingHDLCoder,letusknowaboutyourexperienceshere.

GettheMATLABcode(requiresJavaScript)
PublishedwithMATLABR2013a

PublishedwithMATLABR2013a

AddyourCompanytoAlgoWorld
CopyrightAutomatedTraderLtd2016Strategies|Compliance|Technology
CookiePolicy

PrivacyPolicy

Sitemap WebDevelopment:JohnnyVibrant

Potrebbero piacerti anche