05 Fpga

Download as pdf or txt
Download as pdf or txt
You are on page 1of 54

FPGA

In thislessonyou learnhow to usetheLabVIEWFPGAModuleto


reconfigurean FPGAchip.The VO channelsandmodulescommunicate
with theFPGA chip,which you canprogramto run at high rates.
youcanconfiguretheFPGAto passinformationfrom theVO
Furlhermore,
modules,suchasdatafrom sensors
andcalibrationvalues,to thereal-time
controller.ln addition.thereal-timecontrollercancommunicate
feedback
controlsignalsto theFPGAandVO modules.After youdeveloptheFPGA
VI, youcantestanddebugit usingtheLabVIEw development
macbineand
Interacrive
Fronl PanelCommunicalion

Topics
A. Introduction
B. Fixed-PointMath
C. DefiningFPGALogic with LabVlEW
D. DevelopingtheFPGA VI
E. Te.lingwifi lheDevelopmenr
Machine
F. Inlcraclive
FronlPanelCommunicalion
G. Wiring the Modules
H. CompilingtheFPGAVI
I. Downloadingto FlashMemory
J. UsingLabVIEWFPGAwith CompactRlOSczur
Mode

lnsltunenlsCorpontian
A National

ConpactRlo
andLabVlEW
Fundanentals
CouseManual

A. lntroduction
An FPGAis a chip thatcanbereconfigured
throughsoftwarefor different
applications.
TheNationallnstruments
LabVIEWFPGAModuletargetsNl
reconfigurable
tO (RIO) devicessuchasR Seriesdataacquisition(DAQ),
CompactVision,andCompactRlo.Referto ni . con for a cuffentlist of
devices.R SeriesDAQ devicessupportcomplexdataacquisitionor
real-timeI/O applications.
FPGAlogic on an NI CompactVisionsystem
addscustomtriggering,pulsewidthmodulation(PWM) signals,motion
control,orcustomcommunications
protocols.CompactRlousesFPGAfor
modularity,FPGA-timedVO with built-insignalconditioning,anddirect
signalconnectivityfor maximumflexibilityin embedded
measurement
and
controlapplications.
A singleFPGA canreplacethousands
of discretecomponents
by
incorporating
millionsoflogic gatesin a singleintegrated
circuit(IC) chip.
Figure5-1 showstheFPGAasa reconfigurable
digitalarchitecture
with a
matrixofconfigurablelogic blocks(CLBs)with horizontalandvertical
routingchannelssuroundedby a peripheryofVO blocks.Signalscanbe
routedwithin the FPGAmatrixin anyarbiuarymannerby programmable
interconnect
switchesandwire routes.The switches,knownasregister
flip-flops,passdatafrom inputto outputon a risingedgeof theclock.VIs
you build in LabVlEW definethelogicalinterconnections
betweenCLBs.
produces
(LUT),
The VI
a look-uptable
alsoknownasa truthtable,rhar
definesoutputsfrom all possibleinput valuesto a logicfunction.Typical
logic functionsincludeBooleanoperations,
comparisons,
andbasic
mathematical
operatiors.

CanpactRt0
andLabVtEw
FundanentaE
Causettanual

E3
h

Ert
Lr,

rlt

>,
-t
h

rcf
>
El
/O B ock

F'
-

rl,
hJ
b.

.t
l-.

conigL,bleLogicB ock(CLB)

ld
Figure
5-1. FPGA
Device

>r

lIE
f-

Figure5-2 showsa simpleVI thatcalculates


a valuefor F from inputsA, B,
C, andD whereF C x D x (A + r). Figure5-3 showshow theVI logic is
implemented
on an FPCA.

F3
-

blt

Ht
h

frd
Ih

f'{
h

-t

A Na anallnstrunenECotponlon

5-3

ConoattBlqandLabVlEW
Fundanentals
CouceManual

Figure
5-2. S mplLabvlEW
Vl

tr
T

n
T
I
T
I

c
D

tr

tr

T
1

InterconnectResources

l/O Cells

Loqic Blocks

Figure
5-3. lmplererling
Vl Logicor |-PGA
An FPGA is analogousto a printed circuit board that hasa large numberof
unconnecteddeviceson it. Traditionally,the devicesare connectedwith
physicalwires solderedto the pins with a wire wrapping tool, or embedded
jn the printed circuit board. The physicalwires are difficult to modity.
Howevet the conncctionsin an FPGA circuit are dynamicallydefinedin
softwarewhen the LabVIEW code is comDliedand the wirins list is

ConpacRlAandLabVlEW
fundanentats
Cou6eManuat

5-4

Fr

F
F
F
P
F
F
F
LI
h

Fat

l'

Lesson5

downloaded.
The wiringlist causessemiconductor
switchesto turn on or
off, therebydefiningtheconnections
betweengates.
CompactRlooffers4- and8-slotchassiswith optionsfor eitherI million or
3 million gateFPGAchips.The numberof garesis thecombinationof
memorybanks,cells,multipliers,andsoon. Theefhciencyof a gatein an
FPGAis not equivalent
to thatofa gatein anapplicationspecificintegrated
circuit(ASIC).Forexample,a 1 M gateFPGAis roughlyequivalenr
ro a
100K gateASIC.
Table5- 1 specifiesfte numberof logic slices,cells,andRAM in
CompactRlodevices.
A logiccell consistsofa lookuptable,a flip-flop,and
connections
to adjacent
cells.The lookuptableusescombinatodallogic to
implementa 4 inputexpression
suchasand,or, nand,addition,andsoon.
A logicsliceconsistsof two logic cells.
Xilinx countsapproximately
2.25logic cellsper slicebecause
theycando
moreper CLB thanotherarchitectures.
A CLB consistsof4 slices.This
combinedarchitecture
providesbenefits,suchasincreased
performance
of
logicexecution,in thefinal system.The Xilinx FPGAalsoincludesother
components
suchas44 memoryblocks,eachproviding2 K of storage,and
multipliers.
Table5-1. cRl0FPGA
LogicSlices,
Cells
andRAIM
Specifications

Fdt

t-

rr
t*

F
-

frdt
r{t
h

rr|
r{t

.PGA

Property

CRIO-9101and 9102 cRIO-9103and 9104

Number oflogic slices

5,120

r1.336

Equivalentnumberof
logiccells

I1,520

32,256

Availableembedded
RAM (bytes)

81,920

t96,608

Theembedded
RAM storesdatafrom theFPGAVI withoutconsuming
valuableFPGA space.

B.Fixed-Point
Math
Thefixed-pointdatatypeis a numericdatatypethatreprsents
a setof
rationalnumbersusingbinarydigits,or bits.Unlikethefloating-pointdata
type,whichallowsthetotalnumberofbits LabVlEWusesto represent
numbersto vary,youcanconfrgurefixed-pointnumbersto alwaysusea
specificnumberofbits.Hardwareandtargetsthatonlycanstoreandprocess
datawith a limitedor fixed numberofbits thencanstorcandprocessthe
numbers.Youcanspecifytherangeandprecisionof fixed-pointnumbers.

{
@National
hstrunenlsCaryo.atQn

5-5

Conpactql9andLabVlEW
fundanentalsCouseManual

YoucanspecifyanysizebetweenI and64 bits' inclusive'for a fixed-point


fixed-pointnumbelsassignedor unsigned'
nu.b"r. iou
"onfigure
"un
dalatype thedenominalorof
usinglhen'xed-point
a ralionalnumber
N0le To represent
thebinarynumbersystemis a hase-2
ii" tu,i"r"i'"".t"t -"st be a powerof2, because
numbersystem.
Usethe fixed-point datatype when you do not needthe dynamic
or whenyou wantto work
functionalityof floating-pointrepresentation
an
with a targetthatdoesnot supportfloating-pointarithmetic'suchas
FPGAtarget.
Thefixed point datatypeprovidessomeof the flexibility of the
of
floating-pointdatatyp; bul aho maintainsthesizeandspeedadvantages
type
data
int"ge."*ittt-"ti". tiy default,eachoperationon the fixed-point
geniratesa fixed-pointresultthatis largeenoughto holdall possibleoutput
valuesspecifiedby the input types
the fixed-point
tl0te FPGA SignalGenerationVIs and somefunctionsdo not support
datatype.
losefractionalbits'
Caulion If youwire a fixed-pointnumberto an integer'you might

W0rdLenglh
andIntegel
WordLength,
Encoding,

parameters
The encoding'word length' andintegerword length arethe tbree
by a fixed-point number'These
thatdefinethe valuesthit canbe represented
parametersare all user-deftnedand canbe modified by right-clicking on a
fixed pointconstant,control,or functionandselectingProperties'
Encoding-The binaryencodingof thefixed-pointnumberYlu can
the
selectsignedorunsigned.Ifyou selectsigned,the signbit is always
lhedata'
fir.t bit in thebit stringlhattepre\enlq
Word length-The total numberof bits in the bit string that LabVIEw
all possiblevaluesof the fixed-pointdata LabVIEW
usesto represent
acceptsa maximumword lengthof & bits Certaintaryetsmightlimit
VI
datato smallerword lengths.Ifyou opena VI on a targetandthe
can
the
target
than
containsfixed-pointdatawith largerword lengths
a
acceDt.the VI ;ontains brokenwires.Refer to the documentationfor
hrg;t to determinethe maximumword length the target accepts'
that
Integer word length-The numberoi integerbits in the bit string.
data'
LabiIEw usesto representall possiblevaluesof the fixed-point
bit'
oq given an initial poiition to the left or right of the most significant
significant
the-numberof bitsio shift the binary point to reachthe most
can
bit. The integerword lengthcanbe largerthan the word length' and
be positiveor negattve.

cougeManual
Fundanentals
conpactll?andLabvtEvtl

5'6

Numeric
Re0resentali0n
0fFixed-P0int
Numbers
The maximum and minimum valuesofa fixed-point numberare dependent
upon the encoding,the word length,and the integer word length of the
numbea Thc equationsto determinethesevalueswill changebasedupon
the encoding.The deltaofthe numberis basedon the differencebetweenthe
word lenglh and the integerword length

Table
5-2. Nurerc ReDrese
rtarion
Exam0les
Representation

Minimum Value

Maximum Value

U8

255

I8

-128

r2'1

t2'7.5

Delta

FXP<+.8,7>

0.5

FXP<+,8,6>

0.25

FXP <1,8,7>

0.5

FXP <1.8,6>

0.25

FXP <+,8,0>

0.0039

63.75
-64

63.5

3r.'15
0

0.9961

When the fixed-pointnumberis urlsigned,it is representedas <+,X,Y>. For


an unsignedfixed-pointnumber,the maximum value ofthe fixed-pointdata
is 2Y 1/(2(x-Y)and the delta is 1/(2(xY)).The minimum valuethat can be
rcpresentedis zero. For example:
<+,8,6> is an unsigned8-bit numberwith six integerbits and two decimal
bits. The maximun valuethat can be representcdis 26- 1/(2(86)) = 61 - Va=
63.75andthe deltais l/(2(86))- 0.25.
When the fixed point numberis signed,it is representedas <t,X,Y>. ln this
case,the maximum value of the fixed-pointdata is 2Y I l/(2(x Y)).The
delta is still representedas l/(2(x Y)).The minimum value that can be
representedis -2Y. For example:
<1,8,6> is a signcd 8-bit number with six integerbits. The maximum
value that can be representedis 26-l - l/(2(8 6) = 31 75 and the delta {
1/(2186, = 0.25. The minimum valuethat can be representedis 26 = 32.
N0te The differencebetweenthe maximum and minimum valuesfor a signed
fixed point number is the sameas the differencebetweenthe maximum and minrmum
valuesfor an unsignedfixed-pointnumberwith the sameword and integerword lengths.
The delta also doesnot change.

lnsnunenlsCorpotation
@ Nanonal

ConpactBtjandLabVtEW
Fundanentats
Caurse
Manual

If theintegerwordlengthis largerthantheword length,LabVIEWdoesnot


storetheintegerbitsthatexceedthewordlength.For<+,8,10>,thetwo least
significantbits wouldnotbe stored.The maximumvaluethatcanbe
= 1020andthe deltais
by this numberis 2r0- 1/(2(8r0D
represented
ro))
4.
1/(2(8
Ifthe integerword lengthis negative,LabVIEWdoesnot storanyinteger
bits andalsodoesnot storethenumberof fractiolal bits equalto the
negativenumbet startingfrom the binarypoint.Thus,for <+,8, 2>, the
= 0.2490234375
is 2-2- ll(2(8+2))
maximumvaluethatcanbe represented
=
andthedettais t12rt+z)\ 9..165625E-4.

Fixed-Poinl
Conliguration
or
Youcanconfigurea hxed-pointnumberin a numericcontlol,constant,
indicator.
After youconfigurea fixed-pointcontrol,constant,or indicatot,thatobject
cannotdisplaya numberthatdoesnot conformto the settingsyou specify.
If theobjectyou configureis an indicatotLabVIEW coercesanyinput
settingsof
valueto theindicatortoconformto thefixed-pointconfiguration
the indicator.

Conlrols
Conliguring
Completethe following stepsto configure a fixed-point number in a
numellc conuol.
1- Right-click the control and seleclPropertiesfrom the shortcutmenu to
displaythe Numeric Propertiesdialog box.

Manuat
Course
ConpacfilA
andLabvtryFunrknentats

l t F r Pt l

r-rodtq

!.00'rq

Valuer onth.Bata

Entrytdb haye.hanqed,

t--a ltc"...'ltG

Figure5-4. Fixed-Point
C0ntr0l
Configuration

2 . On the DataType page,click the datatype icon in the Representation


sectionand selectFXP (Fixed-point) from the shoftcutmenu. The
Fixed-PointConfrgurationsectiondisplaysdefault valuesfor the
Encodingand Rangeoptions.

3 . Completethe following slepsto configurethe Rangeoflhe fixed-point


numbet
U SelectSigned or Unsigned to specifywhetheryou want to represent
a signedor unsignednumber.
fl

ln the Word length field, specifythe total numberof bits you want
to use to representthe value of the fixed-point nunber.

D In the Integer word length field, specify the numberof integerbits


you want to use to reprcsentthe value ofthe fixed-point number.
1 . (Optional)Placeacheckmarkin the Include overflow status checkbox
to include an overflow statusin the fixed-point number

5 . Click OK to closethe dialog box and apply the conhgurationsettings.

A Nalional
lnstrunenE
Coryontbn

C,noactRloandLabWEW
rundanentats
Course
Manual

Configuring
Conslanls
Completethe followingstepsto configurea fixed-pointnumberin a
numedcconstant.
1. Right-clicktheconstantandselectPropertiesfrom the shortcutmenu
to displaythe NumericConstantPrcperties
dialogbox.
2. On the Data Type page,removethe checkmarkfrom the Adapt to
entereddala checkbor.
Nole Whenyou selectAdaptto entereddata,LabVIEWdisplaysanyvalueyou enter
with the shofiestpossibleword lengthandintegerword length.Youmustremovethe
checkmarkfrom this checkboxifyou wantto makechangesto theFixed-point
Configurationsettings.
3 . Click the datatypeicon in theReprcsentation
sectionald selectFXP
from
the
shoncur
menu.
TheFixed-PointConfiguration
{Fixed-point)
sectiondisplaysdefaultvaluesfor theRangeandEncodingoptions.
4. Completethefollowingstepsto configuretheRangeofthe fixed-point
number.
D SelectSignedor Unsignedto specifywhetheryouwantto rcpresent
a signedor unsignednumber
D In theWord length field,specifytherotalnumberof bits you want
to useto represent
thevalueof thefixed-pointnumber.
D In theInteger word lengthfield, specifythenumberof integerbits
you want to useto representthe valueof the fixed-point number.
5. (Optional)Placea checkmarkin theIncludeoverllowstatuscheckbox
to includean oveflow statusin the fixed-pointnumber.
6. Click OK to closethedialogbox andapplytheconligurationsettings.

Conf
iguring
Indicators
Completethe followingstepsto configurea fixed-pointnumberin a
numericindicator.
l . Right-clicktheindicatorandselectPropertiesfrom the shoncutmenu

to displaytheNumedcProperties
dialogbox.
'I)ipe
On the Data
page,click the datatypeicon in the Reprcsenrarion
sectionandselectFXP (Fixed-point)from the shortcutmenu.The
Fixed-PointConfiguration
sectiondisplaysdefaulrvaluesfor theRange
andEncodingoptions.
3 . Placea checkmarkin theAdapt to sourcecheckboxif you wantthe
valueto inheritthe fixed-pointconfiguration
settingsof an input
fixed-pointvalue.Ifyou selectthis option,skipto step6.
ConpactRlo
andLabVlEW
Fundanentals
CouseManual

LessDnS FPGA

,1. (Optional) Completethe following stepsto configure the Rangeof the


iixed-poin1number
I

In the Minimum field, enter the minimum value to which you want
thc fixed point numberto conform.

fl

In the Maximum field. enter the maxinrumvalueto which you want


the fixed-point numbcrto confbrm.

D ln the Desird delta l'leld,enter the incrementbetweennumbers


within thc Range.
5. (Oplionai) Placea checkmarkin thc Include overflolv status checkbox
to includc an ovcftlow statusin the fixed-pointnumber.
6. Click OK to closethe dirlog box and apply the configurationseltings-

C0nliguring
Fixed-P0int
Functi0ns
Functionsthat supportthe fixcd point datatypc (add,subtract,multiply, and
so on) includc modesto handlethe overflow and rounding. Use the
Propertiesdialog box fbr the function to selecrthe overflow and rounding
modcs.Right click a lunctior and selectPrcpeniesfiom the shortcutmenu
to displaythe Propeiliesdialogbox.

{:'6ri"iip.pi,ni'
aonfouratibn
Aope.ran.soutPut

ll_.-

! ad"pte-'.

fj.

Ifc-;-l

th"r;l

Figure
FJ-ctr0n
5-5. c \ed'Poi1r
Corligurari0r

A Nahanal
lnsltunentsCorpatalion

Fundanentab
Con1actRlA
andLabVlEW
CouBe\4anual

The ovefflow modesaffect the logic generatedwithin the FPCA as followsl


. Saturate-Requires additionalhardwarcresourcesto deternine if thc
inputvalueis widtin tbedesircdrangeolthe outpurtypc.Sarurdte
is thc
delaultoverflow mode. If you specify a desircdrangeotlter than thc
delaull minimum and maximum, the Saturatemodeperforms a full
comparisonbetweenthe desiredrangeand input value, which mighl
rcquireadditionalclock cyclcs to complcte.Ifyou do not specily a
desiredrangc,the Sa(uratemode checksallbits abovethe most
significantbit of tlte output type lo ensurethe ourput did not overflow.
. Wrap-Requircs fewer hardwareresourccsthan thc Saturatemode.

Eib Edrt !'e4 q.rdd

91qt

Ererere I.ots :&ndow letp

!'l '.uA"F"...0( - :-.ll

tI..l

-l|t r5,

g[ Unrirled
r 8rftk Diaqram
onun ... L- .- fl
!4e Ed'i !,erJ r'o:!t

oFddre I@,

lhd

lml

Fl"5 ElEtrErd' EEr


ti-;

rdr-i;dPmr-itFpdr;qei

-,F

Eillcd

>

rntdedPDre.t IiFPGArarir3r,Emuldtor

Figure
5"6.lvlismatchd
The roundingmodesaffict the logic generaredwithin the FPGA as follows:
. Truncate-Retnoves fractionalbits and thereforedoesnot rccuire anv
rtltlirionrrl
h.rrdurrere\ource..Houc\cr.lhi. rnodcDroJuce.rhc larse\t
Ine:rn
crror lL,tmo\l drls \lterm5.This modc i. the rrefuulrfor inreglr
oPeralions.
. Round-Half-Up (Asymmetric)-Adds to the leasrsignificant bit and
thereforerequiresan adderthat is the width of the output type.
.

Round-Half-Even Requiresthc mostluldware r.esources


andhas the
slowesttiming ofthe thaeeroundingmodes.However.this moder.etur-ns
lhe most statisticallycorrcct resultsfor most datastreamsand is
thereforethe default rounding mode fbr the fixed-point data typc.
Although this mode requircsonly a modestamount of additional
hardwarecomparedto the Round-Half Up (Asymmetric) mode, the

canpactql0andLabVlEW
fundanentalsC0u6eLlanual

512

Lesson5

FPGA

pathis longer,whichreducesthe
lengthof thelongestcombinatorial
maximumclock frequencyfor thepath.
or Round-HalfEven
RoundHalf-Up(Asymmetric),
Note If you selectthe Saturate,
modesandtheoutputcanhandletheoverflowortounding,theoperationdoesnotrequire
If a coerciondot doesnot appearon the blockdiagram,
additionalhardwareresources.
theoutputcanhandletheoverflowor roundingwithoutadditionaihardwareresoulces
For more information aboutfixed-point dataand fixed-point arithmetic,
referto the lblloqing Ldl'yllWHelf lopic.:
.

Numeric Data

'

Configuring FLxed'PoitltNumbers

Numeric Data TJpes Table

C. DeliningFPGALogicwith LabVlEW
computing
reconfigurable
The FPGAcircuitryis a parallelprocessing
enginethalexecutes
a LabVIEWVI in siliconcircuitryon achip.As shown
in Figure5-7,you canusetheLabVIEw FPGAModuleto defineFPGA
suchasveryhigh
logic usingLabVIEWVIs insteadoflow-levellanguages
(VHDL).
LabVIEw
description
language
circuithardware
speedintegrated
paralleltasksin
or asynchronous
andFPGAcanimplementsynchronous
analoganddigitalsignals
synchronized
hardwareto processandgenerate
deterministically.
rapidlyand

Bt

FPGA
Logic
Module
Delines
FPGA
Figure5-7. LabvlEW
@Nationat
lnstrunentsCatpon an

Fundanentals
Cou6eManual
conoact\l0andLabvtEW

Figure5-8showstheblockdiagramfor theFPGAconrmunications
with yO
modulesandthecontrollerthoush the PCIbus.

I
tigwe5-8. FPGA
Communications
BiockDiagram
The LabVIEWFPGAmodulecompilesLabVIEWVIs to FPGA hardware
usingan automaticmulti-stepprocess.Behindthe scenes,
the VI is
to text-based
translated
VHDL code.ThenindustrystandardXilinx ISE
compilertoolsoptimize,reduce,andsynthesize
the VHDL codeinto a
hardwarecircuitrealizationof theLabVIEWdesign.This processalso
appliestimingconstraints
to thedesignandtriesto achieveanefficientuse
(sometimes
ol FPGAresources
calledfabric).
DuringtheFPGAcompilation,the VI is optimizedto reducedigitallogic
andcreateanoptimalimplementation
ofthe LabVIEWapplication.The
endresultis a bitstreamfile thatcontainsthegatearrayconfiguration
information.Whenthe applicationruns,thebitstreamloadsinto theFPGA
chip andreconfigurcs
thegatearay logic.Thebitstreamalsocanloadinto
nonvolatileflashmemoryandloadinstantaneously
whenpoweris applied
to thetarget.Thereis no operatingsystemon the FPGAchip.However,
enable-chain
logicbuilt intotheFPGA applicationcanstartandstop
execution.
Programming
anFPGArequiresa softwaretool in whichthelogicfunctions
aredefined.An analysistool thenverifiesthelogicalfunctionsandthe
expected
timingof thesignalsin the device.A layouttool physicallymaps
the logicaldevicesto specificelementson thechip anddeteminestheir
actualwiring.
Whenyou run an FPGA VI or build for FPGA from the Tools menu,the
LabVIEW diagramis convertedto intermediatefiles that are sentto the
compileserverwheretheyarecompiledfor the FPGA,asshownin
Fisure5-9.TheserverretumstheFPGAbitstreamto LabVIEWwhereit is

ConpactRloandLabvtEW
fundanentals
Course
Manual

=e
Lessons .PGA

rl,
E
E
-,
E
-

is a client,you can
storedin theVI. BecausetheLabVlEW environment
while compiling.The compiled
from the serverandreconnect
disconnect
bitstreamis uniqueto eachtype of CompactRloFPGAandbackplane.
Youcancompilea VI to differentCompactRlotargetsandthedifferent
arestoredin fte sameVI. Thebitstreamdownloads
bitstreams
whenyou a compiletheVI by clickingtheRun button.
automatically

F3

rr
I
=

rr
14

E
tr
E
f

tr

Process
Server
Figure
5-9. Compile
Whenit is turnedoff, the FPGAdoesnot retaintheVI. The VI mustbe
reloadedat powerup.The VI loadsfrom onboaldflashmemoryor from
to uqing
Onead\anlage
o\ er lhebusinlerface.
sofrrareon theconlroller
flashmemoryis thatthe VI startsexecutingalmostimmediateiyafter
power-up,insteadofwaitingfor thecomputerto completelyrestartandload
the FPGA.
andcontlnueto
independently
You cancrealerobustFPGAVIs thatoperate
nrn evenifthe hostcomputer-thecomputerthatcontrolsandmonitorsthe
FPGAtarget {rashes.Fu hemore,youcandesigntheFPGAVl to store
dataon theFPGAuntil the hostcomputercanretdevethedata
andcustomVO
TheFPGA logicprovidestiming,tdggering,processing,
EachfixedI/O resourceusedby theapplicationusesa small
measurements.
The bus
portionof fte FPGAlogic tl'latcontrolsthefixed VO resource.
intedacealsousesa smallportionofthe FPGAlogic to providesoftware
to thedevice.TheremainingFPGAlogicis availablelor higherlevel
access
tulctionssuchastiming,t ggering,andcountingThefunctionsusevaried
amountsof logic.The amountof FPGAspaceyour applicationrequires
on yourneedfor I/O recovery,VO, andlogic algorithms
depends
you canimplementmultiloop
RIO FPGAhardware,
With theembedded
analogPID controlsystemsat loop ratesexceeding100ks/s. Youcan
implementdigitalcontrolsystemsat loopratesup to I MS/s,andit is
possibleto evaluatemultiplerungsofBooleanlogic usingsinglecycle
ofthe parallelnatureof the RIO
while Loopsat 40 MHz (25 ns).Because
reducethe speed
core,addingadditionalcomputationdoesnot necessarily
of the FPGAaDDlicaiion.

lnsltunenECaryatulion
@National

fundanentats
CouseManual
canpacffilAandLabVlEW

Another bcncfit of running your LabVIEW code on the FPGA is that you
can achievellue, simultaneous,purallel processing.There is no operating
systemon the inodule that must dividc CPU timc betwecnsevcraltasks.
Figure5-10 showssirnultaneous
parallelimplcmentation
of
two calculalions,F = (A + B) x C a]ndZ = X + f + M in separatcgateson
an FPGA.
F = {A+B)c

n
T
T
I

I
ft
I

:-.:l

Z = X+Y+[,|

I
I

TT
1

Interconnect
Resources

l/O Cels

LoqicBlocks

Figure
5-10.Parallel
mplementation
onanFPGA
Using
Separate
Gates

D.Developing
theFPGA
Vl
The FPGA containsthe VO ponion olyour applicutionas well as any
hardware-based
timing and triggering,low-level signalprocessing,alld so
on. LabVIEW FPGA Module applicationsrangefrrm a single FPGA VI
running on an FPGA targctto largc LabVIEW solutionsthat inciude
multiplc FPGA targets,the LabVIEW Real-TimeModule, and one or rnore
RT targets,and LabVlEW running on Windor,r's.ln any case,you needto
createfie FPGA Vl that runs on the FPGA target.
Wilh $e LabVIEW FPGA Modulc you can use high-levelgraphical
dataflow programmingto createa highly optimized gate-anay
implementationofyour analogor digital control logic- You can use normal
LabVlEW programmingtechniqucsto devclopyour FPGA application.

CanDactqto
andLabVtEW
fundanentats
CaL6eLlanual

Lesson
5

FPGA

Youcandownloadandrun only oneFPCAVI at a time on a singleFPGA


target.If you downloada secondVI to theFPGAtarget,the secondVI
overwritesthefirst VI.
WhenyouaddanFPGAVI undera hatdware
target,suchasa CompactRlo
chassis,
theLabVIEWFunctionspalotteadaptsto containonly theVls and
functionstl'lataredesignedto work on FPGA.Theprimaryprogramming
differencecompared
to traditionalLabVtEWis thatFPGA devicesuse
integermathandfixed-pointmathinsteadoffloating-pointmath.Also,
thereis no notionof multithreading
or prioritiesbecause
eachloopexecutes
in independent
dedicated
hardwareanddoesnothaveto shareresources-in
effect,eachloopexecutes
in parallelat time-c tical priority.Reterto the
ktbVIEWReal-TineApplicationDevelopment
coursefor moreinformation
aboutthreadsandpriorities.
YouuseInteractive
FrontPanelCommunication
to communicate
between
theRT hostandtheVI runningon theFPGAasshownin Figure5-1L You
useProgrammatic
FPGA InterfaceCommunication
to programmatically
conffolandcommunicate
with FPGAVIs from RT hostVIs. The VISA
serveron theRT controllerhandlesupdates
automatically.
Youwill leam
alternatecommunication
processes
laterin thiscourse.

Figure
5-11.lrleracrive
Fronl
Pane
Comrnunication
Youcanrun theFPGAVl in Windowsto checkthelogic ofthe application
befbrecompiling.The softwareemulationmodesimulatestheI/O
operations
but doesnot duplicatethehardware
timing.Traditional
LabVIEWdebugging
toolsareavailablein emulationmode.
Because
theFPGAis extremelyfastandthehardware
implementation
ofrhe
VI is morereliablethansoftware,you shouldput all of thetime-critical
control,acquisition,
andtiming components
of your applicationin the
FPGA.HowevettheFPGA haslimitedspace,sousetheRT controlleror
WindowsPC processors
for dataanalysis,
file VO, anduserinterface
operations.

@tlatianallnstrunentsCorpontion

ConDactBl0
andLabVlEW
fundanentalsCou$eManual

YoustartbuildingtheFPGAVl from the ProjecrExplorer.Right click the


FPGAtargetandselectNew>VIasshownin Figure5 12.SavetheVI in an
appropriatc
lblder andsavetheproject.

Figure5-12. Adda V to theFPGA


Target
The VIs you developfor your applicationshould conform to the project
hjerarchyas shown h Flglte 3 3, Applicdtion ArchitecrureReLatioishipto
the VIs itl lhe Proiect Explorer Tree.'[he FPGA VI residesunderthe FPGA
target.The RT hostVl that runson the CompactRlo controllerresidesunder
the CompactR[Otarget.The Windows host VI residesunder the My
Computertarget.

FPGA
Functions
Palettes
Eachitemundertl'reFPGAtargetin the ProjectExplorerwindowcontains
FPGAtafget-specific
informationandfunctionality.Whenyou selectan
item underan FPGAtargetin the ProjcctExplorerwindow,LabVlEW
displaysonly optionsavailablefor the specificFPGAtarget.Forcxample,
if you selectan FPGAVI underan FPGA targetin theProjectExplorer
windowandview theblockdiagram,LabVIEWdisplaysonly the
subpalettes,
VIs, andfunctions
on theFunctionspalettethattheFPGAtarget
suDDorts,

CjnpactBlAandLabVlEW
rundanentals
Cor$eManul

518

Lessan5

.PAA

TheFPGAFunctionspalettehasmanysimilaritemsto theLabVIEWfor
WindowsFunctionspalette.Onedifferenceis theFPGAI/O palettewith
iconsfor theFPGAI/O Node,FPGAyO PropertyNode,FPGA yO
constant,andthe FPGAyO MethodNode.YouusetheseFPGAVO nodes
to communicate
with VO Modules.Referto Lesson8. Data Transferand
SynchrcniT.ation.
for moreinformationaboutVO Nodes.Propefiiesand
methods
on theFPGAareusedsimilarto standard
LabVIEWprogramrning.
TheyO constantpassesan tO rcferenceto a subvl.
Anotherdifferenceis theFPGAMath & Analysispalerte.Table5-3
describes
theobjectsin theFPGAMath & Analysispalette.
Tahle5-3. FPGA
lvlatf& Alalysis
Palede
0bjects
PaletteObject

Description

ControlVIs

UsetheControMs in FPGAVls to createcontrolapplications


for
FPGAtargets.

UtilitiesVls

Use the Utilities VIs in FPGA VIs to perform varioustaskssuch as


detectingstatechangesofBoolean inputs, detectjngzero crossings,
delaying the input value,limiting the valid rangeof a signal, and
perfbrming linear interpolation.

Generation
VIs

Use rheGeneretionVls in FPCA ro generare


iignals.

Analog Period
Measurement

Calculatesthe period of an evenly sampledperiodic signal using


thresholdcrossingdetection.

ButterworthFilter

Filtersoneor moreinputsignalsusinga lowpassor lighpassIIR


Butterwonhfilter

DC andRMS
Measurements

Calculates
theDC (Mean)and/orRMS valuesofan inputsignal.You
alsocanusethisVI to calculatetheintermediate
Sum,MeanSquare,
andSquareSumvaluesin orderto saveFPGAresources.

FFI

Computes
the FastFourierTransform(FFT)pointby point.

Look Up TablelD

Providesa general-purpose
blockofinitializedmemory.Uselook-up
tablesto storewavefomsfor signalgeneration,
to modelnonlinear
systems,
andior arithmeticcomputations.
If you usetheLook-Up
TablelD ExpressVI in a single-cycle
TimedLoop,wire the outputs
directlyto Feedback
Nodes.TheLook-UpTable1DExpressVI takes
an entireclockcycleto execuiein a single-cycle
TimedLoop.

Notch Filter

Attenuates
a specificftequencybandin oneor moreinput signals
usinga secondorderIIR notchfilter

A NatonallnstrunentsCoeaetion

ConpacfilAandLabVlEW
Fundanentats
Cau$eManual

(C0ntinued)
Table5-3. FPGA
lvlath
& Analysis
Palette
0bjects
PaletteObject

Description

RationalResampler

Providesa rationalresamplingfilter,which updates


the inputsample
rateby an L/M factor whereL is an interpolation factor andM is a
decimationfactor.

ScaledWindow

MinimizessDectral
leakaeeassociated
with funcatedwavefoms.
Whendesigningan FPGA VI, remember
thatit will comrnunicate
with an
RT or Windowshost.YoucanusethefollowingFPGAinterfacefunctions
to prcgrammatically
controlandcommunicate
with anFPGAVI from host
VIs:
Establisbandterminatecommunication
with theFPGAVI.
Download,abort,reset,andrun theFPGA VI on theFPGAtarget.
Readandwrite datato theFPGAVI.
Wait for andacknowledge
FPGAVI interrupts.
ReaddirectmemoryaccessfirsFinfirsFoutbuffers(DMA FIFOS).

FPGA
Input
andoulput
Nodes
lnputsandoutputson FPGA targetsallowyou to connecttheFPGAtarget
to otherdevices.suchassensors
andactuaton.FPGAyO resources
are
fixedelementsofthe FPGAtargetsthatyou useto tansferdataamongthe
differentpartsof the system.On someFPGAtargets,FPGAVO resources
conespondto lineson front panelconneciors,
PXI backplanes,
or
Real-TimeSystemIntegration(RTSI)connectors.
On otherFPGAtargets,
FPGAVO resources
arenodesinsideFPGASthatconnectthepartofthe
FPGAdesignedby NationalInstruments
with thepartofthe FPGAyou
design.EachFPGAVO resourcehasa specifictype,suchasdigitalor
analog.An FPGAtargetmighthavemultipleresources
of the sameor
differenttypes.
YoucancreateFPGAVO items,determine
thetO resources
on theFPGAtargetthatyou wantto use,andthenassignuniquenamesto
thetO resources
vou use.
N0te Refer to the specificFPGA targethardwarcdocumentationfor information about
supported
featuresandyO functionalityon the FPGAtargetyou use.
SeveralI/O exampleVIs areavailablein the NI ExampleFinderin Toolkits
and Modules>FPGA>CompactRlo>Basic IO andToolkits and
Modules>FPGA>CompactRIO>FPGA
Fundamentals.

ContactqlqandLabVlEW
fundaneutahCourse
llanuaj

Lesson
5

FPGA

UsethefollowingtermswhenworkingwiLhFPGA UONodes:
. Terminal-a hardwareconnection
on a CompactRlOmodule.
.

Channel a logicalrepresentadon
in LabVIEWFPGAof a hardware
terminal.

Alias a nameassigned
by thedeveloper
to a particularchannelthat
normallydescribes
thefunctionofthe channel.Assigninga different
channelto an aliasupdatesall instances
ofthe aliaswitl'fn theproject.

TheFPGAVI configurestheFPGAcircuit.WhentheFPGAcircuitis
activated,
it performsthe [/O operations
in hardwareForexample,ifyori
configureanFPGAI/O nodeto reada digitalline,theFPGAVO nodereads
thelineandretumstheresult.Consequently
theFPGAcanreactto theinput
with the speedanddeterminism
availablein theFPGAtargethardware.
Youcanput inputsandoutputs,analoganddigital,all in thesamenodeon
theblockdiagram.YoucanusetargeFspecihc
properties
andmethodson
theFPGAI/O itemswith theFPGA UOProperrvNodeandrheFPGAI/O
MethodNode,respectively.

Digilall/0
FPGAtargetsmight organizedigitalI/O resources
asindividuallinesor as
groupsoflines calledports.A digitalline VO usestheBooleandatatype.
Thedatatypeof digitalport VO is U8; onebit perline.SomeFPGAtargers
provideaccess
to digitalI/O resources
ascnly linesor ports.OtherFPGA
targetsallowyouto access
thesamephysicallinesasindividuallinesandas
polts.

Youcanusedigitalinputandoutputresoutces
to configuretheI/O resource
andcon[ol thedirectionof dataflow.If you usea digitalresource
to w te
an outputsignal,you mustdisabletheoutputbeforeyoucanusethe sarne
resource
to readan input signal.UsetheFPGAVO MethodNodewith the
SetOutputEnablemethodto disabletheoutputline.
lfyou usetheFPGAI/O Nodeto write a digitaloutput,theFPGAI/O Node
writesthedataandenablcstheterminalfor output.Youalsocanusethe
FPGAyO MethodNodewith the SetOutputDatamethodto wriredata
withoutenablingtheoutput.Usethe FPGAI/O MethodNodewith the Set
OutputEnablemethodto enablethedigitalterminal,whichallowsthedata
to be ddvenout. UsetheSetOutputDatamethodbeforethe SetOutput
Enablemethodto specifythestateof thedigitalresource
whenyou enable
theoutput.For example,you mighthaveoneponionof theblockdiagram
generating
continuously
anintemalsignal.UsetheFPGAVOMethodNode
with theSetOutputEnablemethodin anotherportionofthe blockdiagram
to independently
controlwhentheintemalsignalis actuallydrivenout to an
externaldevice.

A Nalional
hstu nentsCoryaratian

ConorcqlAandLabVlEwfundanentals
CouseManuat

Analog
l/0
TheanalogI/O datatypeis I32. Ifyou configureanFPGA I/O Nodeto read
ananaloginput,theFPGAyO Nodemightinitiateaconversion,
wait for the
result,andthenretumthebinaryrepresentation
ofthe voltageasa signed
integerThe analoginputprocessandthesizeofthe resultingdatatype
variesby FPGA target.For manyFPGA targets,you crearerheFPGA VI to
usethebinaryrepresentation
for operations
within theFPGA VI. You also
canpassthe binaryrepresentation
backto theRT hostVI andconvertthe
binaryrepresentation
to a voltageor otherphysicalquantity.
Ifyou configuretheFPGAyO Nodeto write an analogoutput,theFPGA
tO Nodemightw te thebinaryrepresentation
of the voltageto the
digitalto-analogconverter(DAC),which setstheanalogoutputvoltage.
The sizeof the datatypevadesby FPGAtarget.Youcangenerate
voltage
inlbrmationin two sources-the
RT hostVI or the FPGAVI. Typicallythe
RT hostVI convertsthe voltageto an appropriate
binaryrepresentation
beforewriting thevalueto theFPGAVL If the FPGAVI determines
rhe
voltage,typicallytheFPGAVI performsthecalculations
usingthe
appropriate
binaryrepresentations.
In bothcases,the DAC producesa
voltagethatcorresponds
to thebinaryrepresentation.

Handling
Errors
Youcan ght click theFPGAI/O Nodeon theblockdiagramandselect
ShowError Terminalsio addstandardLabVIEWerlor in anderrorour
paramete$to thefunction.If anellor occurs,you might receiveincorrect
data.Add errorparameters
to be sutethedatayou rcceiveis valid.FPGA
targetsmight reporterrorsdifferently.Referto the specificFPGAtarget
hardwarcdocumentation
for informationabouthow specificFPGAtargets
reporterrors.
Nole Addingeror in anderrorout parameters
increases
the amountof spacethe
functionuseson theFPGA target.Theerrorin anderrorout parameters
alsocancause
slowerexecutionon the FPGAtarget.Sousethemasa genemliule, but ifyou have
difficultywith eitherthe sizeor the speedofthe FPGAapplication,removethemafter
carefullvtestinsvourcode.

ConpacnlAandLabVltWFundanentals
CouBeManual

LCSSON
5

FPGA

Using
FPGA
U0Nodes
YouplaceanFPGA I/O Nodeon theblockdiagramfrom thepalettecr by
dragginganFPGA l/O item from rheProjectExplorer.
If you addtheFPGA VO Nodefrom the Functionspalette,you must
coDfigureit by right-clicking,selectingSelectFPGA UO, andmakingthe
appropriate
choicesfor configuration.
The SelectFPGA VO submenu
displaystheFPGAI/O itemsthatappearin theProjectExplorertree.you
alsocanclickthe FPGAVO Nodeandusethe shortcutmenuto addnew
FPGAyO itemsor selcctfromFPGAI/O itemsyoupreviouslyaddedto the
project.

Timing
l/0withlheLoopTimer
Vl
Somemodules,suchastheNI9233,allowyou to setadatarateandnumber
of samples,
similarto usingtheN Samplesoptionin the DAe Assistant.
Others,suchasthe Nl 9122,aresimilarto the singlesamplenode.
Normally,youusea loop to acquiremultiplesamplesfrom a singlesample
modemodule.Youcantime the loop andcontroltheacquisitionratewith
the VIs from the Timingpalette.
TheLoopTimertimesa loopto execute
on anintervalspecifiedby thevalue
wiredto theCount input.Thefirst time theLoop Timerexecutes
in a loop,
it recordsthecurrenttime.The nexttime the LoopTimerexecutes,
it adds
Count to theinitial time andwaitsuntil Count haselapsedtiom the initial
recordedtime.The LoopTimerdoesnot wait thefirst tjmeyou call it in an
FPGAVI. Ifyou placethe LoopTimerin a loop sothatit canexecute
irninediately
whentheloopstafis,all thecodeparallelwith theLoop Timer
in the loopexecutes
twicebeforeCount elapsesafiertheinitial time.To
preventthecodefrom executingtwicebeforeCount elapses,
usea Flat
Sequence
structure
or a StackedSequelcestructurewith theLoopTimerin
the lust frameandtherestof thecodein subsequent
frames.
ln thefirst iterationof thesequence,
theLoop Timersetsa flag to markthe
loopstanandthenthenextsequence
immediately
beginsexecution.
During
the secondloopiteration,theLoopTimerreadsthetime stampof the flag
from thepreviousloopiterationandholdsfor thewait timeto expire.Ifthe
executionofthe codewithin Lheloopexceedstheloop ratedefinedby the
timingfunction,thenthelooptimingadjustsitselfforsubsequent
iterations.
The LoopTimerdiffersftom theWait Until Next msMultiplefunction,
whichexecutes
on a multipleofthe wired-inrnillisecondvalue.

@NationallnstrunenECotpontion

canpactBl9andLabVlEW
FundanentaE
CouseManual

The LoopTimerconfiguration
dialogbox hasthe followingoptions:
. Counter Units-Unit of time theVI usesfor thecounter.

Ticks-Sets thecounterunitsto a singleclockcycle,the lengthof


which is determined
by theclockratefor $hich the VI is compiled.

[Sec-SeLs thecounterunitsto microseconds.


msec-Sets thecounterunitsto milliseconds.

Sizeof Internal Counter-Specifiesthemaximumtime (8, 16,or


32 bits) a timercantrack.To savespaceon the FPGA,usethesmallest
Sizeof IntemalCounterpossiblefor theFPGA VI.

The LoopTimer input,Count,specifiesthetime betweenloop iterations.


Theoutput,Tick Count, retumsthe valueof a freerunningcounterwhen
theVI wakesup.A freerunningcounterrollsoverwhenthecounterrcaches
themaximumofSize of Internal Counterspecifiedin the configuration
dialogbox.
Youcantime your FPGAcodeusingeithertheLoop TimerVI or theWait
VI. The Wait VI addsan explicitdelaybetweentwo operations
on the
FPGA.YoucanusetheWaitVI to controlthepulselengthofa digitaloutput
or adda triggerdelaybetweena triggersignalandtheresultingoperation.
The differencebetweenthesetwo VIs is how theyaffectcodeexecution.
Whenusingthe LoopTimer,dudngthefirst iteration,the codeexecutes
immediately,
whereastheWait VI delaysthecodeexecution.
Figure5-13showsthelnop Timerin thefiIst sequence
of a Flat Sequence
structure.
The sequence
structurcis nestedin a While Loop for continuous
execution.
A Falseconstantis wiredto theconditionalterminalbecause
the
RT hoststartsandstopstheFPGA.The secondframeofthe Sequence
structurecontainstheFPGAyO Nodeandindicatorsthattransferthedata
to a hostVI.

Inte,v.r(mse()
lE-l----------------']l

,-\
1! l. I

[fPl

LEI

tll

Figure5-13.LoopTimerinanFPGA
Appficati0n

ConpaclRloandLabvtEW
Fundanenkls
Cau$eManual

F
F
F
FT
Ih,

F
I
-1

Frt
-l

I
r

Lesson5

Plogrammalic
FronlPanel
C0mmunicati0n
Theblockdiagramin Figure5,13 usesthreeindicatorsandonecontlol.
Thesevaluescanbe readin anRT or WindowshostVI usingprogranrnatic
FrontPanelCommunication
alsocalledprogrammatic
FPCAInterface
Communication.
Whenyou useProgrammatic
FPGAIntedace
Communication,
theFPGAVI runson theFPGAtarget,anda hostVI runs
on a hostcomputerUsetheFPGA Intedacefunctionsavailablefor a
WindowsVI or anRT targetVI to createa hostVI thatcommunicates
with
the FPGAandperformsotherrequiredfunctions.
Thehostcomputermight communicate
with the FPGAtargelfor rhe
followingrcasons:
. To do moredataptocessing
on a hostthanwill fit on theFPGA
.

To perfom operations
on a hostnot availableon theFPGAtarget,such
astloating-pointarithmetic

To createamultitiefedapplicationwith theFpcA targetasacomponent


of a largersystem

To log dataon a host

To run multipleVIs on a host

To controlthetiming andsequencing
of datatransferbetweenrhehost
andFPGA

To controlwhichcompone[tsarevisib]eon thefront panelwindow


because
somecontrolsandindicatorsmight be moreimportantfor
communication
thanothers

1l
1
h

FPGA

-i

I
E

rf
IE

!t
E

-t
rit
r{
rJ
!t
b

-?

A Naanatlnstrunents
Coryaatian

5-25

ConpattRlOandLabVlEwFundanentats
CauseMannl

Modular
Code
The followingguidelineshelpwhenprogramming
in LabVIEWFPGA:
. Segment
yourLabVIEWFPGA into functionblocks(subvls)*allows
you to developandtesteachindividualfunctionblockin parallel.
. Simulateandtestyour LabVIEWFPGAcodepdor tc
compiling allowsyou to takeadvantage
ofthe parallel
processing
natureof FPGAs.
Whenyoudevelopsubvlsfor LabVIEWFPGA,makesureyoukeeptheVO
outsidethe subvls.This creates
moreefficientLabVIEWcodeandalso
allowsyou to testyoul subvlsin Windowswithoutcompilingthe
LabVIEWFPGAcode.Youcanaccessall theLabVIEWdebuggingtools
within Windows,suchashighlightexecution,
prcbes,breakpoints,
andso
on, to troubleshoot
your LabVIEWFPGAsubvls beforcyou compile.

Creatin0
anFPGA
Vl FrontPanel
Createthe front panel for FPGA applicationssimilar to the one shownin
Figure5-14.lt is a goodideato setdefaultvaluesfor controlssuchasthose
shownbecause
theFPGA VI is not controlledfrom a monitordisplay,but
raLherthroughtheRT hostVI. The front panelcontrolsandindicatorc
automaiicallycofrmunicatewith the RT host,asexplainedin the
PrcgrafituaticFrontP.tnelCommunication
section.Remember
thata host
VI servesasthe userintedaceandthattheFPGAhaslimited memory.So,
keepthecontrolsandindicatorcon thefrontpanelofan FPGAVI simpleto
conservespaceandenhalceperformance.
Youmightaddsometemporary
controlsandindicatorsfor testinsthatvou removelater.

ConpactBlqandLabVlEW
Fundanentats
Cousellanual

=t
h,

rdt

il
h

r{t

F
=3
=3
-

r{'
{

r{t

I
E1

{l
E

fl
-

rt
-l

{t
{

panel
Figure
5-14.Temperature
lvlonitor
FPGA
VlFront

E.Testing
withtheDevelopment
Machine
Because
compilingLabVIEWcodeto run on theFPGAchip takesfrom a
few minutesto severalhours,LabVIEWhasthe abilityto run thecodeon
thedevelopment
machinerc verify thelogicbeforeyou initiatethecompile
process.FPGA coderunningon thedevelopment
machineaccesses
I/O
from the deviceandexecutes
the VI logic on theWindowsdevelopment
computer*,heretraditionalLabVIEWdebugging
toolssuchasexecution
highlighting,probes,andbreakpoints
areavailable.
Whenyou run anFPGAVI on thedevelopment
machine,LabVIEW
generates
randomdatalbr theinputsor downloadsa pre-compiled
emulationVI to theFPGAtargetto provideI/O. If you useI/O from the
FPGAtarger,LabVIEWcommunicates
with the VI on rheFPGAtarget
whileboth VIs run.Youmusthavesupportfor an FPGAtargetinstalledto
useandevelopment
machine.The availabilityofthe development
machine
variesby FPGA target.Referto thespecificFPGAtargethardware
documentation
for informationaboutdevelopmcnt
machinesupport.
Completethefollowingstepstousea development
machinetotestanFPGA
VI:
1. Right-clicktheFPGATargetin theProjectExplorerandselectExecute
VI on>Development
Computerwith SimulatedVO.
2. Right-clickFPGAandselectProperties>Debugging.

rd

ry
A NalionallnstrunentsCorporation

5-27

Canpattql0andLabvlEW
Futuanentats
CouseManual

l, fPGt rdreel Properries

'

O Exd.lte VI on FpcA rdfqer


('lEre.utevr oi Deveopneircompltefwth shurtadtlo

_-lf{-*d
o|,
Ii- H"d t

Figure5-15. FPGA
Properties
i0r Emulati0n
I\lode
You canDottest ce ain behavior,such as tilning and delerminism,wilh a
dcvelopmentmachinebecausethe FPGA VI runs on the host coriputcr
irslead of tlre FPCA.

F. Interaclive
Fronl
Panel
Communication
Becausethere is no monitor connectedto the FPGA, you must view the
output and provide input from a host computer You can use Intcractive
Front PanelCommunicationto communicatewith an FpGA VI running on
an FPGA targetwith no additionalprogramning. With IntefacriveFront
PanelCommunicalion,rhehostcomputcrdisplaysthc FPGA VI tiont panel
window and thc FPGA targetexeculesthe FPGA VI block diagram,as
shownin Figure5-16.

ConpdclRt0end
LabVtEW
FLndanentals
CouseManuat

528

Figure
5-16,Interactive
Front
Panel
C0mmunication
TheLabVIEWftont panelwindowcommunicates
with theFPGAtarget
blockdiagramto excbange
thestateofthe conrolsandindicators.Youcan
communicate
with an FPGAtargetlocatedon thehostcomputeror with an
FPGAtargetlocated
on arcmotesystem.As theFPGAtargetblockdiagram
continuesto run,the hostcomputerupdatesvalueson theFPGAVI front
panelwindowasoftenaspossible.
Theexecution
rateofthe FPGAVI is not
affectedby thehostcomputerupdates
to thecontrolsandindicators.The
frontpaneldatayou receiveduringInteractive
FrontPanelCommunication
is not deterministic.
UseInteractive
FrontPanelCommunication
betweentheFPGAtargetand
thehostcomputertocontrolandtestVIs runningon theFPGAtarget.After
downloading
andrunningtheFPGAVI, keepLabVIEWopenon thehost
computerto displayandinteractwith the lront panelwindowof the
FPGAVI.
DuringInteractive
FrontPanelCommunication,
you cannotuseLabVIEW
debugging
tools,so testwith thedevelopment
machineand/oradd
temporarycontrolsandindicatorsfor debuggingandremovethemafter
testrns.

@National
lnstrunengCorpontion

ConoactBlo
andLabVlEW
Fundanentals
CauseI\lanual

Exercise
5-1 BuildandTestanFPGA
Vl
Goal
CrcateanFPGAVI thatreadstemperature
fromtheNI9211 andtestit with
the development
machinebeforecompiling.

Scenario
The tirst phaseof theconditionmonitoringprojectis to monitor
temperature.
The FPGAacquirestempemture
datafrom a J-type
thermocouple
connected
to theNI 9211module.The FPGAcommunicates
with theRT hostVI runningon theCompactRlocontrollerwith Interactive
FrontPanelCommunication
overthe PCI bus.The RT controllerVI
processes
dataandcommunicates
with a WindowshostPCthatprovidesfile
yO andHML Youhavebeenassigned
thetaskofdesigning,implementing,
andtestinstheFPGA VL

Design
Monitortempemture
continuously
in a loop.Because
temperature
vades
slowly,usea loop delayto time the applicationto avoidcollecting
unnecessarily
largevolumesof data.The userinterfacecontainsa loop
delayconffolwhosevalueis communicated
from the WindowsPC to the
RT conhollerandthento theFPGA.
Usea Flat Sequence
stnrctureto implementthetime-delay,
acquire
sequence.
The first frameofthe structurctimestheloop andthe second
acquiresthethemocouplesignal,CJCvalue,andAutozerovalueandwrites
themto indicators.
Implementtheapplicationin the generalVI architecture.
Table5-4liststhe
front panelobjects.

Table5-4. Temperature
ftilonitor
Vl Inputsand0utputs
FPGA
Tlpe
Numericcontrol

Name
Thermocouple
Th i arrri

Properties
Sample

l2-bit Unsigned
Tnreger.
defaulr= 500m.

Sigmal

Fixed-point<!24, -2>, default= 0

/mqa-\

Numericindicator

Thermocoupfe

Numericindicator

cJc

Fixed-point<!24, -2>, default= 0


Fixed-point<!24, -2>, default= 0

Numericindicator
Erlor Out

FPGA error

ou!

Conpa.tqlo
andLabvlEllFundanentals
Course
Manual

Error Cluster

lmplemenlalion
1 OpentheTemperature
MonitorProjectyou developed
in Exercise4 2,
Acquire TemperatureData From an I/O Variable.

2. Changethemodeof operationfrom scanmodeto FPGAmode.


D Right-clicktheScanInterfaceTemp.viandselectRemoveFrom
Project.
E TheRemoveItemsdialogbox appears
to verify removalof theVI
from theproject.Click OK.
O Right-clickthechassisandselectNeW>FPGATarget.
The DeployCompactRloChassisSettingsdialogbox appears
ro
verifythatyouwantto put thechassis
in LabVIEWFPGAInterface
mode.This changewill occurafteryou deploysettingsto the
chassis.
Click DeployLatr.
B ExpandtheFPGATarget.
O Click eachmoduleanddragit ro theFPGATarger.

A National
lnstru
nentsCoryanon

C,npactRIO
andLabVlEW
fundanentalsCawseManual

0 YourProjectWindowshouldnow be similarto Figure5-17.


- rmp.'.rMeMon'$...
p,.Jtrrpro,er
lJ-trlEl
Ee Edt ylea Prcta.t qFqare look !4rndow Eep

I o.]]rJ tt x ' i l

XlrltJlir@-t" :

Prcjed:
Tenperature
I'lonilor,vpror

3.Rro e01r(10.14.0.r1
I E .hBlGRro elm)
la,eet(Rro0,.Rro'er03,
Dev.ompura)
i. g FPca
i, !

Modl

!,
I
i
I
:

Mod3
{o MH?onbolrdc ock
Modr(sot r, Nrsar)
Mod2lsot
2, NI9233)
Mod3(sot3,r ez63)

J
S
fi
fl
||

, ili r!,ir6a*rrF!'rorai!lia*d!

1t

Figure
l\40nitor
Project
5-17.Temperature
3. Add theFPGAVI to theTemperature
MonitorProiect.
O Right-clicktheFPGA Target andselectNew>VI.
D SavetheVIas <Exercises>\compacERTo
Fundamenlals\
- re!dL r!e

Monitor

|PGA.vi.

B Savethe project.Notice that the FPGA VI appearsunderthe FPGA


target,as shown in Figure 5-18.

CanDactqlo
andLabVlEW
fundanentals
Cource
lilanual

lI pioje.r txpldl - Lmi'idl;tum i{dfti,:.. l-,


Ere Edit !6w gojed qsdt.

x tr

.l'ioC

took lzindM Eerp

Xl tJrtrtr-ls :

Pfdied lemFeralur
e Montor lvprot

.
i:

r)
oo.'4.0
s|(Rro-eol,
a chsiscRro-erm)

rdset (Rro0,.Rro-er03,Dd compulef)


:. B FPGA
c h a s i 'V o
.,
i ;l |iodr
.: ;J Modz
j ;J Mod3
h aoMtszonbNd c o.k
; I
Modt(slot1,NI92tl)
:.lt
Mod2
6rotr, Nrs23o
(slot3, NI9263)
Mod3
i I

, 4.,l.*rii*$Fr.h$A'tca{&
i '*t Butd5ptrirratoF

Figure
5"18.FPGA
Vl intheTemperature
lMonitor
Projecl
Explorer
Window

youbuildtheblockdiagram
ln thefollowingsteps
shownin Figure5-19.

Iite v. (hse4

,r=aj
!al?l

Figure
5-lg.Temperature
lMonitor
FPGA
VlBlock
Diagram

Tip Remember
to saveyourworkfrcquently
asyouworkthroughtheexercises.
4. To readthe thermocouple
signal,expandtheThermocouplfolder
undertheFPGAtargetanddragtheModl/TC0 FPGAUOchannelfrom
theProjectExplorerto theblockdiagram.This createsan FPGAVO
Node that readsthe thermocouple.

@Nationat
lnstrunenECorpontion

ConDactBl1
andLabvtEW
fundanentals
CouseManual

5 . ReadtheCJCandAutozeroValues.
D Createtwo additionalelementsin theFPGA I/O Nodeby
right-clickingtheThermocoupleterminalandselecring
Add
Elementtwice,or by resizingthe node.
E The terminalsshoulddisplaythe CJCandAutozeroitems.If not,
click the terminalandselectModI>CJC or Modl>Autozero.
6.

Createindicatorsfor front panelcommunication


with theRT host.
f,l Right-clickeachof rheoutputterminalsin theFpGA I/O nodeand
selectCreate>Indicatorfor eachterminal.
tr LabeltheindicatorsThermocouple sisnal, cLTc,
andAutozero
as appropriate.

'7.

Add Enor Handling


O Right-clicktheFPGAyO NodeandselectShowError Terminals.
tr

Right-clicktheerrorout outputandselectCreate>Indicator.

Labelthe indicatorFpcA er:ror our.

8 . Implementcontinuous,
tiDed acquisition.
yO Node
tr Add a Flat Sequence
structurearoundtheThermocouple
andildicatorson theblockdiagram.
O Right-clicktheleft borderof theSequence
structureandselectAdd
Frame Before.
tr Add a Loop TimerVI to the fi$t frameof theFlat Sequence
suucluIe.
Q SettheCounterUnitsto msec andthe Sizeof IntemalCounterto
32 Bit in theConfigureLoopTimerdialogbox.

Click OK.

Right-clicktheCount(msec)inputterminalandselectCreate>>
Control.

Label the COntrOlThermocouple

tr

Add a While LooparoundtheSequence


structure.

Conpact?l1nl LabVlEW
fundanentals
Cou6eManul

5-U

Sample

Interval

(msec).

Lesson5

tr

Wire a Falseconstantto the conditional terminal.

On the front panel,set the value of the ThermocoupleSample


lnteryal (msec)control to 500, and then selectthe control,
right-click and selectData Operations)Make Current Value
Default.

.PGA

9. Changethe displayformatofnumericindicators.
tr Right click theThemocoupleSignalindicatoron the front panel
andselectDisplayFormat.
O ChangetheDigitsto 4 andthePrecisionTypeto Significantdigits.
tr Click OK.
E Repeatstep9 for theCJCandAutozeroindictors.
1 0 .Arrangetheconholsandindicatorson the frontpanelasshownin
Figure5-20.
1 1 .Setthedefaultvaluesfor thecontrolsandindicatorsasnotedin
Table5-4.

Figure
5.20.Temperature
lMonitor
FPGA
VlFront
Panel
12. Savethe VI and the project.

@Natianal
lnstrunenECaryontion

5-35

ConpactBl'andLabvtEW
fundanentalsCaurse
Mdnual

Test
I

TesttheVI with simulatedVO.


tr Right click theFPGA Target in theProjectExplorerandselecr
ExecuteVI on>DevelopmentComputr with Simulated VO.
0 Run theVI.
O ObservethattheThermocouple
Signalindicatorvaluesvary
randomly.

2 . Experimentwith the debuggingtoolsin emulationmode.


O While theVI is still running,adda probe.
Q Tum on executionhighlighting.
El Removetheprobe.
D Tum off executionhighlighting.
D StoptheVI with theAbort button.
tr ClosetheVL
3. Tum rheDevelopmenr
Compulerofl
O Right-clicktheFPGA Target in rheProjectExplorerwindowand
selectExecuteVI on>FPGATarget.
O CtickOK.

Endol Exercise
5-1

ConoactBloandLabVtEW
fundanentalsCourse
Manual

=r
=3

ir
P
h

rtt

B
h

r{
h.

theModules
G.Wiring
To connectphysicalwiresbetweensensoNandactuators
andthe
for eachmoduleCompactRlomodules,referto theoperatinginstructions
For example,thet'V1921IOperatingltlstructior,rexplainthattheNI 9211
hasa lo-terminal,detachable
screw-terminal
connector,
shownin Table5-5,
prcvides
that
connections
for four lhermocouple
inputchannels.
Each
channelhasa TC+ terminalthatconnects
to thepositiveleadof the
thermocouple.
anda TC terminalthatconnectsto the negativeleadof the
thermocouple.
TheNl92l I alsohasa commonterminal(COM)thatis
internallyconnected
to theisolatedgroundreference
of themodule.Ifyou
areusingshieldedwiring,connectoneendofthe shieldto the COM
Lermlnat.

r{t

Table
5-5. Nl9211lvlodule
Trminals

r{t

Module

Terminal

Signal
TC0+

b.

rdt
:{t
h

r{
b

r{

TCO_

T C l+

TC1

TC2+

TC2

TC3+

TC3

r{l

No connection

dt

=3
-l

r{,
r{t
h

Common1COM.1

As shownin Figure5-21,theNI92l I channels


sharea conrmongroundthat
is isolatedfrom othermodulesin thesystem.Eachchannelhasimpedance
betweentheTC+ andCOM terminals,andbetweentheTC andCOM
terminals.Eachchannelis filtered,andthensampledby a 24-bitADC.
Thereis a currentsourcebetweentheTC+ andTC- terminals.If an open
thermocouple
is connected
to thechannel,thecurrentsourceforcesa
full-scalevoltageacrosstheterminals.

i{,

=D
-tt
-tt

tnstrunenECotpotdtion
@Ndtional

5-37

CanwtqlqandLabvlEwfundanentals
CauseManual

hpedance

Thsrmocoupte Dilterential
Deteclion
Cufieni

ADC

usB-9211/9211A

Fiqure5-21. N19211
Internal
Circuitry

H.Compiling
theFPGA
Vl
Whenyou completethecircuitwiring, youcantestthe system.Youmust
compileanddownloadthe FPGA.Click theRun buuonro initiatethe
process,
or manuallylaunchtheLabVIEWFPCA CompileSeNerby
selectingStart>All Programs>NationalInstruments>LabvlEw 8..x>
LabVIEW FPGA Utilities>CompileSeryeron the remotecompurer
By default,theFPGAclockrunsat40 MHz. This meansrharonetick ofrhe
FPGAclockis 25 ns.By changingthecompileoptions,youcanincrease
the
FPGAclock speedup to 200MHz (5 ns).Therearcsomedrawbacks
to
usinghigherclock speeds
thatyou shouldbe awareof beforechangingthe
compileoption.Formoreinformation,referto theCompactRlOTechnical
Developers
Libraryat ni. com/compactrio.
Thecompileprocess
convertsthegraphicalcode
to VHDL code,generating
intermediate
files,anddisplaysthewindowshownin Figure5-22.Thenthe
Xilinx ISE compiletoolsoptimize,reduce,andsynthesize
the VHDL code
into a hardwarecircuitrealizationofthe LabVIEWcode.The endresultis
a bitstreamfile thatis loadedinto theFPGAchip to configurethegatearay
logic.

Conpac:tqljandLabVlEW
fundanentats
Caurse
Manual

F
P
P
F
F
P
F
F
F
F
F
L.,

l'

FD

Figule
5-22.Generating
Intermediate
Files
Window
The CompilingVI for FPGAdialogbox, shownin Figure5 23, displays
statusinlbrmationwhile theFPGAVI compiles.Fromthis dialogbox you
cancancelthecompilation,or disconnect
from theLabVIEWFPGA
CompileSeNertocontinue
workingin LabVIEWwhiletheservercompiles
the FPGAVl.
This dialogbox includesthe followingcomponents:
. Client ID-Displays a uniqueID thatis associaLed
with theVI thatis
beingcompiled.
. ServerID Displaysthe ServerSeryiceID on the sefr'erside.To
view previouscompilerecords,launchtheLabVIEWFPGACompile
Serverby selectingStarbAll Program$National Instruments>>
LabVIEW 8.6>LabVIEWFPGA Utilities"CompileServer.Click
theCompileList button,andentertheServerID in thenumericcontrol.
. Status-Displaysthestatusof thecompilationthroughoutthe process.

L-

Refresh Updatestheclientwiththelatestinfomationfromtheserver
Ifyou donotclicktheRefreshbutton,youexperience
a 2o-second
delay
betweenupdatesfrom the server

F
F

Disconnect Disconnects
LabVIEWfrom theLabVIEWFPGA
CompileServerwhilethe LabVIEWFPGACompileServercompiles
the VI. Disconnect
from theLabVIEWFPGACompileServerto
pedormotheroperations
in LabVIEWwhiletheFPGAVI is compiling.
To reconnect
to theLabVIEWFPGACompileServer,right-clickthe
FPGAVl in the ProjectExplorerwindowandselectReconnectto
Compilation.Youalsocanreconnect
to thecompilationby clickingthe
Run buttonon theFPGAVI or usingtheBeginningCompiledialog
box.

l'
h

!{,

i-

t'=t
-!t
-

-t

A Nabnallnstrunents
Caryonton

539

ConpactqloandLabvlEWFundanentals
Cou$ellanual

Ca0lion Do ro, makechangesto theFPGAVI while theLabVtEWFPGA Compile


SeNeris compiling.If you do makechanges,
you mustrecompiletheFPGAVl.
.

Stop Compilation Stopstl'reLabVIEWFPGACompileServerand


closestheclientwithoutfinishingthe compilation.

Figure
5-23.Compile
Activity
Window
The LabVIEWFPGA CompileServer8.5window,shownin Figure5-24,
displayscompilationinfomationwhenyoucompilea VI. You alsocan
launchtheLabVIEW FPGACompileSenermanuallyby selectingTools>>
FPGA Module>StartLocal CompileServer.TheLabVIEWFPGA
CompileServerdoesnotcloseautomatically
whencompilationfinishes.
Click theStop Serverbuttonto closethewindow.

ConpadBlAandLabVlEW
Fundanentals
Cou\eManul

5-44

abntName

statur

tajtlpdarenme

doet nDtdlr dn! oddp'E n tre desqn


s q n a d i e ! i d l d r v e d n r o B d F n sn t h e c E l i q n
$ v / n ' l I f l a n t r p e v e _ q ain'
5avn0br strean n topraveoei.bf
toplevetqen.'br ,
5a!.q ma5kbtn,edmin top*ve qe..m5f'

;-..,',f,-

l=.,*;*

-'l

Figure5-24. Complle
Srver
Window
The LabVIEW FPGA Compile Servcr Window containsthe following
componcnts:
.

Compilc Status Displayssrarusinfonnarionfor the currentcompjle.


Thc Conlpile Statussectionis disableduntil the compile begjns.
- Server Service ID-Displays a number.thalis assocjatedwilh thc
VI you ille compiling.To view pastcompiles,clicktheCompileList
butlon. and cnter the Scrver SeNice ID in the numericcontrol to
view the compilatjon repofl.
Client Namc-Displays the numeof thc computeron which tbe
FPGA VI resides.
Client Service ID-Displays the ID thar is associatedwirh the VI
thatis beingcompiled.
Status-Displays the statusol the compiliLtion.Statusupdates
throughoutthe compilation.
Start'fime
rhc Vl.

A ibio na]Instunenls Cuporalnn

Displaysthe rimc thatlhe serverstartedcompiling

Last Update Time-Djsplays the time that the Compile Status


infbrmation was last updated.

Details-Displays infbrmation aboutthe conversionof the VI into


thc bitstreamrhat is downloadedto tbe FPGA.

Canpr tRIAandLabvIEWf t)ndanentats


Co utsettanLat

StopCompile*Cancclsthecun-entcompile.This buttondoesnot shut


downtheLabVIEW FPGACompileServerwindow.
CompileList-Displays theMarlageAll ServerRecordsdialogbox,
whichyou canuseto browseall pastcompilesandcurent compilesin
thecompilequeue.YoualsocanusetheManageAll ServerRecords
dialogbox to deleteinfornationaboutold cr unwantcdLabVIEW
FPGACompileSelvercompiles.
ServerStatus Displaysthestarusof rheLabVIEWFPGACompile
Server.
StopSeryer-Shuts downthe server.Stoppingtl.leLabVIEWFPGA
CompileServercancelscurrentcompilations.
.

Configure-Displays the Configure Serverdialog box. Use the


ConfigureServerdialog box to configute propefiiesfor rhc LabVIEW
FPGA Compile SeNer.You can fix timeout eflors that appearwhen the
LabVIEW FPGA Compile SeNer sendsor receivesfiles by incrcasing
fte Network timeout (ms) value.Modify the Pon number if the default
pon, 96, conflicts with ports on the network. Ifyou modify the poft
number,you must modify it in the ConfigureSeNer dialog box and in
the ConfigureCompile Settingsdialog box.

The SuccessfulCompile Report dialog box, shown in Figure 5-25, reports


the rcsultsofthe compile process.The first line displaysthe statusor resuil
ofthe compile,whetheror nol the compile was successful.Ifthe programis
too big or ifthe clock speedis set too high, it may not be successful.

Starus

C.hFrlatro!

aonFrtatr.n

successfrl

Sunnary

Dwlce llrrll:arron
Sunfrary
xuiber
of EUICUUI:
Ixabe!
.f E?lerEl
IOBS
,lnhber .I loced IOES
Iuhber
ol SlIaEs

2 our
106 out
10'!.ut
110! our

Clock Rates: (Fequesred rar6


are adrusrrd
Base .]o.L
40 l{Hz onb.ard
Clock
RequesredRar,!0,!0B933UItz
Theorerlcal
Ualiftur
33 243153U92

ior

ot
of
of
of

I rrrer

16
r2Z
4s4
2!/_
106
r00U
14336 7;
ard accura.r)

]2 P)I

:i

-,,.,-.... 1
t- !!tq J

Figure
5-25,Successful
Completion
Rep0rt
Window

Conpactq
l0 andLabvlEWFundanentah
CDu6eManul

P
F

E
F
F
l-.

r
l>

E
f
f

rf'
h

f'

F
F
F

Lesson
5

FPGA

The reportshowstheresultingFPGAcircuitusesabout67oof theslices.


This dialogbox includesthefollowinginformation:
. Summary-This tabcanincludethe followingcategories
oI
information:
- DeviceUtilizationSummary-Mighr conrainthe following
i nfbrmation:
. Number of slices-Specifieshowmuchof theFPGAlogicthe
compiledFPGAVI uses.Slicesarea combinationofLUTS
and FFs
. Number of IOBs-Specifies thenumberof Inpuroutput
Blocksused
. Number of MULTl8Xl8s Specifieshow manvmulripliers
the compiledFPGAVI uses
. Number of RAMBl6s-Specifies how muchRAM the
compiledFPGA VI uses
. BUFGMUXs-Ponal to rheclocknet.which is usedro
clock FFs

Clock Rates-Might containthe followinginformation:


. RequestedRate Displaystheclockrateat whichthecompiled
FPGAVI runs,whichis 40 MHz by default
. TheoreticalMaximum-Displays thetheoreticalmaximum
compile rate for the FPGA VI
Advanced This tab includesthe xftow. tog and . tv,/r files.

If you havepreviouslyselected
the Do not showthis message
in the
future? checkboxyou will no longerseethecompilereport.To re enable
thecompilerepoftyoumustmodifytheLabVIEW . ini file. Makesurethe
line nirvishori/CompileReports=TRUE
existsin the , ini file.
Forsmallapplications,
thecompilerdoesnotoptimizeascompletelyasfor
largerapplications.
As theFPGAreaches9070optimization,thecompiler
pedormsheavyoptimization.

-r

irlt

F
b

l*
h

-t
rdl

After you click OK in the Successful


CompileReporrdialogbox, rheVI
runson theFPGA andcommunicates
with theWindowspC through
Interactive
FrontPanelCommunication.
Datafor thefrontpanelobjectsare
communicated
overtheCompactRlobusto thecontoller andoverthe
Ethemetto thehostPC severaltimesper second,typicallyaboutl0 S/s.
To viewpreviouscompilereportsfrom theProjectExplorerwindow,select
Tool$FPGA Module>StartLocal CompileServerto displaythe
LabVIEWFPGACompileServerwindow.Click rheCompileList butron
to displaythe ManageAll ServerRecordsdialogbox.
A NaionallnslrunenlsCoryaftlion

543

ConoactRlo
andLabVlEW
fundanentats
CouBeManual

l. Downloading
to Flash
Memory
After youcompilelhe FPGAVI, you candownloadit to tlashmemoryon
anFPGAtargetandconfiguretheFPGAtargctto automatically
loadtheVl
whenthedevicepowerson. This makesFPGAVIs easyto distribute.You
do not needLabVIEW or theLabVIEWFPGAModuleto downloadand
contlgurethe loadsettingsfor theVI. All youneedis theLabVIEW
Run-TimeEnginefor 8.2or later.
Completethe followingstepsto downloada VI to flashmemoryon thc
FPGAtargct.
l. Right click thc FPGAtargetin the ProjectExplorerwindowandselect
RIO DeviceSetup.The RIO DeviceSetupdialogbox,shownin
Figure5-26,appears.
Or selectStarbAll Programs>National
Instruments>NI-RIO>RIO
DeviceSetupto displaythe RIO DeviceSetupdialogbox. Whenyou
displaythe dialogbox in this manner,you mustselecttheFPGAtarget
to whichyou wantto downloada bilfile from the Devicepull down
menu.

Figure
5-26.Rl0Device
Setup
Dialoq
Box

CanpactqlA
andLabVlEW
Fundanenkts
CouseManual

Lessan
5

FPGA

2. Browseto or enterthepathto the bitfile you wantto downloadto the


flashmemoryon theFPGAdevicein theBitlile to Downloadpath
control.
3 . Click the Download Bitfile button.
4. On theDeviceSettingstab,selectAutoloadVI on devicepower up or
AutoloadVI on deYicereboot.
5 . Click theApply Settingsbutton.
o . Click Exit.
loadsto the
TheFPGAVI youdownloadto theflashmemoryautomatically
FPGAon theFPGAtarget.
TheRIO DeviceSetupdialogbox includesthe followingcomponents:
. Resource-SelecttheFPGAdeviceto whichyou wantto downloadthe
remotedevicedoesnot appearin the Device
bitfile. If a connected
pull-downmenu,enableVISA to find RIO resources
on theremote
system.
. DownloadBitlile to Flash-Includesthefollowingcomponents:
Bitfile to Download-Determinesthebitfile to downloadto flash
memoryon the FPGAdevice.The VI mustbe compiledfor the
device.
DownloadBifiile
device.

Downloadsthebitfile to flashmemoryof the

EraseBitfile on Flash-Deletestheexistingbitlile on the flash


memoryof the device.Downloadinga newbitfile alsodeletesany
existingbitfile.
.

aNa onallnstrunentscotpotation

DeviceSettings Includesthefollowingcomponents:
- Load VI from FlashMemory-Determineswhenthebitfileloads
ro lheFPCAlromflashmemorJ.
. Do Not Autoloadon Reset Doesnot loadthebitfile from
flashmemoryat stanup.
. AutoloadVI on devicepower up-Loads thebitfile thatis
up.
storedin flashmemoryto theFPGAwhenthesystempowers
. AutoloadVI on devicereboot-Loads thebitfile thatis slored
in flashmemoryto theFPGAwhenyourebootthesystemeither
with or withoutcyclingpower.

5-45

Fundanenhls
Course
llanual
ConpactqtoandLabVlEW

Analog Input Mode-Determineswhichmeasurement


systemthe
downloaded
bitfile uses.This optionis availableonly for analog
inputdevices.
Differential-Uses a measurement
systemin which youdo not
needto connecteither
inputto a fixedreference,
suchasearthor
buildingground.
ReferencedSingle-Ended-Usesa measurement
systemjn
which all measurements
aremadewith resDecl
ro a common
referenceor a ground.
NonreferencedSingle-Ended-Usesa measurcment
systemin
which all measurements
aremadewith respectto a common
rcference,butthevoltageat thisrefercnce
canvary with respect
to the measurement
systemsround.
SynchronizeFPGA Clock to PXI_CLKl0-Phase locksthe
NI 78-IJRclockto the 10MHz clockof rhePXI chassis.
This oprion
is availableonly for NI PXI-78-rrdevices.
Nole This settingdoesnot tal(eeffectuntil you resetthedevice.
.

Apply Sttings-Downloadsthe settingsyou configured.

Eventhoughthe VI loads,it doesnot run automatically.


Verify thatthe
FPGAVI is compiledwith theRun when loadedto FPGA oprionif you
wanttheVI to run automatically
whenit loadsto theFPGA.
Completethe followingstepsto automatically
run anFPGAVI thatis
loadedfrom flashmemorywhenyou poweron an FPGAtarget.
1 . Right click rheFPGA Targetin theProjectExplorerwindowandselect
Properties.The FPGATargetPropefties
dialogbox appears.

2. In theFPGATaryetPropefties
dialogbox,placeacheckmarkin theRun
whenloadedto FPGA checkbox.
3. Click OK. All FPGAVIs youcrcatefor rheFPGAtargetwill run when
loaded.

J. UsingLabVlEW
FPGA
withCompactRl0
ScanMode
Startingwith LabVIEWReal-Time8.6,youcanaccess
eachmodulewith
eitherCompactRlOScanModeor LabVIEWFPGA.UsingLabVlEW
FPGA,youcanimplementcustomtrigge ng,hardware-based
analysisand
signalprocessing,
or high-speed
analogstreaming.
lfyou havebeen
operatingin scanmodeandwishto useI/O modulesin LabVIEW FPGA
Modeinstead,simplydragthemodulero rheFPGArargerin theLabVIEW
Project,removingit from scanmode.ThenuseLabVIEW FPGA to program

Conpactql0andLabVlEW
Fundanenlab
Cjuse Manuaj

5-46

F
F

Lesson5

FPGA

themodulesanduseI/O variablesto readandwrite VO on the remaining


modules.

F
F
F

Eh

Edt

lbw

gdjed

Sd.t6

]dds

gindd

Eetp

ll;:.:(3#x),.: X lid:tr R-r',

F
F3
Ih

lrdl

L_

tlf'

& chssEienedatue
i'4, seep

f,t Mnd2
; a, Modr/aro
: A Modriall
i A Modr/al
-A Mod4AI3
I it MDdr/5rar
&, ffodr/5r"p
:.5J Mod3
: i &, nod3/aoo
: i i, Mod3iAor
, A, Mod3/Ao,
,. a Mod3/Ao3
S {o ftiiz onboadc dk
i ll r'1o&(slot2, NIt3r)
(srot3,Nrer63)
It Mod3
.!
:
i
r

l{

L-

f.,
E

i-{t
h

fl

tt
Figure
5-27.Using
LabVtEW
FpcA

r{t
rt|t
h

r{,
h

-t

Whenyou useLabVIEWFPGAwith CompactzuO


ScanMode (some
modulesusingCompactRloScanModeandsomeusingLabVIEW FPGA
Mode),theCompactRloScanMode logicandthe FpcA VI arecompiled
into a singlebitstreamanddeployedto theFPGA.you canthenaccessVO
modulesin LabVIEWFPGAModewirhrheFPGAInterfaceVIs andaccess
yO modulesin scanmodeusingVO variables.
Ifyou removeall the
modulesfrcm scanmode,thentheCompactRloScanModelogic,known
asthe zuO ScanInterface(RSI),is not comDiledinto thebitstream.The

-t
h

-t

@l! ionallnstrunentsCorpontion

5-47

ConpactRlq
andLabVlEW
funhnentals CouBeManht

spaceconsumed
by RSI on theFPGA scaleswith thenumberof modules
usingscanmode.
Thesizeof thedefaultbitstreamusedin compilingtheRSI logicis roolafge
to fit on a 1M gareFPGA(forexample,
theNI9l0l, NI9102,or theNI9072
chassis).
Ifno compileoccurs,thatis, ifno FpGA codeis developed
andall
modulesin theprojectarebeingusedin scanmode,thenthe defaultRSI
bitstreamwill beusedfortheFPGA.Thisis why scanmodeisrlotsupported
outof thebox for controllerswith lM gateFpGAs.However,ifFPGA code
is developed
andcompiled,thenonly theRSI functionalityneededfor the
modulesbeingusedin scanmodewill be includedin thebitstream.
As long
asthecombinedFPGAandRSI bisrreamis smallenough,CompactRlo
ScanModecanbe usedwith conffolle$with lM gateFpGAs.

When
T0ljseFPGA
M0deInstead
0fScanMode
CompactRloScanModeis designedfor applications
requiring
yO updatesat ntes ofup to I kHz. Youcanusethe specialty
synchronous
digitalfunctionalityprcvidedby scanmodeto convertanyexisting
eight-channel
digitalVO moduleinto an advanced
PWM, counter.or
quadrature
encodermodule.With theVO forcingandtestpanel
functionalityofthe systemmanager,
youcanalsousescanmodefor initial
setup,systempedormance
monitoring,andadvanced
troubleshooting.
For
applications
with higher-pedomance
requirements,
suchasanalog
streaming
at nearlyI MHz, high-speed
PID controlloopsfasterthanI kHz,
customhardwareanalysisandsignalprocessing,
or I/O modulesnot
supportedby
scanmode,usetheLabVIEWFPGAModulewith scanmode.
You can also offload processingfrom the real-time controller with the
LabVIEWFPGAModule. Thedecisionto useFPGAmodeor scanmode
shouldbe madeon a per-module
basis.Reierto themoduledocumentation
for informationaboutscanmodesupport.
Therearesomeperformance
trade-offswhenusingCompactRlOScan
Mode.Forexample,thespecialtydigitalfunctionalitysupports
upto I MHz
counters
versusthe20MHzcountersachievable
with LabVIEWFPGA.The
scanengineusessystemresources,
which includeFPGAspace,two DMA
channels,
memory,andan amountof CPUtime thatscaleswith the scan
rate.

C1npadqtAandLabVlEW
fundanentats
Cou$eManuat

548

P
P
P
F
F
F
F
I

tr3
I

P
lh

ll!-

Exercise
5-2 Compile
andTestanFPGA
Vl
I
Goa
Compileandtesta simpletemperature
monito ngapplicationon theFPGA.

Scenario
Youpreviouslydeveloped
a simpletemperaturc
monitoringFPGA Vl and
testedit with thedevelopment
machine.The FPGAVI continuously
acquiresa themocouplesignal.Now,you havebeenassignedthetaskof
compilingtheVI andtestingtheapplicationrunningon an FPGA.

Design
Usethe ProjectExplorerarchitecturc
andfrontpanelobjectsfrom
Exercise5-l.

lmplementation
l. Compilethe VI on theFPGA.
El Openandrun theTemperatureMonitor FPGA VI to startthe
compileprocess.

lh

E Observetheinformationdisplayedduringthecompileprocess.
Whencomplete,theSuccessful
CompileRepofidialogboxdisplays
informationabouttheprocess.(tt might Lakel0 minutesfor the
compileto complete.)
Recordthecompiletime andthe SLICEs
percentage
below:

f'
Lr

!{,
h,

r{t
ts
dt

CompileTime:

rig

SLICEs:

D ClosetheLabVlEWFPGACompileServerwindowandrhe

r{t

Successful
CompileRepoitwindow.

='
h

-t
h

rttl
:{

-t

@National
lnstrunenECoryontjon

5-49

ConpactBto
andLabvtEW
fundaneniahCowseManul

Tesl
]. Testtheapplication.
0

At theendof colnpile,theprogramshoulddownloadandtheFPGA
shouldbeginto reportthermocouple,
CJC,aridAutozerodatausing
InteractiveFrontPanelCorfnunicationto the PC.lfit doesnot,
click the Run buttonagain-

tr

Observethethermocouple
signalasit stabilizes.

tr

Grip the thermocouple


b efly andgentlybetweenthumband
forefingerto watchthe signalvaluesrise.

tr

Release
the thermocouple
andwatchthe signalvaluesdecline.

tr

Recordtheapproximate
rangeofthermocouple
signalvaluesbelow
Youwill comparethesewith datayou collectin Exercise6 1,Build
and Testa SimpleRT Host VI.

Changethevalueof theThemocoupleSampleTimecontrolto
250 ms andobservetheincreased
samplingrate.

youwill
ClicktheAbortbutton to stoptheFPGA.In laterexercises,
controltheFPGA VI startandstopftom PC controlsinsteadofthe
Abort buttonlater.

Endof Exercise
5-2

ConpactBlqandLabVlEW
fundanentals
Course
Manual

5-50

SelfReview:
0uiz
l

the FPGA.
to reconfigure
Youneedto know VHDL programming
a. True
b. False

ofparallel
parallelprccessing
2. TheFPGAcanachievetrue,simultaneous
operations.
a. True
b. False
in theFPGAVI asa generalrule,
3. Useeffor in andenor out parameters
if
but removethemaftercarefultesting you havedifficultywith sizeor
speedof theFPGA application.
a. True
b. False
4. Youhaveto wait while theFPGAVI compilesuntil youcanbeginwork
on theRT controllerVl.
a. True
b. False
5. Whendevelopinga projectusingbothscai modeandFPGA mode'
whichofthe followingfeatureswill requirethata givenmoduleshould
be usedin FPGAmode?
a. Analogstreamingat 200kHz
PID cont.ollooprunningtasterthanI kHz
b. High-speed
is required
signalprocessing
c. Hardware-based
by scanmode
d. Vo moduleis not supported

hd_

@ atianatlnshunenlscaeoQlion

5-51

Manual
Fundanentals
Course
Conpactql1andLabVlEW

SellReview:
0uizAnswers
the FPGA.
to reconfigure
l. Youneedto knowVHDL programming
a. True
b. False
pifallel processing
ofparallel
2 . TheFPGAcanachievetrue,simultaneous
operations.
a. True
b. False
in theFPGAVI asa genenl rule,
3 . Useerrorin andenor out parameters
but rcmovethemaftercarefultestingifyou bavedifficultywith sizeor
speedol theFPGAapplication.
a, True
b. False
4. Youhaveto waitwhiletheFPGAVI compilesuntil you canbeginwork

on the RT controllerVI.
a. True
b. False
5 . Whendeveloping
a projectusingbothscanmodeandFPGAmode,
whichofthe followingfeatureswill requirethata givenmoduleshould
be usedin FPGAmode?
a. Analog streaming at 20OkIJz
b. High-speedPID control loop running fasterthan I kHz
signalprocessingis required
c. Hardware-based
d. VO moduleis not supportedby scanmode

lnsttunenteCotpoation
A Nationat

5-53

Cou$eManual
ConpntRloandLa,VIEWFundaneotals

Noles

ConpactqloandLabVlEW
rundanenklsCousellanual

5-54

You might also like