Sie sind auf Seite 1von 8

2/8/2016 PololuArduinoLibraryforthePololuQTRReflectanceSensors

ArduinoLibraryforthePololuQTRReflectanceSensors

Viewdocumentonmultiplepages.
YoucanalsoviewthisdocumentasaprintablePDF.

1.Introduction
2.LibraryInstallation
3.QTRSensorsMethods&UsageNotes

1.Introduction

QTRsensorsizecomparison.Clockwisefromtopleft:QTR3RC,QTR1RC,
QTRL1RC,QTR8RC.

ThePololuQTRreflectancesensorscarryinfraredLEDandphototransistorpairsthatcanprovideanalogmeasurementsofIRreflectance,whichmakes
themgreatforcloseproximityedgedetectionandlinefollowingapplications.Themodulescomeascompact,singlesensorunits(QTR1AandQTR
1RCQTRL1A and QTRL1RC), 3sensor arrays (QTR3A and QTR3RC), or as 8sensor arrays (QTR8A and QTR8RC) that can be
optionallysplitintoa2sensorarrayanda6sensorarray.

The modules are available in two different output formats: the QTRxA outputs an analog voltage between 0 and Vcc that can be measured by an
analogtodigitalconverter(ADC),andtheQTRxRCoutputsrequireadigitalI/Olinecapableofdrivingtheoutputlinehighandthenmeasuringthe
timefortheoutputvoltagetodecay(whichprovidesananalogmeasurementofreflectance).

https://www.pololu.com/docs/0J19/all 1/8
2/8/2016 PololuArduinoLibraryforthePololuQTRReflectanceSensors

QTRL1Areflectance QTR1Areflectancesensor QTR1RCandQTRL1RC


sensorschematicdiagram. schematicdiagram. reflectancesensor
schematicdiagram.

Pleaseseetheproductpagesformoreinformationonhowthesesensorswork.

ThisdocumentwillexplainhowtoinstallArduinolibrariesforthePololuQTRreflectancesensors,anditwillprovidesamplesketchesaswellaslinks
to library documentation. The libraries will give you everything you need to interface with a QTR8x reflectance sensor array or multiple QTR1x
reflectancesensors,includingadvancedfeatureslikeautomaticcalibrationand,inthecaseoflinedetection,calculationofthelinesposition.

2.LibraryInstallation

DownloadthearchivefromGitHub,decompressit,anddragtheQTRSensorsfoldertoyourarduino1.0/librariesdirectory.

YoushouldnowbeabletousetheselibrariesinyoursketchesbyselectingSketch>ImportLibrary>QTRSensorsfromyourArduinoIDE(or
simplytype#include<QTRSensors.h> at the top of your sketch). Note that you might need to restart your Arduino IDE before it sees the new
libraries.

Oncethisisdone,youcancreateaQTRSensorsAnalogobjectforyourQTRxAsensorsandaQTRSensorsRCobjectforyourQTRxRCsensors:

1 //createanobjectforthreeQTRxAsensorsonanaloginputs0,2,and6 ?
2 QTRSensorsAnalogqtra((unsignedchar[]){0,2,6},3);
3
4 //createanobjectforfourQTRxRCsensorsondigitalpins0and9,andonanalog
5 //inputs1and3(whicharebeingusedasdigitalinputs15and17inthiscase)
6 QTRSensorsRCqtrrc((unsignedchar[]){0,9,15,17},4);

This library takes care of the differences between the QTRxA and QTRxRC sensors internally, providing you with a common interface to both
sensors.Theonlyexternaldifferenceisintheconstructors,asyoucanseeinthecodesampleabove.ThefirstargumenttotheQTRSensorsAnalog
constructorisanarrayofanaloginputpins(07)whilethefirstargumenttotheQTRSensorsRCconstructorisanarrayofdigitalpins(019).Note
thatanaloginputs05canbeusedasdigitalpins1419.Formoredetails,seeSection3.

Theonlyotherdifferenceyoumightexperienceisinthetimeittakestoreadthesensorvalues.TheQTRxRCsensorscanallbereadinparallel,but
eachrequiresthetimingofapulsethatmighttakeaslongas3ms(youcanspecifyhowlongthelibraryshouldtimethispulsebeforetimingoutand
declaringtheresultfullblack).TheQTRxAsensorsusetheanalogtodigitalconverter(ADC)andhencemustbereadsequentially.Additionally,the
analog results are produced by internally averaging a number of samples for each sensor (you can specify the number of samples to average) to
decreasetheeffectofnoiseontheresults.

Severalexamplesketchesareavailabletohelpyougetstarted.Toviewtheexamplesketches,opentheArduinoIDEandnavigateto:

File>Examples>QTRSensors

As a first step, we recommend using QTRARawValuesExample (for QTRxA sensors) or QTRRCRawValuesExample (for the QTRxRC
sensors).Theseexampleswillsimplyprinttherawreadingsfromthesensorstotheserialmonitor,using9600baud.Oncethatisworking,youmight
wanttotryoneofthemoreadvancedexamples,QTRAExampleorQTRRCExample,whichincorporatecalibrationandalsoestimatethepositionof
aline.

3.QTRSensorsMethods&UsageNotes

QTRSensorCommandReference
https://www.pololu.com/docs/0J19/all 2/8
2/8/2016 PololuArduinoLibraryforthePololuQTRReflectanceSensors

QTRSensorCommandReference

PreviousversionsofthislibrarywerenamedPololuQTRSensors,butwehavechangedittoQTRSensorstodifferentiateitfromthe
QTRsensorlibraryinourArduinoLibrariesfortheOrangutanand3piRobot.Asidefromthelibraryandclassnamechanges,
thenewQTRSensorslibraryisfunctionallyidenticaltopreviousversions.

For QTRxA sensors, you will want to instantiate a QTRSensorsAnalog object, and for QTRxRC sensors you will want to instantiate a
QTRSensorsRCobject.Asidefromtheconstructors,thesetwoobjectsprovidethesamemethodsforreadingsensorvalues(bothclassesarederived
fromthesameabstractbaseclass).Thelibraryprovidesaccesstotherawsensorsvaluesaswellastohighlevelfunctionsincludingcalibrationand
linetracking.

ThissectionofthelibrarydefinesanobjectforeachofthetwoQTRsensortypes,withtheQTRSensorsAnalogclassintendedforusewithQTRxA
sensorsandtheQTRSensorsRCclassintendedforusewithQTRxRCsensors.ThislibrarytakescareofthedifferencesbetweentheQTRxAand
QTRxRC sensors internally, providing you with a common interface to both sensors. The only external difference is in the constructors. This is
achievedbyhavingbothoftheseclassesderivefromtheabstractbaseclassQTRSensors.Thisbaseclasscannotbeinstantiated.

The QTRSensorsAnalog and QTRSensorsRC classes must be instantiated before they are used. This allows multiple QTR sensor arrays to be
controlledindependentlyasseparateQTRSensorsobjects.

Forcalibration,memoryisallocatedusingthemalloc()command.ThisconservesRAM:ifalleightsensorsarecalibratedwiththeemittersbothonan
off,atotalof64byteswouldbededicatedtostoringcalibrationvalues.However,foranapplicationwhereonlythreesensorsareused,andtheemitters
arealwaysonduringreads,only6bytesarerequired.

Internally,thislibraryusesallstandardArduinofunctionssuchasmicros()fortimingandanalogRead()ordigitalRead()forgettingthesensorvalues,
soitshouldworkonallArduinoswithoutconflictingwithotherlibraries.

voidread(unsignedint*sensorValues,unsignedcharreadMode=QTR_EMITTERS_ON)
Readstherawsensorvaluesintoanarray.ThereMUSTbespaceforasmanyvaluesasthereweresensorsspecifiedintheconstructor.Thevalues
returnedareameasureofthereflectanceinunitsthatdependonthetypeofsensorbeingused,withhighervaluescorrespondingtolowerreflectance
(ablacksurfaceoravoid).QTRxAsensorswillreturnarawvaluebetween0and1023.QTRxRCsensorswillreturnarawvaluebetween0and
thetimeoutargument(inunitsofmicroseconds)providedintheconstructor(whichdefaultsto2000).

ThefunctionsthatreadvaluesfromthesensorsalltakeanargumentreadMode,which specifiesthekind of readthat will be performed. Several


optionsaredefined:QTR_EMITTERS_OFFspecifiesthatthereadingshouldbemadewithoutturningontheinfrared(IR)emitters,inwhichcase
thereadingrepresentsambientlightlevelsnearthesensorQTR_EMITTERS_ONspecifiesthattheemittersshouldbeturnedonforthereading,
whichresultsinameasureofreflectanceandQTR_EMITTERS_ON_AND_OFFspecifiesthatareadingshouldbemadeinboththeonandoff
states.ThevaluesreturnedwhentheQTR_EMITTERS_ON_AND_OFFoptionisusedaregivenbyon+maxoff,whereonisthereadingwith
theemitterson,offisthereadingwiththeemittersoff,andmaxisthemaximumsensorreading.Thisoptioncanreducetheamountofinterference
fromunevenambientlighting.Notethatemittercontrolwillonlyworkifyouspecifyavalidemitterpinintheconstructor.

Exampleusage:
1 unsignedintsensor_values[8]; ?
2 sensors.read(sensor_values);

voidemittersOn()
TurntheIRLEDson.Thisismainlyforusebythereadmethod,andcallingthesefunctionsbeforeorafterthereadingthesensorswillhaveno
effectonthereadings,butyoumaywishtousethesefortestingpurposes.Thismethodwillonlydosomethingiftheemitterpinspecifiedinthe
constructorisnotQTR_NO_EMITTER_PIN.

voidemittersOff()
TurntheIRLEDsoff.Thisismainlyforusebythereadmethod,andcallingthesefunctionsbeforeorafterthereadingthesensorswillhaveno
effectonthereadings,butyoumaywishtousethesefortestingpurposes.

voidcalibrate(unsignedcharreadMode=QTR_EMITTERS_ON)
Reads the sensors for calibration. The sensor values are not returned instead, the maximum and minimum values found over time are stored
internally and used for the readCalibrated() method. You can access the calibration (i.e raw max and min sensor readings) through the public
https://www.pololu.com/docs/0J19/all 3/8
2/8/2016 PololuArduinoLibraryforthePololuQTRReflectanceSensors

member pointers calibratedMinimumOn, calibratedMaximumOn, calibratedMinimumOff, and calibratedMaximumOff. Note that these
pointerswillpointtoarraysoflengthnumSensors,asspecifiedintheconstructor,andtheywillonlybeallocatedaftercalibrate()hasbeencalled.If
youonlycalibratewiththeemitterson,thecalibrationarraysthatholdtheoffvalueswillnotbeallocated.

voidreadCalibrated(unsignedint*sensorValues,unsignedcharreadMode=QTR_EMITTERS_ON)
Returnssensorreadingscalibratedtoavaluebetween0and1000,where0correspondstoareadingthatislessthanorequaltotheminimumvalue
readbycalibrate()and1000correspondstoareadingthatisgreaterthanorequaltothemaximumvalue.Calibrationvaluesarestoredseparatelyfor
eachsensor,sothatdifferencesinthesensorsareaccountedforautomatically.

unsignedintreadLine(unsignedint*sensorValues,unsignedcharreadMode=QTR_EMITTERS_ON,unsignedcharwhiteLine=0)
Operates the same as read calibrated, but with a feature designed for line following: this function returns an estimated position of the line. The
estimateismadeusingaweightedaverageofthesensorindicesmultipliedby1000,sothatareturnvalueof0indicatesthatthelineisdirectlybelow
sensor0(orwaslastseenbysensor0beforebeinglost),areturnvalueof1000indicatesthatthelineisdirectlybelowsensor1,2000indicatesthat
itsbelowsensor2,etc.Intermediatevaluesindicatethatthelineisbetweentwosensors.Theformulais:

0*value0+1000*value1+2000*value2+...

value0+value1+value2+...

Aslongasyoursensorsarentspacedtoofarapartrelativetotheline,thisreturnedvalueisdesignedtobemonotonic,whichmakesitgreatforuse
inclosedloopPIDcontrol.Additionally,thismethodrememberswhereitlastsawtheline,soifyoueverlosethelinetotheleftortheright,itsline
positionwillcontinuetoindicatethedirectionyouneedtogotoreacquiretheline.Forexample,ifsensor4isyourrightmostsensorandyouendup
completelyoffthelinetotheleft,thisfunctionwillcontinuetoreturn4000.

Bydefault,thisfunctionassumesadarkline(highvalues)surroundedbywhite(lowvalues).Ifyourlineislightonblack,settheoptionalsecond
argument whiteLine to true. In this case, each sensor value will be replaced by the maximum possible value minus its actual value before the
averaging.

unsignedint*calibratedMinimumOn
Thecalibratedminimumvaluesmeasuredforeachsensor,withemitterson.Thepointersareunallocatedandsetto0untilcalibrate()iscalled,and
then allocated to exactly the size required. Depending on the readMode argument to calibrate(), only the On or Off values may be allocated, as
required.Thisandthefollowingvariablesaremadepublicsothatyoucanusethemforyourowncalculationsanddothingslikesavingthevaluesto
EEPROM,performingsanitychecking,etc.

unsignedint*calibratedMaximumOn
Thecalibratedmaximumvaluesmeasuredforeachsensor,withemitterson.

unsignedint*calibratedMinimumOff
Thecalibratedminimumvaluesmeasuredforeachsensor,withemittersoff.

unsignedint*calibratedMaximumOff
Thecalibratedmaximumvaluesmeasuredforeachsensor,withemittersoff.

Destructor:~QTRSensors()
ThedestructorfortheQTRSensorsclassfreesupmemoryallocatedforthecalibrationarrays.

Constructor:QTRSensorsRC()
Thisversionoftheconstructorperformsnoinitialization.Ifitisused,theusermustcallinit()beforeusingthemethodsinthisclass.

Constructor:QTRSensorsRC(unsignedchar*digitalPins,unsignedcharnumSensors,unsignedinttimeout=2000,unsignedcharemitterPin
=QTR_NO_EMITTER_PIN)
Thisconstructorjustcallsinit(),below.

voidQTRSensorsRC::init(unsignedchar*digitalPins,unsignedcharnumSensors,unsignedinttimeout=2000,unsignedcharemitterPin=
QTR_NO_EMITTER_PIN)
InitializesaQTRRC(digital)sensorarray.

https://www.pololu.com/docs/0J19/all 4/8
2/8/2016 PololuArduinoLibraryforthePololuQTRReflectanceSensors

ThearraydigitalPinsshouldcontaintheArduinodigitalpinnumbersforeachsensor.

numSensorsspecifiesthelengthofthedigitalPinsarray(thenumberofQTRRCsensorsyouareusing).numSensorsmustbenogreaterthan16.

timeoutspecifiesthelengthoftimeinmicrosecondsbeyondwhichyouconsiderthesensorreadingcompletelyblack.Thatistosay,ifthepulse
lengthforapinexceedstimeout,pulsetimingwillstopandthereadingforthatpinwillbeconsideredfullblack.Itisrecommendedthatyouset
timeouttobebetween1000and3000us,dependingonfactorsliketheheightofyoursensorsandambientlighting.Thisallowsyoutoshortenthe
durationofasensorreadingcyclewhilemaintainingusefulmeasurementsofreflectance.

emitterPinistheArduinodigitalpinthatcontrolswhethertheIRLEDsareonoroff.Thispinisoptionalandonlyexistsonthe8Aand8RCQTR
sensorarrays.Ifavalidpinisspecified,theemitterswillonlybeturnedonduringareading.IfthevalueQTR_NO_EMITTER_PIN(255)isused,
youcanleavetheemitterpindisconnectedandtheIRemitterswillalwaysbeon.

Constructor:QTRSensorsAnalog()
Thisversionoftheconstructorperformsnoinitialization.Ifthisconstructorisused,theusermustcallinit()beforeusingthemethodsinthisclass.

Constructor: QTRSensorsAnalog(unsigned char* analogPins, unsigned char numSensors, unsigned char numSamplesPerSensor = 4,
unsignedcharemitterPin=QTR_NO_EMITTER_PIN)
Thisconstructorjustcallsinit(),below.

voidinit(unsigned char* analogPins, unsigned char numSensors, unsigned char numSamplesPerSensor = 4, unsigned char emitterPin =
QTR_NO_EMITTER_PIN)
InitializesaQTRA(analog)sensorarray.

ThearraypinsshouldcontaintheArduinoanaloginputpinnumberforeachsensor.Forexample,ifpinsis{0,1,7},sensor1isonanaloginput0,
sensor2isonanaloginput1,andsensor3isonanaloginput7.

numSensorsspecifiesthelengthoftheanalogPinsarray(thenumberofQTRAsensorsyouareusing).numSensorsmustbenogreaterthan16.

numSamplesPerSensor indicates the number of 10bit analog samples to average per channel (per sensor) for each reading. The total number of
analogtodigital conversions performed will be equal to numSensors times numSamplesPerSensor. Increasing this parameter increases noise
suppressionatthecostofsamplerate.Thisparametermustnotexceed64.Recommendedvalue:4.

emitterPinistheArduinodigitalpinthatcontrolswhethertheIRLEDsareonoroff.Thispinisoptionalandonlyexistsonthe8Aand8RCQTR
sensorarrays.Ifavalidpinisspecified,theemitterswillonlybeturnedonduringareading.IfthevalueQTR_NO_EMITTER_PIN(255)isused,
youcanleavetheemitterpindisconnectedandtheIRemitterswillalwaysbeon.

UsageNotes
Calibration
Thislibraryallowsyoutousethecalibrate()methodtoeasilycalibrateyoursensorsfortheparticularconditionsitwillencounter.Calibratingyour
sensorscanleadtosubstantiallymorereliablesensorreadings,whichinturncanhelpsimplifyyourcodesince.Assuch,werecommendyoubuilda
calibrationphaseintoyourapplicationsinitializationroutine.Thiscanbeassimpleasafixeddurationoverwhichyourepeatedcallthecalibrate()
method.Duringthiscalibrationphase,youwillneedtoexposeeachofyourreflectancesensorstothelightestanddarkestreadingstheywillencounter.
Forexample,ifyouhavemadealinefollower,youwillwanttoslideitacrossthelineduringthecalibrationphasesotheeachsensorcangetareading
ofhowdarkthelineisandhowlightthegroundis.Asamplecalibrationroutinewouldbe:

1 #include<QTRSensors.h> ?
2
3 //createanobjectforyourtypeofsensor(RCorAnalog)
4 //inthisexamplewehavethreesensorsonanaloginputs02,a.k.a.digitalpins1416
5 QTRSensorsRCqtr((char[]){14,15,16},3);
6 //QTRSensorsAqtr((char[]){0,1,2},3);
7
8 voidsetup()
9 {
10 //optional:waitforsomeinputfromtheuser,suchasabuttonpress
11
12 //thenstartcalibrationphaseandmovethesensorsoverboth
13 //reflectanceextremestheywillencounterinyourapplication:
14 inti;
15 for(i=0;i<250;i++)//makethecalibrationtakeabout5seconds

https://www.pololu.com/docs/0J19/all 5/8
2/8/2016 PololuArduinoLibraryforthePololuQTRReflectanceSensors
16 {
17 qtr.calibrate();
18 delay(20);
19 }
20
21 //optional:signalthatthecalibrationphaseisnowoverandwaitforfurther
22 //inputfromtheuser,suchasabuttonpress
23 }

ReadingtheSensors
Thislibrarygivesyouanumberofdifferentwaystoreadthesensors.

1.You can request raw sensor values using the read() method, which takes an optional argument that lets you perform the read with the IR
emittersturnedoff(notethatturningtheemittersoffisonlysupportedbytheQTR8xreflectancesensorarrays).
2.YoucanrequestcalibratedsensorvaluesusingthereadCalibrated()method,whichalsotakesanoptionalargumentthatletsyouperformthe
readwiththeIRemittersturnedoff.Calibratedsensorvalueswillalwaysrangefrom0to1000,with0beingasormorereflective(i.e.whiter)
thanthemostreflectivesurfaceencounteredduringcalibration,and1000beingasorlessreflective(i.e.blacker)thantheleastreflectivesurface
encounteredduringcalibration.
3.Forlinedetectionapplications,youcanrequestthelinelocationusingthereadLine()method,whichtakesasoptionalparametersabooleanthat
indicateswhetherthelineiswhiteonablackbackgroundorblackonawhitebackground,andabooleanthatindicateswhethertheIRemitters
shouldbeonoroffduringthemeasurement.readLine()providescalibratedvaluesforeachsensorandreturnsanintegerthattellsyouwhereit
thinksthelineis.IfyouareusingNsensors,areturnedvalueof0meansitthinksthelineisonortotheoutsideofsensor0,andareturnedvalue
of1000*(N1)meansitthinksthelineisonortotheoutsideofsensorN1.Asyouslideyoursensorsacrosstheline,thelinepositionwill
changemonotonicallyfrom0to1000*(N1),orviceversa.ThislinepositionvaluecanbeusedforclosedloopPIDcontrol.

Asampleroutinetoobtainthesensorvaluesandperformrudimentarylinefollowingwouldbe:

1 voidloop() ?
2 {
3 unsignedintsensors[3];
4 //getcalibratedsensorvaluesreturnedinthesensorsarray,alongwiththelineposition
5 //positionwillrangefrom0to2000,with1000correspondingtothelineoverthemiddle
6 //sensor.
7 intposition=qtr.readLine(sensors);
8
9 //ifallthreesensorsseeverylowreflectance,takesomeappropriateactionforthis
10 //situation.
11 if(sensors[0]>750&&sensors[1]>750&&sensors[2]>750)
12 {
13 //dosomething.Maybethismeanswe'reattheedgeofacourseorabouttofalloff
14 //atable,inwhichcase,wemightwanttostopmoving,backup,andturnaround.
15 return;
16 }
17
18 //computeour"error"fromthelineposition.Wewillmakeitsothattheerroriszero
19 //whenthemiddlesensorisovertheline,becausethisisourgoal.Errorwillrangefrom
20 //1000to+1000.Ifwehavesensor0ontheleftandsensor2ontheright,areadingof
21 //1000meansthatweseethelineontheleftandareadingof+1000meansweseethe
22 //lineontheright.
23 interror=position1000;
24
25 intleftMotorSpeed=100;
26 intrightMotorSpeed=100;
27 if(error<500)//thelineisontheleft
28 leftMotorSpeed=0;//turnleft
29 if(error>500)//thelineisontheright
30 rightMotorSpeed=0;//turnright
31
32 //setmotorspeedsusingthetwomotorspeedvariablesabove
33 }

PIDControl
The integer value returned by readLine() can be easily converted into a measure of your position error for linefollowing applications, as was
demonstratedinthepreviouscodesample.Thefunctionusedtogeneratethisposition/errorvalueisdesignedtobemonotonic,whichmeansthevalue
willalmostalwayschangeinthesamedirectionasyousweepyoursensorsacrosstheline.ThismakesitagreatquantitytouseforPIDcontrol.

ExplainingthenatureofPIDcontrolisbeyondthescopeofthisdocument,butwikipediahasaverygoodarticleonthesubject.

ThefollowingcodegivesaverysimpleexampleofPDcontrol(IfindtheintegralPIDtermisusuallynotnecessarywhenitcomestolinefollowing).
Thespecificnatureoftheconstantswillbedeterminedbyyourparticularapplication,butyoushouldnotethatthederivativeconstantKd is usually

https://www.pololu.com/docs/0J19/all 6/8
2/8/2016 PololuArduinoLibraryforthePololuQTRReflectanceSensors

muchbiggerthantheproportionalconstantKp.Thisisbecausethederivativeoftheerrorisamuchsmallerquantitythantheerroritself,soinorderto
produceameaningfulcorrectionitneedstobemultipliedbyamuchlargerconstant.

1 intlastError=0; ?
2
3 voidloop()
4 {
5 unsignedintsensors[3];
6 //getcalibratedsensorvaluesreturnedinthesensorsarray,alongwiththelineposition
7 //positionwillrangefrom0to2000,with1000correspondingtothelineoverthemiddle
8 //sensor
9 intposition=qtr.readLine(sensors);
10
11 //computeour"error"fromthelineposition.Wewillmakeitsothattheerroriszerowhen
12 //themiddlesensorisovertheline,becausethisisourgoal.Errorwillrangefrom
13 //1000to+1000.Ifwehavesensor0ontheleftandsensor2ontheright,areadingof
14 //1000meansthatweseethelineontheleftandareadingof+1000meansweseethe
15 //lineontheright.
16 interror=position1000;
17
18 //setthemotorspeedbasedonproportionalandderivativePIDterms
19 //KPistheafloatingpointproportionalconstant(maybestartwithavaluearound0.1)
20 //KDisthefloatingpointderivativeconstant(maybestartwithavaluearound5)
21 //notethatwhendoingPID,it'sveryimportantyougetyoursignsright,orelsethe
22 //controlloopwillbeunstable
23 intmotorSpeed=KP*error+KD*(errorlastError);
24 lastError=error;
25
26 //M1andM2arebasemotorspeeds.Thatistosay,theyarethespeedsthemotorsshould
27 //spinatifyouareperfectlyonthelinewithnoerror.Ifyourmotorsarewellmatched,
28 //M1andM2willbeequal.WhenyoustarttestingyourPIDloop,itmighthelptostartwith
29 //smallvaluesforM1andM2.Youcanthenincreasethespeedasyoufinetuneyour
30 //PIDconstantsKPandKD.
31 intm1Speed=M1+motorSpeed;
32 intm2Speed=M2motorSpeed;
33
34 //itmighthelptokeepthespeedspositive(thisisoptional)
35 //notethatyoumightwanttoaddasimiliarlinetokeepthespeedsfromexceeding
36 //anymaximumallowedvalue
37 if(m1Speed<0)
38 m1Speed=0;
39 if(m2Speed<0)
40 m2Speed=0;
41
42 //setmotorspeedsusingthetwomotorspeedvariablesabove
43 }

Relatedproducts

QTR1AReflectanceSensor

QTR1AReflectanceSensor(2Pack)

QTR3RCReflectanceSensorArray

QTR3AReflectanceSensorArray

QTRL1RCReflectanceSensor(2Pack)

QTRL1AReflectanceSensor(2Pack)

QTR1RCReflectanceSensor

QTR1RCReflectanceSensor(2Pack)
https://www.pololu.com/docs/0J19/all 7/8
2/8/2016 PololuArduinoLibraryforthePololuQTRReflectanceSensors
QTR1RCReflectanceSensor(2Pack)

QTR8RCReflectanceSensorArray

QTR8AReflectanceSensorArray

https://www.pololu.com/docs/0J19/all 8/8

Das könnte Ihnen auch gefallen