FRC Electrical Bible
FRCElectricalBible
TableofContents
Introduction
0
TheroboRIO
1
GeneralroboRIOOverview
1.1
ConfiguringtheroboRIO
1.2
ConnectingtotheroboRIOWirelessly
1.3
UploadingCodetotheroboRIO
1.4
TheCANBus
1.5
TheRobotSignalLight
1.6
ThePowerDistributionBoard(PDP)
2
ThePDP
2.1
120ACircuitBreaker
2.2
TheVoltageRegulatorModule
2.3
ThePowerConverter
2.4
TheD-Link
3
ThePhysicalLayer
3.1
AutomaticConfiguration
3.2
ManualConfiguration
3.3
TroubleshootingtheD-Link
3.4
DriverStation
4
Introduction
4.1
TheInterface
4.2
PrintingtoDriverStation
4.3
ACrashCourseonC++
5
Variables
5.1
Functions
5.2
ObjectUsage
5.3
TheJoystick
5.4
MotorControllers
6
GeneralOverview
6.1
Motors
6.2
2
FRCElectricalBible
Jaguar
6.3
Victor888
6.4
Talon
6.5
TalonSRX
6.6
Spike
6.7
Fans
6.8
DriveCode
7
BoxonWheels
7.1
BoxonWheelsTemplatevsCustomProgram
7.2
CustomProgram(TankDrive)
7.3
CustomProgram(MecanumDrive)
7.4
Sensors
8
roboRIOAccelerometer
8.1
Microswitch
8.2
OpticalEncoder
8.3
Gyro
8.4
Camera
9
Hardware
9.1
SettinguptheCamera
9.2
LiveFeed
10
TheCode
10.1
UsingNIVisionAssistant
10.2
DevelopingCameraCode
10.3
Pneumatics
11
ThePhysicalLayer
11.1
PneumaticsCircuit
11.2
PneumaticsCode
11.3
Appendixes
AppendixA:GeneralWiringDiagram
Changelog
12
12.1
13
3
FRCElectricalBible
TheElectricalBible-Beta
WelcometoourElectricalFIRSTopedia!
Wecreatedthisguideinhopesofcombiningabasicunderstandingofalltheelectronic
componentstheFRCrobotusesintoonecohesiveandcomprehensiveguide.Thisguide
wasmadewiththepowerofGoogleDocs,GitBook,ourphones’camerasandendless
Googlesearches.
Thisguidehasbeenupdatedtoincludethe2015controlsystem.Ourolderdocumentcan
befoundhere,andincludesdocumentationonthecRIO.
SomethingtonoteisthatweprograminC++,soreferencestoclasseslike“Encoder”and
oursamplecodesarewritteninC++.However,classesareinterchangeableinJavaand
C++,andtherearetopicscoveredinthisguidethatarenotlanguage-exclusivelikethe
roboRIOandtheDriverStationitself.Wehopethisisguideservestobeusefulforyou!
Team2853Electrical/ProgrammingTeam
IfyouareviewingthisonGitHub,pleaseusetheGitBooklink:
https://mililanirobotics.gitbooks.io/frc-electrical-bible/content/index.html
Introduction
4
FRCElectricalBible
1.TheroboRIO
1.1GeneralroboRIOOverview
➠WhatisaroboRIO?
➠Connectors
➠WiringDiagram
1.2ConfiguringtheroboRIO
➠Installing/UpdatingNewFirmware
➠Imaging/ReimagingaroboRIO
1.3ConnectingtotheroboRIOWirelessly
1.4UploadingCodetotheroboRIO
1.5TheCANBus
➠Introduction
➠WiringtheCAN
TheroboRIO
5
FRCElectricalBible
GeneralroboRIOOverview
➠WhatisaroboRIO?
AroboRIOisamorerecentversionofthecRIO(compactReconfigurableInput/Output)that
wasintroducedtoFRCteamsinthe2015season.Itisafaster,smaller,andmorepowerful
versionofthepreviouscontroller.LikethecRIO,itactsasthebrainoftherobot,and
connectstoaD-Linkrouterusinganethernetcable.Additionally,theroboRIOcombinesthe
functionsofthedigitalsidecarincludingthedigitalandanalogmodulesoftheprevious
controlsystem.TheroboRIOismorerobustthanthedigitalsidecar,andisprotectedfrom
shortsbetweenitsexternalpins.
Specs
BasicOverview
Dual-CoreARMCortex667MHzprocessor
256MBRAM
512MBNANDstoragememory
LinuxOperatingSystemwithreal-timeextensionsSupportsLABVIEW,C++,andJava
Physical/ElectricalCharacteristics
6.8Vto16Vinputpower(stagedbrownoutfrom4.5Vto6.8V)
3.3Vuseroutput(with1.5Amaximum)
5Vuseroutput(with1Amaximum)
6Vservooutput(with2.2Amaximum)
Operatingtemperature0°C-40°C
Storagetemperature-20°C-70°C
5.7inchesby5.6inches,weighs12ounces
I/OandCommunicationPorts
10dedicatedPWMchannels
GeneralroboRIOOverview
6
FRCElectricalBible
10DIOdedicatedchannels
4bi-directional
RelayControlchannels
2USBHostports
1USBDeviceport
1Ethernetport
1CANPort
1Integrated,3-axisaccelerometer
12VRobotsignallightchannel
➠Connectors
WeidmullerConnectorsareusedtosupplypowertotheroboRIO,PCM(PneumaticControl
Module),andVRM(VoltageRegulatorModule).Theconnectoracceptswiregaugesfrom16
AWGto24AWG.WirescanbeinsertedintoorremovedfromtheWiedmullerconnectorby
pushingdownonthewhitetabusingatinyflathead.
➠WiringDiagram
GeneralroboRIOOverview
7
FRCElectricalBible
Notes:
TheCANPortsontheroboRIOareusedtoconnecttothePCMandPDP
TheroboRIOisconnectedtothePDPthroughitsinputpowerports.Donotconnectthe
roboRIOdirectlytotherobotbattery.
TheUSBDeviceportcanbeusedtoconnecttoacomputertoupdatetheroboRIO
firmwareandtoreimagetheroboRIO.
TheLEDsindicatethecurrentstatusoftheroboRIO.TheroboRIOcanbemounted
usingzip-tiesthroughthemountingfeatures.
PleaseseetheAppendixforanexamplewiringofthewholecontrolsystem.
GeneralroboRIOOverview
8
FRCElectricalBible
ConfiguringtheroboRIO
BeforeabrandnewroboRIOcanbeputintoaction,youmustfirstinstallthelatestroboRIO
firmwareandthenre-imagethesoftwareusingthelatestversion.Beforeyoubegin,ensure
thattheNI(NationalInstruments)suiteisupdated.TheNIupdateaswellasinstructionsfor
downloadingitcanbefoundbelow:
https://wpilib.screenstepslive.com/s/4485/m/13503/l/144150-installing-the-frc-2015-updatesuite-all-languages
➠InstallingandUpdatingtheroboRIOfirmware
PriortotheimagingoftheroboRIO,thefirmwareontheroboRIOmustbeupgradedtothe
latestversion.Thisprocesswillprovidethebootloader,safemode,andfirmwareforthe
roboRIO.Whileitispossibletodothisusinganethernetconnection,itisnotrecommended.
Thefirmwarecanbeupdatedusingyoursystem’swebbrowserinthefollowingsteps:
ConfiguringtheroboRIO
9
FRCElectricalBible
1. Asshownintheelectricallayoutbelow,connecttheroboRIOtoyourcomputerusinga
printerUSBcableandsupplypowertotheroboRIO.
2. Thedrivershouldinstallautomatically.Oncethedownloadiscomplete,openaweb
browseronyourcomputer.
3. Intheaddressbarofthewebbrowser,type“172.22.11.2”andpressenter.
4. Clicklogin.“admin”willbetheusernameandleavethepasswordfieldblank.Then,click
“UpdateFirmware”
5. LookfortheroboRIO(.cfgfileinyourNationalInstrumentsfolder.Thedefaultlocationof
thisfileisunder“ProgramFiles\NationalInstruments\Shared\Firmware\cRIO\76F2”
ConfiguringtheroboRIO
10
FRCElectricalBible
6. Click“BeginUpdate”
➠ImagingandReimagingtheroboRIO
TheroboRIOImageloadstheFPGA,operatingsystem,linuxfilesystem,anddefault
settingsfortheroboRIO.NowthattheroboRIOhasthelatestfirmwareinstalled,itisnow
possibletoimagetheroboRIOinthefollowsteps:
1. EnsurethattheroboRIOisstillpoweredfromthePDP(PowerDistributionPanel)andis
stillsecurelypluggedintothecomputerusingaprinterUSBcable.
2. LookfortheroboRIOImagingtool(.exefile)asshownbelow.Itislocatedwithinthe
NationalInstrumentsfilefolder,anditsdefaultlocationis“National
Instruments\LabVIEW2014\project\roboRIO”
3. Doubleclicktorunthe“roboRIO_ImagingTool.exe”application,andthetheinterfacewill
attempttoidentifyconnectedroboRIOdevices.
4. Enteryourteamnumberunder“SystemInformation.”Selectthelatestversionofthe
roboRIOImage(indicatedbythehighestversionnumber)andthenameoftheroboRIO
youintendtoimage.
5. SelecttheFormatTargetoptionbutmakesurethattheConsoleOutandDisableRT
StartupAppoptionsarenotselected.Click“Reformat”
6. OncetheImagingiscomplete,click“OK”onthecompletionmessageandRebootthe
ConfiguringtheroboRIO
11
FRCElectricalBible
roboRIOusingtheResetbutton.
ConfiguringtheroboRIO
12
FRCElectricalBible
ConnectingtotheroboRIOWirelessly
1. ChangetheIPaddressandsubnetmaskofyourcomputer.TheIPaddressshouldbe
“10.xx.yy.100”,withxxandyybeingyourfourdigitteamnumber,andthesubnetmask
should“255.0.0.0”
2. Connecttotheteam’swirelessrouter.It’sthateasy!
ConnectingtotheroboRIOWirelessly
13
FRCElectricalBible
ConnectingtotheroboRIOWirelessly
14
FRCElectricalBible
UploadingCodetotheroboRIO
WiththeintroductionoftheroboRIOtoFRCteamsin2015,uploadingcodetotherobotis
madeeasy!Here’sthesteps:
1. Establishanetworkconnectiontoyourrobotnetwork.Onyourcomputer,goto
yournetworkconnectionsandconnecttotherouterthatisconnectedtotheroboRIO.
Don’tworryifyou’realreadyconnectedtoanothernetwork,asyouwillautomatically
disconnectfromthatnetworkconnection.
Connectingtoanetwork
2. BuildyourProject.Clickthe“Project”optionandthenclick“BuildProject.”Toupload
codetotheroboRIO,itisonlynecessarytobuildtheprojectforuploadingcodethat
hasn’tbeenbuildinthepastorwasmodified,butit’sagoodhabittoalwaysbuildyour
projectsbeforeuploadingthemtotherobot.Therefore,werecommendedhavingyour
UploadingCodetotheroboRIO
15
FRCElectricalBible
projectsbeforeuploadingthemtotherobot.Therefore,werecommendedhavingyour
“BuildAutomatically”settingenabled.
BuildinganEclipseproject
3. Runyourcode.PressCtrl+F11,andwhenpromptedhowyouwouldliketorunyour
code,selectthe“WPILibC++Deploy”optionandpressOK.Nowyou’redone!Waitfor
theDriverStationtoshowthatcommunicationshasbeenestablished,andyou’llbeon
yourwaytotestingyourcode!
Runningyourcodeusing“WPILibC++Deploy”
UploadingCodetotheroboRIO
16
FRCElectricalBible
UploadingCodetotheroboRIO
17
FRCElectricalBible
TheCANBus
➠Introduction
Asofthe2015FRCgame,RecycleRush,teamsarerequiredtousetheCANbusonthe
roboRIOwhenconnectingtothePCM,PDP,TalonSRXs,andJaguars(R60-62).
ThissectionwillnotgooverhowtouseCANontheTalonSRX(youcanreadCTR’sTalon
SRXUserguide)ortheJaguar,becauseourteamdoesnothaveexperiencewiththese
items.
ByconnectingthecontrolsystemtogetherwithCAN,thePDPandPCMcancommunicate
witheachother.ThePDPprovidesmonitoringforeachofitsoutputs.Amainadvantageof
thissystemisthatcompressorsandpressureswitchesnolongerneedtobeconnectedtoa
RelaySpike.
➠WiringtheCAN
Whenwiring,werecommendtwistingthetwowirestogether.Therearenospecificbusesfor
input/outputbutbyconvention,weusetheleftbusasinputandrightbusasoutput.
IfyouarenotusingtheroboRIOorPDPasterminalsfortheCANchain,terminatetheCAN
chainbyinsertinga120ΩresistorintotheWeidmullerterminals.
TheCANBus
18
FRCElectricalBible
TheRobotSignalLight
➠Introduction
TheRobotSignalLight(RSL)ismandatoryduringcompetitionandactsasasignalto
whethertherobotisconnectedtotheFCS,inteleopmode,etc.
➠WiringtheRSL
AseparatewireactsasajumperbetweenLaandLb.ConnectLato'S'andNtoGroundon
theroboRIO.
➠RSLIndicators
TheRobotSignalLight
19
FRCElectricalBible
LightCode
Meaning
SolidON
Autonomousenabled
SolidONbut
blinksoffevery
1.5sec
Teleopenabled
Slowblink
(900msON/
900msOFF)
Systemdisabledbysystemwatchdog,userwatchdog,ordriver
stationsettodisabled
Fast-slow
(200msON/
900msOFF)
Lowbattery(<12V)ornousercodeANDsystemdisabledeither
bysystemwatchdog,userwatchdog,orDriverStationsetto
disabled.
Fast(200msON
/200msOFF)
Systemerror;noDriverstationcommunication;badcRIOimage,
badteamID,extensivecommunicationerrors
TheRobotSignalLight
20
FRCElectricalBible
2.ThePDP
2.1ThePDP
➠Wiring
2.2120ACircuitBreaker
2.3TheVoltageRegulatorModule
➠Wiring
2.4ThePowerConverter
ThePowerDistributionBoard(PDP)
21
FRCElectricalBible
ThePDP
ThePDPisaneweriterationofthePDBthatwasintheKitofPartsgiventoteamsinthe
2015FRCseason.ThemaindifferencebetweenthetwoisthatthePDPisslightlysmaller,
lighter,andhasupdatedconnectors,whichincludestheWeidmullerConnectorsusedonthe
CANbus.Ingeneral,thePDPservesthesamefunctionasthePDB,distributingpowerto
thesystem,butisimprovedtobetterreflecttheupdatesmadetotherestofthecontrol
system.
Specs
Dimensions:7.586”x4.748”x1.442”tall(rough)
Weight:1lband5.3oz
4Mountingholes(oneateachcorner,smallerthan1/4-20andlargerthan10-32
fasteners)
Connectors
MainBatteryInput
2Bushinglugs
ThreadM6x1(size6mm)
PowerChannels(0-15)
ThePDP
22
FRCElectricalBible
8Red/8BlackWAGOConnectors30AmpChannels(4-11)
8Red/8BlackWAGOConnectors40AmpChannels(0-3,12-15)
6PositionWeidmullerConnectors(accept24-16AWG)
1x20ampfuse(usedforPCMandVRM)
1x10ampfuse(usedforRoboRIO)
8x20/30ampThermalBreakerbySnapActionslots(channels4-11)
8x40ampThermalBreakerbySnapActionslots(channels0-3,12-15)
CAN
4PositionWeidmullerConnectors
2YellowCANHigh
2GreenCANLow
StatusLights
BothLightsarealwaysthesamecolor/blinkingpatternwiththeexceptionof
bootingup
FastGreenBlink-Robotisenabled
SlowGreenBlink-Robotisdisabled
SlowOrangeBlink-Robotisdisabled&StickyFaultpresent(lowvoltage,<6.5V
SlowRedBlink-NoCANcommunication
BootStatuslights(COMMLEDonly)
Green/OrangeBlink-Deviceisinboot-loader/Field-upgradenecessary
BothLEDsoff-DeviceisNOTpowered
ThePDP
23
FRCElectricalBible
120ACircuitBreaker
Currentlyneedstobedocumented.
120ACircuitBreaker
24
FRCElectricalBible
TheVoltageRegulatorModule
➠GeneralVRMOverview
Imagecourtesyofhttp://khengineering.github.io/
➠WhatisaVRM?
TheVoltageRegulatorModule(VRM)isanewcomponentintroducedinthe2015FRC
seasonaspartoftheKitofParts.Thisreplacesthe12Vand5Vregulatorandspecial
protectedandunprotectedpoweroutputsontheoldPDB.ThepurposeoftheVRMistoact
asaDCtoDCconverter,andbothboostandbuckvoltageregulation.TheVRMisrequired
whenusingcomponentsthatrequirespecialprotectedpower.
Specs
Dimensions:2.220”x2.030”x0.784”Tall
Weight:1.8oz
4mountingholes(oneateachcorner,6-32fasteners)
Connectors(alluseWeidmullerconnectors,accepting24-16AWG)
TheVoltageRegulatorModule
25
FRCElectricalBible
4xconnectorsforregulated12V/2Amaxsurge/1.5Alimitpoweroutput
4xconnectorsforregulated12V/500mAmaxsurgepoweroutput
4xconnectorsforregulated5V/2Amaxsurge/1.5Alimitpoweroutput
4xconnectorsforregulated5V/500mAmaxsurgepoweroutput
2xconnectorsforunregulated12Vinput
StatusLights
5V/500mAStatusLED
On-5Vchannelsarepowered
Off-Breakerhastripped
12V/500mAStatusLED
On-12Vchannelsarepowered
Off-Breakerhastripped
LEDsnotaffectedwhen2Achannelsarelimited
Flickering-Lowvoltage(<4V)
➠Wiring
AllportsuseWeidmullerconnectors,accepting24-16AWG
Note:Therearetwoseparatepowersupplies,12Vand5V.Thereisjustenoughpowerto
runbothaD-LinkandCameraonthe5Vrail,butyoumayneedtouseaseparate12Vto5V
adapter.
TheVoltageRegulatorModule
26
FRCElectricalBible
ThePowerConverter
Althoughwehavethevoltageregulatormodule,ifyouarelookingtopower>1camera,you
willneedapowerconvertersothecameracanoperateunderit'snecessaryvoltage.The
powerconverterplugsintothePDPwitha20Acircuitbreaker.
ThePowerConverter
27
FRCElectricalBible
WiringthePowerConverter
ThePowerConverter
28
FRCElectricalBible
ThePowerConverter
29
FRCElectricalBible
3.TheD-Link
3.1ThePhysicalLayer
➠Introduction
➠TheVoltageRegulatorModule
3.2AutomaticConfiguration
➠2015ConfigurationPrerequisites
➠FRCConfigurationBridgeUtility
3.3ManualConfiguration
➠Setup:LANSettings
➠SetaDeviceName
➠SettheLANConnectionType
➠ConfiguretheIPv4Address,SubnetMask,andDefaultGateway
➠WirelessSettings
3.4TroubleshootingtheD-Link
TheD-Link
30
FRCElectricalBible
ThePhysicalLayer
➠Introduction
WecontroltherobotthroughaLogitechgamepadcontroller.Generally,wewouldn’twantto
followtherobotaroundwithanethernetcable,sowesolvethisproblembyconnecting
wirelessly.WeusetheD-Linkasamediumtocommunicatewiththerobotinthisfashion.
➠TheVoltageRegulatorModule
Asofthe2015FRCgame,RecycleRush,theDLinkisrequiredtobepoweredbythe5V/2A
AKA“Radio”portontheVoltageRegulatorModule.YoucanreadmoreaboutittheThe
PowerDistributionPanelsection.
ThePhysicalLayer
31
FRCElectricalBible
TheD-Linkitselfisconnectedtoapoweradapterthatis:
5VOutput
PowerCabletoD-LinkModelNo:AMS3-0502000FU
Barrel5.5/2.1mm
AndyMark-PowerConverter|
TheD-LinkconnectstothecRIOviaaStandardCAT-5EthernetCable.Itcanalsoactasthe
“middle-man”withanEthernetcableconnectingtotheDriverStationlaptop.
ThePhysicalLayer
32
FRCElectricalBible
Makesuretherouterhaspower
Makesuretheethernetcablesarepluggedinsecurely(onbothends)
NOTE:Itdoesn’tmatterwhichLANPortstheethernetcablesarepluggedinto.However,by
conventionweusuallymakesurethattheroboRIOconnectstoport2andacomputerplugs
intoport1.
ThePhysicalLayer
33
FRCElectricalBible
AutomaticConfiguration
➠2015ConfigurationPrerequisites
1. MakesurethattherouterisswitchedtotheAccessPointmodeyourequest(2.4Ghz,
5.0Ghz,Bridge).Asettingof2.4GhzisappropriateformostFRCteamsandshouldbe
usedasthedefault.
2. EnsurethatyourcomputerhasJavainstalled.Ifyou’reunsureorneedtocheckor
downloadtheJavasoftware,usethislink:http://www.java.com/en/download/index.jsp
3. AlsoensurethattheNISuiteisupdated,whichincludestheFRCBridgeConfiguration
UtilitytoconfigurearoutertouseinFRC.TodownloadtheNewFRCSoftware,usethis
link:http://wpilib.screenstepslive.com/s/4485/m/13503/l/144150-installing-the-frc-2015update-suite-all-languagesNOTE:Toresettherouterpressandholdtheresetbutton
for30secondstoperformafactoryresettowipeanypreviousconfigurations
➠FRCBridgeConfigurationUtility
NOTE:Iftherouterisnotbrandnew,itisnotnecessarytopressandholdtheresetbutton
for30secondstoperformafactoryresettowipeanypreviousconfigurationsbecausethe
FRCsoftwarewilldosoforyou.
1. TurnofftheWifionyourcomputer
2. Makesurethephysicallayerontherouterissetupproperly.
3. LaunchtheFRCBridgeToolsoftware.ItislocatedundertheNationalInstruments
folder,anditsdefaultlocationisC:\ProgramFiles\NationalInstruments\LabVIEW
2014\project\FRCBridgeConfigurationUtility.exe
AutomaticConfiguration
34
FRCElectricalBible
4. UndertheNetworkInterfacespopupfromtheBridgeConfigurationUtility,Select“Local
AreaConnection”andpressOK.Iftherearenonetworkinterfacesshown,clickthe
refreshbutton.
AutomaticConfiguration
35
FRCElectricalBible
5. UndertheFRCBridgeConfigurationUtility,TypeinyourFRCteamnumberaswellasa
passwordtobesetunderthesectionfor“WPAKey.”EnsurethattheRadiooptionisset
toDAP1522RevB,andthattheModeoptionissettothecurrentprerequisitesetting
(defaultof2.4GHzAccessPointshouldbeused).Nowclick“Configure.”
6. WaituntiltheConfigurationProgressiscomplete,andthenpressOKonceitisdone!
NotethattherouterSSIDcanbeconfiguredthroughtheD-Linkap
AutomaticConfiguration
36
FRCElectricalBible
ManualConfiguration
1. Openupyourwebbrowser(Firefox,Chrome,etc.)
2. Intheaddressbar,typeintheIPaddressoftherouter.It’seither:
192.168.1.1,thedefaultIPaddress
8OR10.xx.yy.1,wherexxisthefirsttwodigitsofyourteam’s#(itcanbeonedigitif
yourteamhasathree-digit#)andyyisthelasttwo
ORtypeindlinkap/andhitenter.
3. You’llgetapromptfortherouternameandpasswordliketheoneshownbelow.Ona
brandnewrouterorarouterthatwasreseted,thelogininfowillbethis:
UserName:Admin
NoPassword(bydefault)
AutomaticConfiguration
37
FRCElectricalBible
➠Setup:LANSettings
AutomaticConfiguration
38
FRCElectricalBible
➠SetaDeviceName:Teamxxxx-y
xxxx=Yourteamnumbertoavoidconfusion.
y=Arbitrarybutuniquenumbertoyourroutertoavoidconfusion.Youshouldbaseitonthe
numberofroutersyourteamowns.ExampleDeviceName:Team2853-1
➠SettheLANConnectiontype:“StaticIP"
➠ConfiguretheIPv4Address,SubnetMask,andDefaultGateway
IPAddress:10.xx.yy.1
xx.yy=YourTeamNumber
xxcanbothbetheonedigitifyourteamhasathree-digitnumber
ExampleIPAddress:10.28.53.1
SubnetMask:255.0.0.0
DefaultGateway:10.28.53.4
AutomaticConfiguration
39
FRCElectricalBible
➠WirelessSettings
EnableWireless:
CheckmarktheBox
SettoAlways
WirelessNetworkName:
Nameitto(whateveryouwant)
AutomaticConfiguration
40
FRCElectricalBible
WirelessSecurityMode:
SecuritytoWPAPersonal
WPAmodetoWPA2Only
CipherTypetoAES
Pre-sharedkeyistheNetworkSecurityKey
AutomaticConfiguration
41
FRCElectricalBible
ManualConfiguration
1. Openupyourwebbrowser(Firefox,Chrome,etc.)
2. Intheaddressbar,typeintheIPaddressoftherouter.It’seither:
192.168.1.1,thedefaultIPaddressOR
10.xx.yy.1,wherexxisthefirsttwodigitsofyourteam’s#(itcanbeonedigitif
yourteamhasathree-digit#)andyyisthelasttwoOR
typeindlinkap/andhitenter.
3. You’llgetapromptfortherouternameandpasswordliketheoneshownbelow.Ona
brandnewrouterorarouterthatwasreseted,thelogininfowillbethis:
UserName:Admin
NoPassword(bydefault)
➠Setup:LANSettings
ManualConfiguration
42
FRCElectricalBible
➠SetaDeviceName:Teamxxxx-y
xxxx=Yourteamnumbertoavoidconfusion.
y=Arbitrarybutuniquenumbertoyourroutertoavoidconfusion.Youshouldbaseiton
thenumberofroutersyourteamowns.
ExampleDeviceName:Team2853-1
➠SettheLANConnectiontype:“StaticIP”
➠ConfiguretheIPv4Address,SubnetMask,andDefaultGateway:
IPAddress:10.xx.yy.1xx.yy=YourTeamNumber
ManualConfiguration
43
FRCElectricalBible
xxcanbothbethefirstdigitifyourteamhasathree-digitnumber
ExampleIPAddress:10.28.53.1
SubnetMask:255.0.0.0
DefaultGateway:10.28.53.4
➠WirelessSettings
(red)EnableWireless:
CheckmarktheBox
SettoAlways
ManualConfiguration
44
FRCElectricalBible
(green)WirelessNetworkName:
Nameitto(whateveryouwant)-youmaywanttoimplementanamingsystemsoyou
don'tgetmultipleroutersconfused.
(blue)WirelessSecurityMode:
SecuritytoWPAPersonal
WPAmodetoWPA2Only
CipherTypetoAES
Pre-sharedkeyistheNetworkSecurityKey
ManualConfiguration
45
FRCElectricalBible
TroubleshootingtheD-Link
Ensurethatallnecessarycables(Powerand/orEthernetcables)arepluggedin
securely.
Ensurethattheswitchonthebackoftherouterissetto“AP2.4GHz”unlessyouhave
specificallysettherouteranditsconfigurationtoadifferentmode.
EnsureyourrouterisnotlabeledBROKENwithelectricaltape.(Teamspecific)
Tryresettingthepowerontherouter.Removeitspowersource,wait10seconds,then
plugthepowercablebackin.Sometimeswizardscomeandmagicallyfixtherouter
whenyoudothis.
Trypoweringthroughanoutletusingthepoweradapterthatcamewithyourrouter.
Tryresettingtherouter’sdata.Getatoothpickorsomeotherthinobject,thenuseitto
holdtheresetbuttondownfor10seconds.Waitabout30secondsforittoreboot.Then,
refertotheinitialconfigurationprocessabove.
Routersdobreakdownanditspossiblethatit’ssimplybusted.However,thesethings
areexpensivesomakesureit’sbrokenbeforedeclaringthatyouneedtogetanew
one.
AdditionalResources
GettingStartedwiththe2015ControlSystem
WPILib-GettingStartedwiththe2014FRCControlSystem
GettingStartedwiththe2013FRCControlSystem
D-LinkDAP-1522UserManual
AndyMarkProductPage
TroubleshootingtheD-Link
46
FRCElectricalBible
4.DriverStation
4.1Introduction
4.2TheInterface
➠MainDisplay
➠OperationTab
➠DiagnosticsTab
➠SetupTab
➠Power&Can
➠Messages&Charts
4.3PrintingtotheDriverStation
DriverStation
47
FRCElectricalBible
Introduction
Thisisyourinterface--neat,organizedsimplicity.Itisn’tnecessarytoknowhowtowritecode
inordertousetheDriverStation,yousimplyneedtoknowthefollowing:
1. Howtodeploycode(connectingtotherobotisagiven)
2. Whatdeployedcodedoes
ThisistheprogramthatallowstototestanduseyourcodeonFRCcomponents.TheDriver
Stationisthemiddle-manbetweenyouandtherobot!,thisisyourmiddlemanbetweenyour
codeandtherobot!
DriverStationdefinitelygotanupdate:revisedappearance,morefeatures,what’snotto
love?TogetherwecanrelearnthisadjustedDriverStation,itshouldn’tbeallthatdifferent
comparedtoitslastiteration,dependingonhowyoulookatit.
Introduction
48
FRCElectricalBible
TheInterface
➠MainDisplay
Thisdisplayisindependentfromthesectionsleftandrightofthisdisplay,itwillalwaysbein
view(whileDriverStationisopenofcourse)evenifyouswitchtabsontheDriver
Station(SeeTabSelection,alsoCharts&Messages)
1. YourTeam#,thiscanbeconfiguredpersonallyintheSetupTab(SeeTabSelection
Section:➠SetupTab)
2. CurrentvoltageofthebatteryinV(volts)hasavisualindicatortotheleftintheformofa
pictorialrepresentationofabattery(fillslikeabartorepresentamountofcharge).
3. LightsindicatingtheDriverStation’sstatusondetectingit:Redmeansthereisno
connection,greenmeansaconnectionhasbeenestablished.Ifyouhoverovereachof
the3lines,atroubleshootingmessageappearsinthemessagestab(SeeCharts&
Messages)iflightisred.
4. Displayscurrentmodeenabledordisabledunlessthefirsttwolightsarered,inorder,
“NoRobotCommunication”,“NoRobotCode”(SeeTabSelection:➠OperationTabfor
modes)
➠TabSelection
TheInterface
49
FRCElectricalBible
Redboxesindicatetabselectionandthehighlightedtabisthecurrenttab,intheblueboxis
thecurrentlydisplayedtab(automaticallydisplaysOperationsTabwhenDriver
➠OperationTab
1. Thedepressedbuttoniswhatstatetheperiodisin;canpress[]\toquicklyenable,can
pressEnterbuttontoquicklydisableifthefirsttwolightsinMainDisplayarelit
(Communications&RobotCode)
2. Availablemodes,currentmodeisdepressed(Teleoperatedbydefault),youcanswitch
modesbyclickingoneofthe3buttons
3. NEW:VisualindicatorofyourPCCPU%usageElapsedTimesinceyouclicked
“Enable”untildisabled
TheInterface
50
FRCElectricalBible
➠DiagnosticsTab
1. WhattheDriverStationhascommunicationswith;ifpluggedthroughEthernetdirectlyto
something(routerorroboRIO),EnetLinkwilllightup.DSRadioisalegacyindicatorof
pingstatusofanexternalradioat10.TE.AM.4(ComparedtolastDriverStation,thislight
willusuallynotbelitexceptunderspecificcircumstances[TESTING])Bridgewillbelitif
connectedtotherouter,RobotwillbelitifitcancommunicatewiththeroboRIO.FMS
shouldbelitifatcompetitionsinceitismandatorytocommunicatewiththeField
ManagementSystem.Ifunlit,youcanhoveroverthemfortroubleshootingtipsinthe
messagesbox(SeeMessages&Charts)
➠SetupTab
TheInterface
51
FRCElectricalBible
1. Configureyourteam#here,clickontheboxtypeitinandboom
2. PracticetimingcontrolshowlongCountdowntillstartofeachperiod,Autonomous,
Teleoperated,andhowlongendgameis.Delayishowmuchtimeisinbetween
AutonomousandTeleoperated.
3. Typeofdashboardyouwanttobringup,defaultautobringsupFRCPCDashboard
(ScreenStepsacknowledgesanissuewithsettingDashboardtypetoJavaorC++soto
startuptheSmartDashboardwouldrequiresettingthedefaulttoSmartDashboard),
LabviewbringsupFRCPCDashboard,C++andJavashouldbringup
SmartDashboard,andremoteisifthedashboardisonaseparatecomputer/device
4. FieldManagementSystemprotocol,protocolforDStoFieldManagementSystem
communication;shouldbeautosetto‘15whichrequiredfor2015competition.Unless
youwereparticipatinginweekzeroeventsin2014,thiswon’thavetobetouched
➠USBDevicesTab
1. USBSetuplistholdsallcompatibledeviceshookeduptotheDriverStation(AKA,
Laptop,usually2,butwithUSBsplitter,youcanconnectmore)Ifyoupressabuttonon
aconnecteddevice,itshouldbeprecededbytwoasterisks(**)andhighlightedin
green.TherescanbuttonforcesasearchoforforUSBdevices.Whiledisabled,it
automaticallyupdatesUSBdevices.UsetherescanbuttonorpressF1toforcesearch
duringamatch.
Locking&Rearranging
TheInterface
52
FRCElectricalBible
1. TorearrangeUSBdevices,drag&drop.Whenyoudrag&dropordoubleclickonone
ofthedevices,itunderlinesthedevicemeaningitis“locked”Lockeddevicesreserve
theslotevenwhiledisconnecteduntilreconnected,representedbygreyedoutand
underlined.
➠Power&CAN
1. AmountoffaultsthatoccurredsincelastconnectiontoDriverstation;CommsmeanDS
torobotcommunication,12VisBrownouts(SeeroboRiofordetails),6V/5V/3.3Vare
UserVoltageRailfaults(typicallyshortcircuits)
2. Utilization%isasitstatesandtheother4aretypesofCANfaultssincelastconnection
toDriverStation
➠Messages&Charts
TheInterface
53
FRCElectricalBible
1. LogsisanindependentbuttonofthetabsonthissectionoftheDS
2. Clearsallmessagescurrentlyinthebox
3. MessageFilter:Fillediniconfiltersoutwarningsfrombeingpostedinmessagebox,
Outlinepostseverything
4. Themessagebox,troubleshootingtipsappearhere,messageswillappearhere
Logs
LoadsuptheDSLogFileViewer,youcanviewmessages&eventdatainonedisplay,atool
usuallyusedfortroubleshooting.Thistoolhasitsownsectiontobeaddedelsewhere.
5.Chartstriptimefordatatorobotwithagreenlinevstherightaxis,lostdatapacketstothe
robotisin“blue”vstheleftaxis
6.Graphsbatteryvoltagewithayellowlinevstheleftaxis,roboRIOcpu%usagewithared
linevstherightaxis
7.Timescaleforthetimeaxisofthegraphs(12s,1m,5m)
TheInterface
54
FRCElectricalBible
PrintingtoDriverStation
Withthe2015updateoftheDriverStation,amaximumof10linesofstrings(eachallowing
for21characters)canbemanipulatedtoprinttotheDriverStationconsole.Notethatthe
DriverStationLCDClasswasremovedentirely,andnowprintingisdonethroughthe
Smartdashboard.
UnliketheDiverStationLCDprintconsole,itispossibletotypedirectlyintothestringfields
aswellasreadthesestringswithinyourrobotcode.Someteamsmayfindthisusefulwhen
testingtheirrobotcode.
StringscanbesenttotheSmartdashboardprintconsoleusingthefollowingcode:
SmartDashboard::PutString("DB/String0","Thisisastring");
SmartDashboard::PutString("DB/String1","Thisisanotherstring");
SmartDashBoard::PutStringiscallingtheSmartdashboardandallowsyoutosendstringsto
theDriverStationprintingconsole.EachlineisassignedanamefromDB/String0to
DB/String9fromtoptobottomthenlefttoright.Thesecondsetofquotationscanbe
manipulatedtosendvariousstrings.
StringsthatareonorweresenttotheSmartdashboardcanthenberetrievedusingthe
followingcode:
std::stringdashData=SmartDashboard::GetString("DB/String0","myDefaultDa
std::stringdashData=SmartDashboard::GetString("DB/String1","myDefaultDa
HerewearecreatingastringwithinthecodecalleddashDatathatissettothestringthat
wasinthefirstandsecondlineontheSmartDashboardprinterconsole.
PrintingtoDriverStation
55
FRCElectricalBible
PrintingtoDriverStation
56
FRCElectricalBible
5.ACrashCourseonC++
5.1Variables
➠DefiningVariables
➠Instantiating
➠Constants
5.2Functions
➠ArithmeticFunctions
➠RelationalOperators
➠LogicalOperators
5.3ObjectUsage
➠DefiningObjects
➠InstantiatingObjects
➠UsingMethods
5.4TheJoystick
➠SampleCode
➠Explanation
ACrashCourseonC++
57
FRCElectricalBible
Variables
Avariableisalocationinthecomputer’smemorywhichallowsyoutostoreavaluewhich
canlaterbereceived.Variablesareassignednames,whichallowyoutoquicklyandeasily
accessthelocationinmemorywherethevariable’sdataisstoredwithouthavingtoknowthe
actualmemoryaddress.
Whenyoudefineavariable,youmustalsodeclarethedatatypeofthatvariable.The
datatypeofthevariabledetermineswhatkindofdatathevariableisholdingaswellashow
muchmemorymustbesetasideforthatvariable.Anexampleofadatatypewouldbean
integerwhichisdeclaredwiththe‘int’command.Integervariablesstorewholenumber
values.
Differentdatatypesrequireadifferentamountofmemory,butsincetheuseofC++inthis
competitiondoesnotrequireyoutoknowthedetailstodatatypememoryitwillnotbe
reviewedinthissection.
ThetablestofollowwereadaptedfromSamsTeachYourselfC++in24Hours.
VARIABLETYPES
VALUES
unsignedshortinteger
0to65,535
shortinteger
-32,768to32,767
unsignedlonginteger
0to4,294,967,295
longinteger
-2,147,483,648to2,147,483,647
integer
-2,147,483,648to2,147,483,647
unsignedinteger
0to4,294,967,295
longlong
-9.2quintillionto9.2quintillion
char
256charactervalues
boolean
trueorfalse
float
1.2e-38to3.4e38
double
2.2e-308to1.8e308
➠DefiningVariables
Definingavariableisveryeasy.Generally,theformatfordefiningavariableisthedatatype
followedbythenameyouwanttoassignyourvariablefollowedbyasemicolon.
Variables
58
FRCElectricalBible
inttheExample;
booliAmAmazing;
Youmustrememberthattherearerulesandguidelinestonamingvariables.Among
programmers,thereispropernamingetiquettewhichallowssomeonewhoisreadingyour
codetoeasilyunderstandwhyyounamedavariableacertainway.Hereisalistofrulesand
guidelinestofollowtosuccessfullynameavariable:
Rules:
1. Variablenamescanbemadewithanycombinationofletters
2. Variablenamescannotcontainspaces,symbols,orpunctuationmarks
3. Variablenamesmayincludeunderscores
4. Variablenamescannotbeginwithanumberbutmaycontainanumberelsewhereinthe
name
5. Variablenamescannotbethesameasreservedkeywords.Seebelowtablefora
completelistingofreservedwords.
6. C++iscasesensitivesokeepthisinmindwhilenamingvariables(intmyIntreferstoa
differentlocationthanintMyIntorintmyint)
Guidelines:
1. Constantsareusuallywritteninallcaps
2. Variablesareusuallystartedwithlowercaseandifanamecontainsmorethanone
word,thefirstletterofthenextwordiscapitalized(eg:intthisIsAnExample)
3. Variablesshouldbenamedsomethingthedescribeswhatthevariableisgoingtobe
usedfor
4. Avoidgivingvariableslongnames,itisokaytoabbreviatelongwords
ReservedWords(C++)
alignas(sinceC++11)
alignof(sinceC++11)
and
and_eq
asm
auto(changedinc++11)
bitand
Variables
59
FRCElectricalBible
bitor
bool
break
case
catch
char
char16_t(sinceC++11)
char32_t(sinceC++11)
class
compl
const
constexpr(sinceC++11)
const_cast
continue
decltype(sinceC++11)
default(changedinC++11)
delete(changedinC++11)
do
double
dynamic_cast
else
enum
explicit
export(1)
extern
false
float
for
friend
goto
if
inline
int
long
mutable
namespace
new
noexcept(sinceC++11)
not
not_eq
Variables
60
FRCElectricalBible
nullptr(sinceC++11)
operator
or
or_eq
private
protected
public
register
reinterpret_cast
return
short
signed
sizeof
static
static_assert(sinceC++11)
static_cast
struct
switch
template
this
thread_local(sinceC++11)
throw
true
try
typedef
typeid
typename
union
unsigned
using(1)
virtual
void
volatile
wchar_t
while
xor
xor_eq
Adaptedfromcppreference.com
Variables
61
FRCElectricalBible
BelowisanexampleofhowtodefinevariablesintheC++language:
main()
{
inta;
intohMyLord;
charmyChar;
}
Todefinemorethanonevariableofthesamedatatype,youcanusethecomma
punctuation.
main()
{
inta,b,c;
charohMahGlob,lumpySpacePrincess,partyTime;
booldownLieToMe,cats;
}
➠Instantiating
Instantiatingavariableisalsoknownasassigningavariablewithavalue.Theoperator
usedtoassignvaluestoavariableistheequalssign,(=).
Thevariablethatthedataisbeingassignedtoisalwaysontheleftside,whilethedatathat
isbeingassignedtothevariableisontheright.Itisimportanttonotmixthisupbecause
variablescanalsobeassignedvaluesfromsimilarvariabletypes.Thisiscommonwhile
usingmathfunctionswithothervariables.
main()
{
inta=5;
intb=10;
intc=a;
charcharacter=‘A’;
boolcounter=true;
}
➠Constants
Variables
62
FRCElectricalBible
Sometimesinprogramming,wehavevariableswithdatathatwedonotwanttochangeat
all.Althoughyoucouldeasilyjustnotchangethevariabledata,itissafertodeclarea
constantvariable.Aconstantvariableisavariablethatcannotbechangedonceitis
instantiated.
main()
{
constintTHIS_IS_A_CONSTANT=100;
}
Variables
63
FRCElectricalBible
Functions
InC++,therearebasicallythreetypesoffunctions:arithmeticfunctions,relationalfunctions,
andlogicalfunctions.
➠ArithmeticFunctions
Thesetypesoffunctionsareyourbasicmathfunctionsandareusedinconjunctionwith
numericdatavaluesandvariables(int,double,float).Itisimportanttorememberthatorder
ofoperationsdoesapplytothesefunctions.
Youshouldbeabletorecognizethesefunctionsasyouhaveusedthemsinceelementary
school.Theonlyonethatyoumaynotbefamiliarwithisthemodulusfunction,whichdivides
twonumberstogetherandreturnstheremainder.Thisfunctioniscommonlyusedintruefalsestatementsorloopstorecognizewhenanumericalvariablebeinganalyzedispositive
ornegativeoramultipleofacertainnumber.Parenthesesareusedlikeinalgebratosay
whichoperationsshouldbedonefirstifthoseactionsdifferfromthedefaultorderof
operations.
Inprogramming,itisalsoquiteoftentousevariablesinconjunctionwitharithmetic
functions.Tousevariablesinthisway,allyouneedtodoisusethevariable’sdefinedname
wherenumberswouldusuallybeused.It’sthesameasbasicalgebra.
Sign
Meaning
+
Addition
-
Subtraction
/
Division
*
Multiplication
%
Modulus
=
AssignmentOperator
(operatorhere)
Parenthesis(orderofoperation)
++/--
Increment/decrementnumericvalueby1
Functions
64
FRCElectricalBible
main()
{
inta=5;
intb=10;
intc=a+b;
intd=c*a;
inte=a(3+b);
intf=b%2;
a++;
}
intaisassignedthevalue5and intbisassignedthevalue10. intc,isthesumofa
andb.Because aand bareassignedthevalue5and10,respectively, ciscurrentlyat
avalue15.Itcanbesubjecttochangeintheeventthevalues aandbchange. intdis
theproductof cand a,(15*5).int eistheproductof aandthesumof 3+b. intfis
theremainderof bdividedby2(itwillreturn avalueofeither0or1).
➠RelationalOperators
Relationaloperatorsareusedtodeterminewhethertwonumbersareequal,orwhetherone
isgreaterorlessthantheother.Everyrelationalexpressionreturnseither1(true)or0
(false).Theseoperatorsareusedinstatements(if,else,while)inordertocreate
expressionsthatsetconditionsforthatcodeinsidethestatement.Besurenottoconfusethe
assignmentoperator(=)withtherelationoperatorofequality(==).
Functions
65
FRCElectricalBible
Name
Equals
Operator
==
NotEquals
Greaterthan
Greaterthanorequals
Lessthan
Lessthanorequals
!=
>
>=
<
<=
Sample
Evaluation
100==50;
false
50==50;
true
100!=50;
true
50!=50;
false
100>50;
true
50>50;
false
100>=40;
true
50>=50;
true
100<50
false
50<50;
false
100<=50
false
50<=50
true
➠LogicalOperators
Logicaloperatorsareusedinconjunctionwithrelationaloperatorstocreatemorecomplex
statementexpressions.
OPERATOR
SYMBOL
AND
OR
EXAMPLE
&&
2:2
(2pipes)
2:3
!
2:4
NOT
AlogicalANDstatementevaluatestwoexpressions,andifbothexpressionsaretrue,the
logicalANDstatementistrueaswell.
AlogicalORstatementalsoevaluatestwoexpressions.Ifeitherorbotharetrue,theentire
expressionistrue.
ANOTstatementcompareswhetheraconditionisNOTwhatisstated(i.e.switchesthe
returnvaluefromtruetofalseandviceversa).
Whenusinglogicaloperatorstoformstatements,makesureyouuseparenthesestomake
theorderofprecedenceclearertothecompilertoavoidanyerrors.Forexample,
if(x>5&&y>5||z>5)
Functions
66
FRCElectricalBible
Thisstatementgoestoshowhowambiguousthesestatementscangetifparenthesesare
notused.Doyouwantthestatementtoreturntrueifx>5andy>5orwhenjustz>5,ordid
youwantthestatementtoreturntruewhenx>5andwheneithery>5orz>5?Ifyouwanted
thelatter,thenyoushouldrewritethestatementtomakethingsclearer:
if((x>5&&y>5)||z>5)
Functions
67
FRCElectricalBible
ObjectUsage
Inobject-orientedprograms(OOP),objectsarebasicallyobjectslikethatoftherealworld,
andthushavecertainbehaviorsandcharacteristics.CharacteristicsofanobjectinOOP
includeanyvariablesorotherobjectsthataredeclaredintheclassthattheobjectiswritten
in.Behaviorsofanobjectaremethodsthattheobjectcontainsinitsclasscode.
WewillusetheJaguarclassfromtheWPIlibrarytohelpexplainthissection.Clickhereto
viewit.
➠DefiningObjects
Definingobjectsisasimilartodefiningvariables,butinsteadthedatatypeisreplacedbythe
nameoftheobject.Aftertheobjectnamecomesthenamethatyouassigntotheaddress
locationoftheobject.IntermsoftheJaguarclass,aJaguarobjectisdefinedas:
Jaguarjag1;
Jaguarjag2;
Jaguarexample;
RememberthateachJaguarobjectthatyoucreateisadifferentinstanceoftheobjectand
thatdifferentspacesinmemoryarecreatedforinstancevariablesofeachJaguarobject.
ThenameyougavetoaJaguarobjectistheonlythingyouhavetodistinguishbetween
Jaguars.
➠InstantiatingObjects
Instantiatinganobjectisquitedifferentfromdefiningavariable.Wheninstantiatingan
object,youmustusethe newoperator.Followedbythe newoperatoristheobject’s
constructorsignature.Anobject’sconstructorsignaturemaylooklikethis:
Jaguar(UINT32channel)
Asyoucanseetheobjectnameisdisplayedalongwithsomecodeinsideparentheses.The
codeinsidetheparenthesesiscalledaparameter.Parametersarewhereyoupassdatainto
theobjectsothattheobjectcanuseit.Noticethatdatainparametersareseparatedby
commas.Intheabovecase,theobjectconstructorasksyoutoinputafloatandachannel
number.Soanexampleinstantiationwouldlooksomethinglikethefollowing:
ObjectUsage
68
FRCElectricalBible
jag1(1)
Where 1isthenumberofa UINT32channel(thePWMOUTportthejaguaroccupieson
thedigitalsidecar).
Objectclassesoftenhavemultipleconstructorswhichaskfordifferentsetsofparameters.In
thecaseoftheSolenoidclass,herearethefollowingconstructorsforaSolenoidobject.
Solenoid(uint32_tchannel)//ConstructorusingthedefaultPCMID
Solenoid(uint8_tmoduleNumber,uint32_tchannel)//Constructorthatspecifi
Youshouldseethattheonlythingdifferentistheparametersthatmustbecalled.Thefirst
callsforthePCMchannelonly(assumesthePCMIDas 0).Tocallthefirstconstructor
afterdefining sol1,youwouldtype:
sol1(1)
whichmeans sol1isassignedtoPWMport 1onthePCMandisautomaticallyassumed
tobeonthePCMIDof 0.
BecausetheroboRIOcansupportmorethanonePCM,anythingconnectedaPCMwithan
IDthatisnot 0willneedtousethesecondconstructor.
➠UsingMethods
Inprogramming,objectsalonedonomorethantheydoinreality.Simplystating“theJaguar
exists!”willnotmakeyourrobotmove,norwillmerelydeclaringitinyourcodemake
anythinghappen.
Therealworkisdonethroughmethods,auniquesetofcommandsthateachobjecthas.
Thesearenotedbya .afterthenameofaparticularobjectandarealwaysfollowedby
(),thoughoftentherearesomevaluespassedintotheparentheses.IntheJaguarclass,
forexample,onemightseethefollowingcodefragment:
jag1.Set(0.5);
Thenameoftheobjectis jag1,whichhaspreviouslybeendeclaredtobeaJaguar.The
methodis Set,which,asonemightexpect,setsthespeedofthemotor.The 0.5inside
theparenthesesiscalledtheparameter,whichvariesdependingonthemethodused.Here,
ObjectUsage
69
FRCElectricalBible
itisafloatvaluefrom -1to 1,inclusive,butoftenyoumustpassanint,bool,oreven
anotherobjectasaparameter.Forobject-specificinformationonmethodsandparameters,
seethesectiononthatparticularobjectorusetheWPILibrary.
Notethatjustaseachobjectwillhavemultiplemethods,differentobjectscanhavemethods
ofthesamenameandmayormaynotdodifferentthings.TheVictorclass,forexample,
alsohasaSetmethodthatfunctionsexactlythesame,buttheRelayclasstakesanentirely
differentdatatypeandfunctionspurelyasanon/offswitch.
ObjectUsage
70
FRCElectricalBible
TheJoystick
LogitechGamepadF310
Logitechhasmadeahome-touch-feelycontrollerasitappearstobeastandardcontroller.
Mostpeoplehaveplayedvideogameswithacontrollerlikethis,sothere’snothingnewto
learnaboutit.Onthebackisalittleslidebutton,makesureitissettotherightandtapeit
likethattopreventincidentsofbadjoystick.Makesuremodelightisoff.
AndyMark
TheJoystick
71
FRCElectricalBible
LogitechAttack3USBJoystick
ThisAttack3Joysticklooksawesome,doesn’titexudethefeelingofrobotics?Onehandto
movethesinglejoystick,theothertopressthebuttonsonthebottom.Thejoystickclassin
theWPILibrarydoessupportthisjoystickandallifitsmanyinputs.
FIRSTChoice
JoystickClass(C++)
➠SampleCode
TheJoystick
72
FRCElectricalBible
#include"WPILib.h"
classRobot:publicSampleRobot
{
Joystickstick;
public:
Robot():
stick(0)//Usejoystickonport0.
{
}
voidOperatorControl()
{
while(IsOperatorControl())
{
if(stick.GetRawAxis(1)>.2)
{
}
if(stick.GetRawAxis(2)>.2)
{
}
if(stick.GetRawButton(1)==1)
{
}
if(stick.GetRawButton(4)==1)
{
}
if(stick.GetTop()==1)
{
if(stick.GetRawAxis(3))
{
}
if(stick.GetRawAxis(4))
{
}
}
}
}
};
START_ROBOT_CLASS(Robot);
TheJoystick
73
FRCElectricalBible
➠Explanation
Joystickstick;
Declareone Joystickobject.Declaredbetween classRobotDemo:publicSampleRobot
and public:RobotDemo(void):
stick(0);
Instantiateone JoystickobjectinUSBportofcomputer(limitedto#ofUSBportson
computer).Instantiationoccursbetweenthe public:RobotDemo(void):andthebraces( {
}).Ifnotthelastinstantiatedobjectinlist,itneedsacommaafterinstantiationstatement
likelisting.Ifitis,itdoesnotneedanypunctuationaftertheinstantiationbeforethebraces;
nocomma,nosemicolon,noperiod,etc.Ifsyntaxnotfollowed,erroroccurs.
TheJoystick
74
FRCElectricalBible
voidOperatorControl()
{
while(IsOperatorControl())
{
if(stick.GetRawAxis(1)>.2)
{
}
if(stick.GetRawAxis(2)>.2)
{
}
if(stick.GetRawButton(1)==1)
{
}
if(stick.GetRawButton(4)==1)
{
}
if(stick.GetTop()==1)
{
if(stick.GetRawAxis(3))
{
}
if(stick.GetRawAxis(4))
{
}
}
}
}
Joystickfunctionsarethesauceforconditionsin OperatorControl.Bydoingcertainactions
onthejoystickobject(thisinstanceisusingaLogitechF310Gamepad),itexecutesthe
codethatwouldbewritteninthebraces.Forexample, GetRawAxis(1)correspondstothe
leftsticky-axis(upanddown)oftheF310Gamepadorthey-axisoftheExtreme3DPro
joystick;the||(or)correspondstopositive(up)ornegative(down)input.Theaxisisusually
associatedwithdrivingtherobot. GetRawButton()onlyreturns1ifitisbeingpressed;
GetRawButton(1)isthex-buttonontheF310GamepadorthetriggeroftheExtreme3DPro
joystick. GetTopisthesmallerstickontheExtreme3DPro,anditonlyreturns 1iftopis
beingusedor 0ifnot,soextraconditionsforaxis3&4,y-axisandx-axisoftop
respectively.FortheF310Gamepaditwouldbeaxis6&5,y-axisandx-axisrespectively.
TheJoystick
75
FRCElectricalBible
6.MotorControllers
6.1GeneralOverview
6.2Motors
➠MotorControllerVarieties
6.3Jaguar
➠SampleCode
➠Explanation
6.4Victor888
➠SampleCode
➠Explanation
6.5Talon
➠SampleCode
➠Explanation
6.6TalonSRX
➠Wiring
➠CAN
➠SampleCode
➠Explanation
6.8Spike
➠SampleCode
➠Explanation
MotorControllers
76
FRCElectricalBible
6.9Fans
MotorControllers
77
FRCElectricalBible
GeneralOverview
Motorcontrollersarewhattheysoundlike;theyallowustocontroltheamountofpowersent
tothemotor.TheyserveasthemiddlemenfromthePDBtothemotoritself.
GeneralOverview
78
FRCElectricalBible
Motors
CIMmotor
PhysicalSpecs
Size:2.5inchdiameter,4.34inchlongbody
OutputShaftsize:0.313+/-0.0004,with2mmkeyway
Weight:2.82pounds
MountingHoles:#10-32tappedholes(2),ona2"boltcircle
Performance
Voltage:12voltDC
NoloadRPM:5,310(+/-10%)
FreeCurrent:2.7ampsMaximumPower:337Watts(at2655rpm,172oz-in,and68
amps)
StallTorque:2.42N-m,or343.4oz-in
StallCurrent:133amps
AndyMark
mini-CIMmotor
Motors
79
FRCElectricalBible
⅔powerofCIM,similarformfactorandsamemounting
PhysicalSpecs
OutputShaftsize:8mm(0.314in)with2mmkeyway
Size:2.5”diameter,3.36”long
Weight:2.16lbs
Performance
FreeSpeed:6,200rpm(+/-10%)
FreeCurrent:1.5A
MaximumPower:230W
StallTorque:12.4in-lbs[1.4N-m]
StallCurrent:86A
MountingHoles:(4)#10-32tappedholesona2"boltcircle
Vex
WindowMotor
Motors
80
FRCElectricalBible
Makesureyouremovethelockingpins.
StallTorque:9.3Nm
FreeSpeed:92RPM
FreeCurrent:2.5A
StallCurrent:25A
Servo
ShouldnotbehookeduptoANYmotorcontrollersanddirectlytothePWMportinthe
roboRIO.
AndyMark
➠MotorControllerVarieties
Motors
81
FRCElectricalBible
Itispossibletocontrolallthemotorsabove(excepttheservo)withthebelowmotor
controllers;however,thebreakersusedhavetobeabletoprotectthewiresandprovide
enoughpowerforthemotorused.Forexample,itispossibletoconnect16gaugewirewith
a20ampCBtoatalon,butwouldnotprovideenoughpowerifconnectedtosayaCIM.
Therearetwosidewiresthatconnecttoeachmotorcontroller:theM-/M+andtheV-/V+
side.The‘M’standsforMotor,whichdenotesthewiresattachedhereshouldbetheones
alsoattachedtothemotor.TheothersideconnectstothePDB.Inbothcases,thepower
goestothe+andgroundtothe-.ThereisalsoathinslotwherePWMcablesplugintofrom
theDigitalSidecar,withitsdirectionbasedonthesmallnotationsonthemotorcontrollers
(often,groundisfacingthesidemarkedwitha‘B’).
Motors
82
FRCElectricalBible
Jaguar
Therearejumpersthatcanbeusedintwoplaces,themotorcoast/brake,andtheLimit
Switches.Themotorcoast/brakecontrolsifaftertherobotstopsitslowlydecelerates
(coasts),orimmediatelydecelerates(brakes).Thejumpersaretobeinstalledinthelimit
switchareaiftherearenolimitswitchesbeingused.JaguarsusetheCANnetworkfolder.
ThestatusLEDindicatesmanythingslikeoperation,fault,calibration,andotherconditions
usingyellow,red,andgreenlights.
Jaguar
83
FRCElectricalBible
Jaguar
84
FRCElectricalBible
➠SampleCode
JaguarClass(C++)
Jaguar
85
FRCElectricalBible
#include"WPILib.h"
classRobotDemo:publicSampleRobot{
Jaguarjaguar;
Joystickstick;
public:
RobotDemo(void):
jaguar(1),
stick(1)
{
}
voidOperatorControl(){
if(stick.GetRawButton(1)){
jaguar.Set(1.0);
}
elseif(stick.GetRawButton(2)){
jaguar.Set(-1.0);
}
else{
jaguar.Set(0);
}
}
};
START_ROBOT_CLASS(RobotDemo);
➠Explanation
Jaguarjaguar;
DeclareJaguarmotorcontrolleras jaguar;declaredbetween publicSampleRobotand
public:RobotDemo
jaguar(1),
Jaguar
86
FRCElectricalBible
InitializeJaguarmotorcontrollerasport#1inDigitalSidecar(PWMOut),initializedbetween
public:RobotDemoandthebraces({}).Ifitisnotthelastobjectinitialized,itneedsa
commalikealist.Ifitisthelastobjectinitialized,nopunctuation;nocomma,nosemicolon,
noperiod,etc.oryouwillgetanerror.
voidOperatorControl(){
if(stick.GetRawButton(1)){
jaguar.Set(1.0);
}
elseif(stick.GetRawButton(2)){
jaguar.Set(-1.0);
}
else{
jaguar.Set(0);
}
}
Joystickclassisgoneintodepthinanearliersectionofthismanual.Motorcontrollersare
putintoresultsofconditionsbecauseafree-spinningmotorisawasteofpowerandthereis
nocontroloverthemotor(whichiswhyitisamotorcontroller)The .Setmethodofthe
classacceptsafloatbetween-1.0to1.0asaparameterandsetsthespeedofthemotorto
thatfloat.1.0isfullspeed“forward”,-1.0isfullspeed“backward.”Themotorwheninitialized
beginsat .Set(0).The elsejaguar.Set(0)istostopthemotorbecauseunlessthemotor
controllerissetto0,themotorremainsatthelast .Set()value.
Jaguar
87
FRCElectricalBible
Victor888
Thevictorissimilartothejaguar,butsacrificescomputingpowerforalighterweightanda
smallersize.
Victor888
88
FRCElectricalBible
Whenwiring,makesurethatthePWMispluggedinsothattheblackwireisfacingthe
inside(towardsthefan).PayspecialattentiontotheM+M-V+andV-onthesidesofthe
Victorwhenwiringittothemotorandthepowerdistributionboard.
Victor888UserManual
Victor888-VEXStore
➠SampleCode
VictorClass(C++)
#include"WPILib.h"
classRobotDemo:publicSampleRobot{
Victorvictor;
Joystickstick;
public:
RobotDemo(void):
victor(1),
stick(1)
{
}
voidOperatorControl(){
if(stick.GetRawButton(1)){
victor.Set(1.0);
}
elseif(stick.GetRawButton(2)){
victor.Set(-1.0);
}
else{
victor.Set(0);
}
}
};
START_ROBOT_CLASS(RobotDemo);
➠Explanation
Victor888
89
FRCElectricalBible
Victorvictor;
Declarevictormotorcontrolleras victor;declaredbetween publicSampleRobotand
public:RobotDemo
victor(1),
Initializevictormotorcontrollerasport#1inDigitalsidecarPWMOut.Thisisstated
between public:RobotDemoandthebraces( {}).Ifitisnotthelastobjectinitialized,it
needsacommalikealist.Ifitisthelastobjectinitialized,nopunctuation;nocomma,no
semicolon,noperiod,etc.oryouwillgetanerror.
voidOperatorControl(){
if(stick.GetRawButton(1)){
victor.Set(1.0);
}
elseif(stick.GetRawButton(2)){
victor.Set(-1.0);
}
else{
victor.Set(0);
}
}
Joystickclassisgoneintodepthinanearliersectionofthismanual.Motorcontrollersare
putintoresultsofconditionsbecauseafree-spinningmotorisawasteofpowerandthereis
nocontroloverthemotor(whichiswhyitisamotorcontroller)The .Setmethodofthe
classacceptsafloatbetween -1.0to 1.0asaparameterwhichsetsthespeedofthe
motortothatfloat. 1.0isfullspeed“forward”, -1.0isfullspeed“backward.”Themotor
wheninitializedbeginsat .Set(0).Theelse victor.Set(0)istostopthemotor;unlessthe
motorcontrollerissetto 0,themotorremainsatthelast .Set()value.
NOTE:The883,884and885modelshavebeendiscontinued,butthemanufacturer’s
documentationcanbefoundbelow.
Victor883/885UserManual
Victor884UserManual
Victor888
90
FRCElectricalBible
Talon
Thetalonisinterchangeablewiththejaguar.Ithasapeakoutputof100Aand60A
continuouscurrent.Therearemountingholesforanoptional40mmfan.TheLEDonthe
talonisastatusindicator.
TalonUserManual
➠SampleCode
Talon
91
FRCElectricalBible
TalonClass(C++)
#include"WPILib.h"
classRobotDemo:publicSampleRobot{
Talontalon;
Joystickstick;
public:
RobotDemo(void):
talon(1),
stick(1)
{
}
voidOperatorControl(){
if(stick.GetRawButton(1)){
talon.Set(1.0);
}
elseif(stick.GetRawButton(2))
{
talon.Set(-1.0);
}
else{
talon.Set(0);
}
}
};
START_ROBOT_CLASS(RobotDemo);
➠Explanation
Talontalon;
Declaretalonmotorcontrolleras talon;declaredbetween class:SampleRobotand
public:RobotDemo.
talon(1),
Talon
92
FRCElectricalBible
Initializetalonmotorcontrollerasconnectedtoport#1intheDigitalSidecar(PWMOut);
initializedbetween public:RobotDemoandthebraces( {}).Ifitisnotthelastobject
initialized,itneedsacommalikealist.Ifitisthelastobjectinitialized,nopunctuation;no
comma,nosemicolon,noperiod,etc.oryouwillgetanerror.
voidOperatorControl(){
if(stick.GetRawButton(1)){
talon.Set(1.0);
}
elseif(stick.GetRawButton(2)){
talon.Set(-1.0);
}
else{
talon.Set(0);
}
}
Joystickclassisgoneintodepthinanearliersectionofthismanual.Motorcontrollersare
putintoresultsofconditionsbecauseafree-spinningmotorisawasteofpowerandthereis
nocontroloverthemotor(whichiswhyitisamotorcontroller)The.Setmethodoftheclass
acceptsafloatbetween -1.0to 1.0asaparameterwhichsetsthespeedofthemotorto
thatfloat. 1.0isfullspeed“forward”, -1.0isfullspeed“backward.”Themotorwhen
initializedbeginsat .Set(0).Theelse talon.Set(0)istostopthemotor;unlessthemotor
controllerissetto 0,themotorremainsatthelast .Set()value.
Talon
93
FRCElectricalBible
TalonSRX
TheTalonSRXisanewiterationoftheTalonmotorcontrollerseriesthatwasintroducedin
the2015FRCseason.TheSRXisuniqueasitisCANenabledandcapableofoperating
withtheroboRIO,PCM,andVRM,whichalluseCANprotocols.BecausetheTalonSRX
wasdesignedwithoutabuilt-inventilationsystem,youshouldmountitinanareawith
adequateairflow.Theuserguiderecommendsmountingittotherobot’smetalframe
becauseitwillactlikeagiantheatsink.
Specs
Dimensions:2.75”x1.85”x.96”tall
Weight:.2lbsincludingwires
15kHzoutputswitchingfrequency
60AmpContinuouscurrent,100Amp
2xMountingHoles(oneateachend,6-32fasteners)
SupportsCAN(ControllerAreaNetwork),SPI(SerialPeripheralInterface),DigitalI/O,
andUSART(UniversalSynchronous/AsynchronousReceiver/Transmitter)
➠Wiring
TalonSRX
94
FRCElectricalBible
➠Can
TalonSRX
95
FRCElectricalBible
TalonSRXUserManual
➠SampleCode
TalonSRXClass(C++)
TalonSRX
96
FRCElectricalBible
#include"WPILib.h"
classRobotDemo:publicSampleRobot{
TalonSRXtalonsrx;
Joystickstick;
public:
RobotDemo(void):
talonsrx(1),
stick(1)
{
}
voidOperatorControl(){
if(stick.GetRawButton(1)){
talonsrx.Set(1.0);
}
elseif(stick.GetRawButton(2)){
talonsrx.Set(-1.0);
}
else{
talonsrx.Set(0);
}
}
};
START_ROBOT_CLASS(RobotDemo);
➠Explanation
TalonSRXtalonsrx;
DeclareTalonSRXmotorcontrolleras talon;declaredbetweenpublicSampleRobotand
public:RobotDemo
talonsrx(1),
InitializetalonSRXmotorcontrollerasconnectedtoport#1intheDigitalSidecar(PWM
Out);initializedbetween public:RobotDemoandthebraces( {}).Ifitisnotthelastobject
initialized,itneedsacommalikealist.Ifitisthelastobjectinitialized,nopunctuation;no
comma,nosemicolon,noperiod,etc.oryouwillgetanerror.
TalonSRX
97
FRCElectricalBible
voidOperatorControl(){
if(stick.GetRawButton(1)){
talonsrx.Set(1.0);
}
elseif(stick.GetRawButton(2)){
talonsrx.Set(-1.0);
}
else{
talonsrx.Set(0);
}
}
Joystickclassisgoneintodepthinanearliersectionofthismanual.Motorcontrollersare
putintoresultsofconditionsbecauseafree-spinningmotorisawasteofpowerandthereis
nocontroloverthemotor(whichiswhyitisamotorcontroller)The.Setmethodoftheclass
acceptsafloatbetween -1.0to 1.0asaparameterwhichsetsthespeedofthemotorto
thatfloat. 1.0isfullspeed“forward”, -1.0isfullspeed“backward.”Themotorwhen
initializedbeginsat .Set(0).Theelse talonsrx.Set(0)istostopthemotor;unlessthe
motorcontrollerissetto 0,themotorremainsatthelast .Set()value.
TalonSRX
98
FRCElectricalBible
Spike
BindicatesthatthegroundsideofthePWMfacesinward
Spikesaremotorcontrollersusedindrivingsmallmotorsinforward,reverse,orstop
(brake).Itusesa20Acircuitbreaker.Itcanalsobewiredtocompressorsandsolenoidsand
itsindicatorlightsaredifferentformotorsandsolenoids,asshowninthetablebelow.
Spike
99
FRCElectricalBible
SpikeUserManual
➠SampleCode
RelayClass(C++)
Spike
100
FRCElectricalBible
#include"WPILib.h"
classRobotDemo:publicSampleRobot{
Relayspikeblue;
Joystickstick;
public:
RobotDemo():
spikeblue(1,Relay::kForward),
stick(1)
{
}
voidAutonomous(){
spikeblue.Set(Relay::kOn);
}
voidOperatorControl(){
while(IsOperatorControl()){
if(stick.GetRawButton(1)){
spikeblue.Set(Relay::kOn);
}
else{
spikeblue.Set(Relay::kOff);
}
}
}
};
START_ROBOT_CLASS(RobotDemo);
➠Explanation
Relayspikeblue;
Declarespikerelayasname spikeblue.Thedeclarationoccursbetween classRobotDemo:
publicSampleRobotand public:RobotDemo():
Spike
101
FRCElectricalBible
spikeblue(1,Relay::kForward),
Instantiatethespikerelaywiththeparameters[DigitalSidecarPort#],[directionofcurrent
[kForward,kBackward,orkBothDirections]]Thisisinstantiatedbetween public:
RobotDemo():andthebraces( {}).Ifitisnotthelastobjectinitialized,itneedsacomma
likealist.Ifitisthelastobjectinitialized,nopunctuation;nocomma,nosemicolon,no
period,etc.oryouwillgetanerror.
voidAutonomous(){
spikeblue.Set(Relay::kOn);
}
voidOperatorControl(){
while(IsOperatorControl()){
if(stick.GetRawButton(1)){
spikeblue.Set(Relay::kOn);
}
else{
spikeblue.Set(Relay::kOff);
}
}
}
TheJoystickclasshasalreadybeencoveredinaprevioussectionofthemanual.Controls
currenttowhateverisontheothersideofthespike(onesideconnectedtothePDB).In
autonomous,ifthereissomethingwiredtothespikethatneedstobeturnedon,itcanbe
Set(Relay::kOn).Toturnitoff,use Set(Relay::kOff).Notethatitwillnotshutoff
automaticallyandhencemanualoffcommand.In OperatorControl,therelaywilloftenbe
insertedinsidecontrolstatementstopreventlooserelayon/off.Usuallyturningitonifbutton
setinifconditionispressedotherwiserelayoff.Orviceversaifneedbe.
Spike
102
FRCElectricalBible
Fans
Beforethepedanticcommentregardingourtableofcontents,no,fansarenotmotor
controllers.Theyare,however,securedontopofmotorcontrollerstocoolthemdown;being
fansandall.TalonsandVictorshavemountingholesthatrequire6-32inchscrews.The
terminalsconnecttotheV+/-sideonthemotorcontroller(youdon’twantyourfansturning
offandoninunisonwithyourmotors).
Fans
103
FRCElectricalBible
7.DriveCode
7.1BoxonWheels
➠TheCode
➠TheExplanation
7.2BoxonWheelsTemplatevsCustomProgram
➠TheCode
➠TheExplanation
7.3CustomProgram(TankDrive)
➠TheCode
➠TheExplanation
7.4CustomProgram(MecanumDrive)
➠Introduction&WheelConfiguration
➠MovementConfiguration
➠SampleTestingCode
➠TheExplanation
➠TestedandModifiedCode
➠TheExplanation
DriveCode
104
FRCElectricalBible
BoxonWheels
Youhavenowopenedupabarebonestemplatetowriteyourrobotcode;congratulations
you’vemadeaboxonwheels,nowtounderstandwhatyou’reboxonwheelsdoes,before
youdestroyitandcreateyourowncompletelyimprovedcode.Itisnecessarytounderstand
theclassesthatcreatedthisboxonwheelssoyouknowthatyoujustdidn’tcreateanother
boxonwheelsprogram,butitisagoodstart.
➠TheCode
Thedriveprograminit’sentirety:
#include“WPILib.h”
//Lastmodified:January19,2014by:Alan
/*
ThisisademoprogramshowingtheuseoftheRobotBaseclass.TheSampleRob
AutonomousandOperatorControlmethodsattherighttimeascontrolledbyt
*/
classRobotDemo:publicSampleRobot{
RobotDrivemyRobot;//robotdrivesystem
Joystickstick;//onlyjoystick
public:
RobotDemo(void):
myRobot(1,2),//thesemustbeinitializedinthesameorder
stick(1)//astheyaredeclaredabove.
{
myRobot.SetExpiration(0.1),//youcaninitializethingsherelikegy
}
//Driveleft&rightmotorsfor2secondsthenstop
voidAutonomous(void){
myRobot.SetSafetyEnabled(false);
myRobot.Drive(0.5,0.5);//driveforwardathalfspeed
Wait(2);//for2seconds
myRobot.Drive(0.0,0.0);//stoprobot
}
BoxonWheels
105
FRCElectricalBible
//Runsthemotorswitharcadesteering
voidOperatorControl(void){
myRobot.SetSafetyEnabled(true);
while(IsOperatorControl())
{
myRobot.ArcadeDrive(stick);//drivewitharcadestyle(userigh
Wait(0.005);//waitforamotorupdatetime
}
}
//Runsduringtestmode
voidTest(){
}
};
START_ROBOT_CLASS(RobotDemo);
➠TheExplanation
Breakdownofthecodefollowsasso:
#include“WPILib.h”
ThisincludingoftheWPILibraryistheinclusionofaspellbookforalmosteveryclass
neededfortherobot:motors,pneumatics,Axiscameras,etc.NOTE:Therewillstillbemuch
timespentusingthe“WPILibC++Reference”,buttheuseofthebasicmanualreducesmost
ofthetimespentbypresentingsample/properusagesothelearningprocessdoesnotneed
torepeatitselfandtimecanbebestallocatedelsewhere.
/*
ThisisademoprogramshowingtheuseoftheRobotBaseclass.TheSampleRob
AutonomousandOperatorControlmethodsattherighttimeascontrolledbyth
*/
Ifyou’vecommentedinprogramming,thenyouknowwhatyoushouldbedoing,ifyouare
lazyandhavesomepersonalbeliefordogmathat,“Toughbeans,figureoutmygiant
program,”youareimpedingtheprogressofyoursubteamandyouareabsolutelyterrible.
BoxonWheels
106
FRCElectricalBible
However,ifyou’rejustinthemoodandhavestartedaprogram,commentwhatneedstobe
understoodbecauseyouneverknowwhenyoumightbegonethenextdayandsomeone
elsehastorunyourprogram.
classRobotDemo:publicSampleRobot
Thisisyourphysicalrobot,RobotDemoisthenameoftheclass,SampleRobot
{
RobotDrivemyRobot;//robotdrivesystem
Joystickstick;//onlyjoystick
Declarationoftherobotsparts, RobotDriveisasimplifieddrivesystemclassthatdeclares
motorsforyouandhaspreprogrammeddrivefunctions; Joystickalsodeclaredlast
becauseitisapartoftherobot,buthowelseareyougoingtocontrolit?Withyourmind?I
THINKNOT!
public:
RobotDemo(void):
myRobot(1,2),//thesemustbeinitializedinthesameorder
stick(1)//astheyaredeclaredabove.
{
myRobot.SetExpiration(0.1),//youcaninitializethingsherelikegy
}
RobotDemoistheconstructorofyourrobot,itwillnowinitializewhatyoudeclaredpreviously
asportsinthesidecarformostofthedeclaredobjects,withtheexceptionofthejoystick.As
noted, RobotDemohasthesamenameastheclassbecauseofhowobjectswork,anditis
void,butyoudon’thavetoputvoidasinC++itautomaticallyassumesvoid.Thepairof
bracesafteryouinstantiatetheportsofyourcontrollersallowsyoutoinitialize/run
commands(likesensors)attheverybeginning.
BoxonWheels
107
FRCElectricalBible
//Driveleft&rightmotorsfor2secondsthenstop
voidAutonomous(void){
myRobot.SetSafetyEnabled(false);
myRobot.Drive(0.5,0.5);//driveforwardathalfspeed
Wait(2);//for2seconds
myRobot.Drive(0.0,0.0);//stoprobot
}
Thisisthe Autonomousmethodofthe RobotDemoclass,anditwasinheritedfrom
SampleRobot.ItwillonlyrunduringtheAutonomousperiodofthegame. SetSafetyEnabled
istoprotecteveryoneincaseoflossofcommunicationorotherproblemswhensettotruein
the ().Drivesetsthespeedofthemotorsintheorderinitializedrespectively,fromavalue
of( -1.0to 1.0).Waitisamethodthatstopstheprogramfromreadinganyfurtherlines
forthetimespecifiedinthe ()inseconds.Tostoptherobot,themotorsafterbeingsetto
movemustbesetbacktozero.
//Runsthemotorswitharcadesteering
voidOperatorControl(void){
myRobot.SetSafetyEnabled(true);
while(IsOperatorControl()){
myRobot.ArcadeDrive(stick);//drivewitharcadestyle(useright
Wait(0.005);//waitforamotorupdatetime
}
}
OperatorControlisamethodofthe RobotDemoclass,thismethodwasalsoinheritedfrom
SampleRobot.Thisiswherethecodeforyourtele-opordrivercontrolperiodgoes.
SetSafetyEnabledwasalreadymentioned,butasareminder,it’sforthesafetyofallothers
andtherobotincaseofcommunicationproblemswiththerobot.Thewhileloopisthereto
makesurethatyouarealwaysincontrolduringtheperiod,withouttheloop,thecodewould
onlyrunonceandyourrobotwouldthenbecomeastationerybox. ArcadeDriveisthetype
ofdriveusingarcadejoystick,therobotwillmoveaccordingtothejoystickinput.
//Runsduringtestmode
voidTest(){
}
BoxonWheels
108
FRCElectricalBible
Thisiswhereyouwouldinputtestcodethatyouwouldn’tputintoeitherAutonomousor
Tele-opwithoutbeingsureitwouldworkfirstorifitwouldconflictwithotherpartsofthecode
insidethosemethods.
};
START_ROBOT_CLASS(RobotDemo);
START_ROBOT_CLASSsetsupa"userclassfactory",whichisafunctionthatreturnsapointer
newinstanceofyourrobotclass.Italsocreatestheentrypointfunction,
FRC_UserProgram_StartupLibraryInit.
BoxonWheels
109
FRCElectricalBible
BoxonWheelsTemplatevsCustomProgram
WhileBoxonWheelsTemplateisalreadymade,thereisnotalotofroomtoeditthisdrive
codeunlessyouareusingtwoLogitechExtreme3DProUSBJoysticks.Ifyousearchinthe
WPILibReferenceforRobotDrive,theconstructorsanddrivemethodsaredesignedfor
somethingliketheabove.Alsoyourchoicesof#ofmotorsfordriveisonlyeither2or4.If
youwishtouseaLogitechF310Gamepad,youarebetteroffwritingyourowndrivecode.
WhenImeancustom,deletetheunnecessarypartsofthetemplatethatwouldbenot
conducivetothewordcustom.Belowisbarebonescodethatyoumaymodifytomeetyour
owndesires.
➠TheCode
BoxonWheelsTemplatevsCustomProgram
110
FRCElectricalBible
#include"WPILib.h”
//Lastmodified:January25,2014by:Alan
classRobotDemo:publicSampleRobot{
Joystickstick;
public:
RobotDemo(void):
stick(1){
}
//Insertyourowncomment
voidAutonomous(void)
{
}
//Insertyourowncomment
voidOperatorControl(void){
while(IsOperatorControl()){
Wait(0.005);//waitforamotorupdatetime
}
}
//Insertyourowncomment
voidTest(){
}
};
START_ROBOT_CLASS(RobotDemo);
➠TheExplanation
Here’sapancakesandwichwithsprinkles.
#include"WPILib.h"
Thisisyourspellbook.Liveit,breatheit.
classRobotDemo:publicSampleRobot
The RobotDemoclass+ SampleRobotfromthetemplategivesyoutheinheritedmethodsto
useintheDriverStation,willneedit
BoxonWheelsTemplatevsCustomProgram
111
FRCElectricalBible
Joystickstick;
Youwillalwaysneedajoystick,again,unlessyoucancontrolyourrobotwithyourmind,orit
iscompletelyautonomous,makethejoystick.
public:
RobotDemo(void):
stick(1)
{
}
Instantiatethestick,youcan’tuseitifyoudon’tinstantiateit.Thebraceshavetobethere,
partofthecompiling.Whenyoustartaddinginmotorsandsensors,their
expirations/initializationwillbesetinthosebraces.
voidAutonomous(void){
}
Stillneedautonomoussection,partoftheinheritance.Ifyouuseitornotisuptothatyear’s
game,butyoustillneedthis!
voidOperatorControl(void){
while(IsOperatorControl()){
Wait(0.005);//waitforamotorupdatetime
}
}
Thisiswhereyouwritethegodcode,whereyouletyourdriverfeellikeakingmovingthe
robot...withyourcode:DMakesurethecodethatwillletthedriverexecutecommandsisin
thewhileloop,wouldn’titsuckthattheycanonlydoitoncebecauseitwasnotintheloop?
Beforetheloopiswhenyoucaninstantiatespecificthingssuchastheresolutionofanaxis
camera.
voidTest(){
}
Testingspaceforsmallportionsofquestionablecode.Alsopartofinheritance,required.
BoxonWheelsTemplatevsCustomProgram
112
FRCElectricalBible
};
START_ROBOT_CLASS(RobotDemo);
Closesbracefromthebeginningoftheclass. START_ROBOT_CLASS(RobotDemo);noticehow
RobotDemoisintheparameter,isn’tthattheclass?Sothisisalsoimportantforitrunsthe
class.
BoxonWheelsTemplatevsCustomProgram
113
FRCElectricalBible
CustomProgram(TankDrive)
AnexampleofwherethedriverusestheLogitechF310Gamepad,butbecauseoftheway
theRobotDriveclassismade,itispreferabletomakeone’sowncode.
➠TheCode
#include"WPILib.h"//WPILibrary.h
#include"Math.h"//Math.hrequiredforfabsfunction
//Lastmodified:January30,2014by:Alan
classRobotDemo:publicSampleRobot{
TalonfrontLeft,frontRight,backLeft,backRight;//TalonMotorControll
Joysticklogitech;//LogitechF310Gamepad/Controller
public:
RobotDemo(void):
frontLeft(1),
frontRight(2),
backLeft(3),
backRight(4),
logitech(1)
/*
*Setmotorexpirationtopreventunwarrantedmovementifconnectionlosto
*disabled
*/
{
frontLeft.SetExpiration(0.1),
frontRight.SetExpiration(0.1),
backLeft.SetExpiration(0.1),
backRight.SetExpiration(0.1);
}
voidAutonomous(void){
}
/**
*Runsthemotorswithtanksteering
*/
CustomProgram(TankDrive)
114
FRCElectricalBible
voidOperatorControl(void){
while(IsOperatorControl()){
if(fabs(logitech.GetRawAxis(2))>0.2){
/*leftjoystick,forward&back*/
frontLeft.Set(logitech.GetRawAxis(2)*-.65);
backLeft.Set(logitech.GetRawAxis(2)*-.65);
}
else{
frontLeft.Set(0);
backLeft.Set(0);
}
if(fabs(logitech.GetRawAxis(4))>0.2){
/*rightjoystick,forward&back*/
frontRight.Set(logitech.GetRawAxis(4)*.65);
backRight.Set(logitech.GetRawAxis(4)*.65);
}
else{
frontRight.Set(0);
backRight.Set(0);
}
Wait(0.005);//wait0.005secondsbeforerepeatingloop
}
}
/**
*Runsduringtestmode
*/
voidTest(){
while(IsTest()){
}
}
};
START_ROBOT_CLASS(RobotDemo);
➠TheExplanation
#include"WPILib.h"//WPILibrary.h
#include"Math.h"//Math.hrequiredforfabsfunction
CustomProgram(TankDrive)
115
FRCElectricalBible
WPILib.hisalwaysourspellbook. Math.hisadifferentlibrarythatisgenerallyusedinC++
formathfunctions.Asstatedinthecomment,itisusedforthe fabs(floatabsolutevalue)
functionthatappearsinthetankdriveportionofthiscode.
classRobotDemo:publicSampleRobot
{
TalonfrontLeft,frontRight,backLeft,backRight;//TalonMotorControll
Joysticklogitech;//LogitechF310Gamepad/Controller
RobotDemoclasswithinheritedmethodsfrom SampleRobotmakestemplatingeasier.The
talonsareoneofseveralmotorcontrollersexplainedinanearliersectionofthismanual.
RobotDriveintheoriginaltemplatedeclarestheminthebackground,butthenyouare
limitedtoit’sdrivemethods.Thiscustomprogramusesalogitechgamepadwhichisone
joystickobject.IfyoulookintheWPILibreference,itwillshowthattousethetankdrive
methodofthe RobotDrive,youneedtwojoysticks.
public:
RobotDemo(void):
frontLeft(1),
frontRight(2),
backLeft(3),
backRight(4),
logitech(1)
//Setmotorexpirationtopreventunwarrantedmovementifconnectionlosto
{
frontLeft.SetExpiration(0.1),
frontRight.SetExpiration(0.1),
backLeft.SetExpiration(0.1),
backRight.SetExpiration(0.1);
}
Nowintheconstructor,themotorcontrollersareinstantiatedintheportsofthedigital
sidecarcorrespondingtothenumberintheparentheses.Thejoystickisinstantiatedusing
theUSBport.Asmentionedinthecomment,insidetheotherbraces,thereare
SetExpirationstopreventcontinuedmovementineventofdisablementorlostconnection.
Itdoesthisbyshuttingdownpowertotheobjectthathasexpired;nowaslongasyou’re
connected,themotorsare“fed”andtheexpirationsrefresh.
CustomProgram(TankDrive)
116
FRCElectricalBible
/**
*Insertowncomment
*/
voidAutonomous(void){
}
Autonomouscodegoeshere.Howeverthiscustomprogramistoshowtankdrivenotfull
autopilot.
/**
*Runsthemotorswithtanksteering
*/
voidOperatorControl(void){
while(IsOperatorControl()){
if(fabs(logitech.GetRawAxis(2))>0.2){
/*leftjoystick,forward&back*/
frontLeft.Set(logitech.GetRawAxis(2)*-.65);
backLeft.Set(logitech.GetRawAxis(2)*-.65);
}
else{
frontLeft.Set(0);
backLeft.Set(0);
}
if(fabs(logitech.GetRawAxis(4))>0.2){
/*rightjoystick,forward&back*/
frontRight.Set(logitech.GetRawAxis(4)*.65);
backRight.Set(logitech.GetRawAxis(4)*.65);
}
else{
frontRight.Set(0);
backRight.Set(0);
}
Wait(0.005);//waitforamotorupdatetime
}
}
Thishereisthejuicypart,thisistankdrive.Forthosewhodonotknowtankdrive,one
joystickcontrolsonesideofthedrive,sowhenonestickispushed,onlyonesidemoves
andtheotherjoystickcontrolstheotherrespectiveside.Thisiswherethefabsfunctionis
CustomProgram(TankDrive)
117
FRCElectricalBible
usedtoshortencodinglines.Normallytherewouldhavetobetwoconditionsinthoseifsfor
tankdrivetowork;ifthejoystickisgreaterthanathresholdORifthejoystickisbelow
negativethreshold.Itwouldlooklike joystick.GetRawAxis(2)>0.2||
joystick.GetRawAxis(2)<-0.2.Comparedtowhatisinthere,itismucheasiertocode,but
lessunderstandable.Reasoningiswhenyoutiltthejoystickbackitisnegative,butitdoes
notpass> 0.2.Use fabsorabsolutevalue(forfloats,justabsforints),lesscoding.
/**
*Runsduringtestmode
*/
voidTest(){
while(IsTest()){
}
}
};
START_ROBOT_CLASS(RobotDemo);
Closesbracefromthebeginningoftheclass. START_ROBOT_CLASS(RobotDemo);noticehow
RobotDemoisintheparameter,isn’tthattheclass?Sothisisalsoimportantforitrunsthe
class.
CustomProgram(TankDrive)
118
FRCElectricalBible
CustomProgram(MecanumDrive)
➠Introduction&WheelConfiguration
TheMecanumDriveallowstherobottomoveforward,backward,andstrafe.Thisispossible
duetothenatureofthewheels,whichslipbecauseoftherollersonthem.Theywillnaturally
travelina45degreemotioninthedirectionthattheentirewheelisrotating.Whenworking
withmecanumwheels,itisimportanttoconsidertheweightdistributionoftherobotframe
becausemecanumwheelsaredesignedforrobotswithanevenweightdistribution.An
unevenweightdistributionwillcausewheelssupportingmoreweighttohavemoretraction
thanthewheelssupportinglessweight.Thisdifferenceintractionwillmodifytheeffective
rotationofeachwheel,andtheeffectofthemecanumdriveislost.
Leftconfiguration
RotatingForwards:motion45degreesnorthofeast
RotatingBackwards:motion45degreessouthofwest
Usedby:Wheel1,frontleft,andWheel4,backright.
RightConfiguration
RotatingForwards:motion45degreesnorthofwest
RotatingBackwards:motion45degreessouthofeast
CustomProgram(MecanumDrive)
119
FRCElectricalBible
Usedby:Wheel2,frontright,andWheel3,backleft.
➠MovementConfiguration
DrivingForward
Wheels1,2,3,and4arerotatingforwardtoallowthedriveframetodriveforward.
DrivingBackward
Wheels1,2,3,and4arerotatingbackwardtoallowthedriveframetodrivebackward.
CustomProgram(MecanumDrive)
120
FRCElectricalBible
StrafingLeft
Wheels2and3arerotatingforward,Wheels1and4arerotatingbackwardtoallowthe
driveframetostrafetowardtheleft.
CustomProgram(MecanumDrive)
121
FRCElectricalBible
StrafingRight
Wheels1and4arerotatingforward,Wheels2and3arerotatingbackwardtoallowthe
driveframetostrafetowardtheright.
CustomProgram(MecanumDrive)
122
FRCElectricalBible
TurningClockwise
CustomProgram(MecanumDrive)
123
FRCElectricalBible
Wheels1and3arerotatingforward,Wheel2and4arerotatingbackwardtoallowthedrive
frametorotateclockwiseaboutitscenter
TurningCounter-Clockwise
Wheels2and4arerotatingforward,Wheels1and3arerotatingbackwardtoallowthe
driveframetorotatecounter-clockwiseaboutitscenter
CustomProgram(MecanumDrive)
124
FRCElectricalBible
➠SampleTestingCode
#include"WPILib.h"
#include“Math.h”
classRobotDemo:publicSampleRobot{
VictorleftFront;//Initializingmotor1;front-leftmotor
VictorleftBack;//Initializingmotor3;back-leftmotor
VictorrightFront;//Initializingmotor2;front-rightmotor
VictorrightBack;//Initializingmotor4;back-rightmotor
Joysticklogitech;//LogitechGamepadController
public:
RobotDemo():
leftFront(1),//leftFrontmotorusesPWMport1
leftBack(2),//leftBackmotorusesPWMport2
rightFront(3),//rightBackmotorusesPWMport3
rightBack(4),//rightBackmotorusesPWMport4
logitech(1)//LogitechGameControllerwithDriverstationport1
CustomProgram(MecanumDrive)
125
FRCElectricalBible
{
}
voidOperatorControl(){
intleftFrontPolarity=1;//Thesevariablesflipthesignvalue
intleftBackPolarity=1;//themotorsinthesituationthatthey
intrightFrontPolarity=-1;//flipped
intrightBackPolarity=-1;
while(IsOperatorControl()){
floatx=0;//x-axismotion-right(+),left(-)
floaty=0;//y-axismotion-forward(+),backward(-)
floatz=0;//z-axismotion-clockwise(+),counterclockwise(if(fabs(stickOne.GetRawAxis(1))>.2)
z=stickOne.GetRawAxis(1);//z-axisthreshold
if(fabs(stickOne.GetRawAxis(2))>.2)
y=-(stickOne.GetRawAxis(2));//y-axisthreshold
if(fabs(stickTwo.GetRawAxis(1))>.2)
x=stickTwo.GetRawAxis(1);//x-axisthreshold
//y-axismotion
if(fabs(y)>fabs(x)&&fabs(y)>fabs(z))//Activatesifyis
leftFront.Set(y*leftFrontPolarity);
rightFront.Set(y*rightFrontPolarity);
leftBack.Set(y*leftBackPolarity);
rightBack.Set(y*rightBackPolarity);
}
//x-axismotion
if(fabs(x)>fabs(y)&&fabs(x)>fabs(z))//Activatesifxis
leftFront.Set(x*leftFrontPolarity);
rightFront.Set(x*rightFrontPolarity*-1);
leftBack.Set(x*leftBackPolarity*-1);
rightBack.Set(x*rightBackPolarity);
}
//z-axismotion
elseif(fabs(z)>fabs(y)&&fabs(z)>fabs(x)){
leftFront.Set(z*leftFrontPolarity);
rightFront.Set(z*rightFrontPolarity*-1);
leftBack.Set(z*leftBackPolarity);
rightBack.Set(z*rightBackPolarity*-1);
CustomProgram(MecanumDrive)
126
FRCElectricalBible
}
//Otherwisesticksarenotpushed
else{
leftFront.Set(0);
leftBack.Set(0);
rightFront.Set(0);
rightBack.Set(0);
}
Wait(0.005);
}
}
};
START_ROBOT_CLASS(RobotDemo);
➠TheExplanation
Breakdownofthecodefollowsasso:
#include"WPILib.h"
#include"Math.h"
classRobotDemo:publicSimpleRobot
{
VictorleftFront;//Initializingmotor1;front-leftmotor
VictorleftBack;//Initializingmotor3;back-leftmotor
VictorrightFront;//Initializingmotor2;front-rightmotor
VictorrightBack;//Initializingmotor4;back-rightmotor
Joysticklogitech;//LogitechGamepadController
Hereweinstantiatethe4motorcontrollersweareusingtomanipulatethe4mecanum
wheelsontherobotunderthe Victorclass(hereweusedVictormotorcontrollers).We
alsoinstantiatedourLogitechGamepadControllerunderthe Joystickclass.
CustomProgram(MecanumDrive)
127
FRCElectricalBible
public:
RobotDemo():
leftFront(1),//leftFrontmotorusesPWMport1
leftBack(2),//leftBackmotorusesPWMport2
rightFront(3),//rightBackmotorusesPWMport3
rightBack(4),//rightBackmotorusesPWMport4
logitech(1)//LogitechGameControllerwithDriverstationport1
{
}
Wefurtherdefineourconstructorsbyassociatingeachpieceofhardwaretotheirrespective
ports.The VictorClass,whichisacategoryofmotorcontrollers,utilizePWMportswhile
the JoystickClassutilizedfortheLogitechGamepadControllerutilizesthedriverstation
(USB)ports
voidOperatorControl()
{
DriverStationLCD*screen=DriverStationLCD::GetInstance();
intleftFrontPolarity=1;//Thesevariablesflipthesignvalue
intleftBackPolarity=1;//themotorsinthesituationthatthey
intrightFrontPolarity=-1;//flipped
intrightBackPolarity=-1;
Thesevariablesareinplacetocontrolthepolarityofthemotors(whethertheyrotate
forwardsorbackwardswhenpushingtheleftandrightsticksinacertaindirection).This
makesiteasiertofixthecodeintheeventofamotorbeingreversed.
while(IsOperatorControl()){
floatx=0;//x-axismotion-right(+),left(-)
floaty=0;//y-axismotion-forward(+),backward(-)
floatz=0;//z-axismotion-clockwise(+),counterclockwise(
Thissplitstheaxesofthemotionsothattheycanbeassignedbasedonhowthe
thumbsticksarepushed.Thepushingtheleftthumbstickonit’sy-axiswillgiveay-value( +
=forward, -=backward),pushingtheleftstickonit’sx-axisgivesaz-value( +=
clockwise, -=backward),andpushingtherightstickonit’sx-axisgiveax-value( +=
right, -=left).
CustomProgram(MecanumDrive)
128
FRCElectricalBible
if(fabs(stickOne.GetRawAxis(1))>.2)
z=stickOne.GetRawAxis(1);//z-axisthreshold
if(fabs(stickOne.GetRawAxis(2))>.2)
y=-(stickOne.GetRawAxis(2));//y-axisthreshold
if(fabs(stickTwo.GetRawAxis(1))>.2)
x=stickTwo.GetRawAxis(1);//x-axisthreshold
Thissectionassignsavaluetotheaxesbasedontheorientationofthethumbsticks.A
thresholdisplacedsothattinyaccidentalmovementsdonotcausetherobottodrift.
//y-axismotion
if(fabs(y)>fabs(x)&&fabs(y)>fabs(z))//Activatesifyis
leftFront.Set(y*leftFrontPolarity);
rightFront.Set(y*rightFrontPolarity);
leftBack.Set(y*leftBackPolarity);
rightBack.Set(y*rightBackPolarity);
}
Iftheleftstickispushedmoreonit’sy-axis(forward/backward)thanitortherightstickis
pushedontheirx-axis,thentherobotwillmoveforwardorbackwardsdependingonthe
directionofthethumbstick.Pushingforwardwillmakeallwheelsrotateforwardandpushing
backwardsmakesallwheelsrotatebackward.Also,thespeedofthemotorsdependson
howmuchtheleftthumbstickispushedalongthey-axis.
//x-axismotion
if(fabs(x)>fabs(y)&&fabs(x)>fabs(z))
//Activatesifxislargest{
leftFront.Set(x*leftFrontPolarity);
rightFront.Set(x*rightFrontPolarity*-1);
leftBack.Set(x*leftBackPolarity*-1);
rightBack.Set(x*rightBackPolarity);
}
Iftherightstick’sx-axismagnitudeisgreaterthananyoftheleftstick’saxes,thentherobot
willstrafeeitherrightorleft.Pushingthethumbsticktotherightmakestheleftfrontandright
backmotorsrotateforwardwhiletheothertworeverse(usedthevectordiagramto
CustomProgram(MecanumDrive)
129
FRCElectricalBible
determinedirection).Pushingthethumbsticktotheleftmakestheoppositehappen,withthe
rightfrontandleftbackrotatingforwardwhiletheleftfrontandrightbackreverse.Again,the
speedofthemotorsdependsonhowlargethemagnitudeoftherightthumbstick’sx-axisis.
//z-axismotion
elseif(fabs(z)>fabs(y)&&fabs(z)>fabs(x)){
leftFront.Set(z*leftFrontPolarity);
rightFront.Set(z*rightFrontPolarity*-1);
leftBack.Set(z*leftBackPolarity);
rightBack.Set(z*rightBackPolarity*-1);
}
Ifthemagnitudeoftheleftstick’sx-axisisgreaterthanit’sowny-axisandtheright
thumbsticksx-axis,thentherobotwillrotate.Iftheleftstickispushedtotheright,theleft
wheelswillrotateforwardandtherightwheelswillrotatebackwards,makingitturn
clockwise,muchliketankdrive.Theoppositehappenswhenyoupushthesticktotheleft.
else{
leftFront.Set(0);
leftBack.Set(0);
rightFront.Set(0);
rightBack.Set(0);
}
Thissetsallthemotorsto 0whenthejoysticksarenotpushedinanassigneddirectionor
arenotpushedpastthethreshold
AlternateCode(putthisinplaceofalloftheifelsestatements)
leftFront.Set(x-y-z);
leftBack.Set(-x-y-z);
rightFront.Set(x+y+z);
rightBack.Set(-x+y+z);
Thiscodeisusedasasimplificationoftheonepostedearlier.However,thereisa
fundamentaldifferenceinhowthesetwooperate.Intheoriginalcode,youcanonlymovein
specificdirections,likeforward,backwards,right,left,androtate,whereasinthisversionyou
canmoveinanycombinationofthethreeaxes.Thisisachievedbybypassingifstatements
andjustusingadditionandsubtraction.Thiswayalsoallowsyoutobypasstheissueof
CustomProgram(MecanumDrive)
130
FRCElectricalBible
makingaspecificvariableforpolarity,asyoucanjustchangethe +or -forthespecific
motor.Inthissituation,theleftmotorswerereversed,soitwasnecessarytochange +yto
-yand +zto -zasitisnow.Youalsohavetoswitchthesignofthe xvariable.Ifthe
leftmotorswerenotreversed,thecodewouldbe leftFront.Set(-x+y+z)and
leftBack.Set(x+y+z).However,thereisanissuethatexistswithinthiscodeasitispossible
forthesetvalueforeachmotortoexceed1ifyouweretorotatewhilemovinginanother
direction.
➠TestedandModifiedCode
//Thisistemporarycodethatwillbereplacedinthebibleuponfinalcode
#include"WPILib.h"
#include"Math.h"
classRobotDemo:publicSimpleRobot{
VictorleftFront;//Initializingmotor1;front-leftmotor
VictorleftBack;//Initializingmotor3;back-leftmotor
VictorrightFront;//Initializingmotor2;front-rightmotor
VictorrightBack;//Initializingmotor4;back-rightmotor
JoystickstickOne;//LogitechGamepadController
JoystickstickTwo;//LogitechGamepadController
public:
RobotDemo():
leftFront(1),//leftFrontmotorusesPWMport1
leftBack(2),//leftBackmotorusesPWMport2
rightFront(3),//rightBackmotorusesPWMport3
rightBack(4),//rightBackmotorusesPWMport4
stickOne(1),//LogitechGameControllerwithDriverstationport1
stickTwo(2)//Joystickwithdriverstationport2
{
}
voidOperatorControl(){
DriverStationLCD*screen=DriverStationLCD::GetInstance();
intleftFrontPolarity=1;//Thesevariablesflipthesignvalueof
intleftBackPolarity=1;//themotorsinthesituationthattheya
intrightFrontPolarity=-1;//flipped
intrightBackPolarity=-1;
floatx=0;//x-axismotion-right(+),left(-)
CustomProgram(MecanumDrive)
131
FRCElectricalBible
floaty=0;//y-axismotion-forward(+),backward(-)
floatz=0;//z-axismotion-clockwise(+),counterclockwise(-)
while(IsOperatorControl()){
if(fabs(stickOne.GetRawAxis(1))>.2)
z=stickOne.GetRawAxis(1);//z-axisthreshold
if(fabs(stickOne.GetRawAxis(2))>.2)
y=-(stickOne.GetRawAxis(2));//y-axisthreshold
if(fabs(stickTwo.GetRawAxis(1))>.2)
x=stickTwo.GetRawAxis(1);//x-axisthreshold
//y-axismotion
//Activatesifyislargest
if(fabs(y)>fabs(x)&&fabs(y)>fabs(z)){
leftFront.Set(y*leftFrontPolarity);
rightFront.Set(y*rightFrontPolarity);
leftBack.Set(y*leftBackPolarity);
rightBack.Set(y*rightBackPolarity);
}
//x-axismotion
//Activateswhenxislargest
elseif(fabs(x)>fabs(y)&&fabs(x)>fabs(z)){
if(x>0){
//Executesifxisgreaterthandeadbandof0.5
if(fabs(x)>=0.5){
leftFront.Set(x*leftFrontPolarity*1.1);
rightFront.Set(x*rightFrontPolarity*-0.95
leftBack.Set(x*leftBackPolarity*-1.1);
rightBack.Set(x*rightBackPolarity);
}
elseif(fabs(x)>0.35){
leftFront.Set(x*leftFrontPolarity*0.9);
rightFront.Set(x*rightFrontPolarity*-0.9);
leftBack.Set(x*leftBackPolarity*-1.1);
rightBack.Set(x*rightBackPolarity);
}
}
elseif(x<0){
if(fabs(x)>=0.5){
leftFront.Set(x*leftFrontPolarity*1.05);
rightFront.Set(x*rightFrontPolarity*-1);
CustomProgram(MecanumDrive)
132
FRCElectricalBible
leftBack.Set(x*leftBackPolarity*-1);
rightBack.Set(x*rightBackPolarity);
}
elseif(fabs(x)>0.35){
leftFront.Set(x*leftFrontPolarity*1.1);
rightFront.Set(x*rightFrontPolarity*-1);
leftBack.Set(x*leftBackPolarity*-1.1);
rightBack.Set(x*rightBackPolarity);
}
}
}
//z-axismotion
elseif(fabs(z)>fabs(y)&&fabs(z)>fabs(x)){
leftFront.Set(z*leftFrontPolarity);
rightFront.Set(z*rightFrontPolarity*-1);
leftBack.Set(z*leftBackPolarity);
rightBack.Set(z*rightBackPolarity*-1);
}
//turnleftwhenpressing5
elseif(stickOne.GetRawButton(5)){
leftFront.Set(0.5);
rightFront.Set(0.3);
leftBack.Set(0.3);
rightBack.Set(0.3);
}
//turnrightwhenpressing4
elseif(stickOne.GetRawButton(4)){
leftFront.Set(-0.3);
rightFront.Set(-0.5);
leftBack.Set(-0.3);
rightBack.Set(-0.5);
}
//Otherwisesticksarenotpushed
else{
leftFront.Set(0);
leftBack.Set(0);
rightFront.Set(0);
rightBack.Set(0);
}
x=0;//x-axismotion-right(+),left(-)
CustomProgram(MecanumDrive)
133
FRCElectricalBible
y=0;//y-axismotion-forward(+),backward(-)
z=0;//z-axismotion-clockwise(+),counterclockwise(-)
screen->PrintfLine(DriverStationLCD::kUser_Line1,"X:%f"
screen->PrintfLine(DriverStationLCD::kUser_Line2,"Y:%f"
screen->PrintfLine(DriverStationLCD::kUser_Line3,"Rotation:%f
screen->UpdateLCD();
Wait(0.1);
}
}
voidTest(){
while(IsTest()){
//Forwardpolaritytest
if(stickOne.GetRawButton(6))
leftFront.Set(.3);
elseif(stickOne.GetRawButton(7))
leftBack.Set(.3);
elseif(stickOne.GetRawButton(11))
rightFront.Set(-.3);
elseif(stickOne.GetRawButton(10))
rightBack.Set(-.3);
else{
leftFront.Set(0);
leftBack.Set(0);
rightFront.Set(0);
rightBack.Set(0);
}
}
}
};
START_ROBOT_CLASS(RobotDemo);
➠TheExplanation
Breakdownofthecodefollowsasso:
CustomProgram(MecanumDrive)
134
FRCElectricalBible
#include"WPILib.h"
classRobotDemo:publicSimpleRobot{
VictorleftFront;//Initializingmotor1;front-leftmotor
VictorleftBack;//Initializingmotor3;back-leftmotor
VictorrightFront;//Initializingmotor2;front-rightmotor
VictorrightBack;//Initializingmotor4;back-rightmotor
JoystickstickOne;//LogitechGamepadController
JoystickstickOne;//LogitechGamepadController
Hereweinstantiatethefourmotorcontrollersweareusingtomanipulatethe4mecanum
wheelsontherobotunderthe Victorclass(hereweusedVictormotorcontrollers).We
alsoinstantiatedourtwojoysticksthatwillbecontrollingthemotionoftherobots
public:
RobotDemo():
leftFront(1),//leftFrontmotorusesPWMport1
leftBack(2),//leftBackmotorusesPWMport2
rightFront(3),//rightBackmotorusesPWMport3
rightBack(4),//rightBackmotorusesPWMport4
stickOne(1)//Logitechattack3withDriverstationport1
stickTwo(2)//Logitechattack3withDriverstationport2
{
}
Here,wefurtherdefineourconstructorsbyassociatingeachpieceofhardwaretotheir
respectiveports.The VictorClass,whichisacategoryofmotorcontrollers,utilizePWM
portswhiletheJoystickClassutilizedfortheLogitechAttack3utilizesthedriver-station
ports.
CustomProgram(MecanumDrive)
135
FRCElectricalBible
voidOperatorControl(){
DriverStationLCD*screen=DriverStationLCD::GetInstance();
intleftFrontPolarity=1;//Thesevariablesflipthesignvalueof
intleftBackPolarity=1;//themotorsinthesituationthattheya
intrightFrontPolarity=-1;//flipped
intrightBackPolarity=-1;
floatx=0;//x-axismotion-right(+),left(-)
floaty=0;//y-axismotion-forward(+),backward(-)
floatz=0;//z-axismotion-clockwise(+),counterclockwise(-)
Thetophalfofthissectionismeanttobeinpreparationforthesituationwhereoneormore
wheelsneedtohavetheirpolarity(goingforwardsorbackwards)flipped.Thebottomhalfis
meanttoinstantiateandconstructthevariablesthatwillberepresentingourvariousaxesof
motion.Thesewillbeusedtocontrolthevoltagesenttoeachindividualmotor.
while(IsOperatorControl()){
if(fabs(stickOne.GetRawAxis(1))>.2)
z=stickOne.GetRawAxis(1);//z-axisthreshold
if(fabs(stickOne.GetRawAxis(2))>.2)
y=-(stickOne.GetRawAxis(2));//y-axisthreshold
if(fabs(stickTwo.GetRawAxis(1))>.2)
x=stickTwo.GetRawAxis(1);//x-axisthreshold
Thissectionservestwomainpurposes.Thefirstoneissettingathresholdforallaxesof
motion.Thejoysticksmustbepushedpastavalueof.2inorderforitsvaluetobe
consideredvalid.Thisismeanttopreventtherobotfromdriftingduetothejoysticknot
perfectlyrestingat0.Thesecondfunctionistoassigneachaxisofmotiontoajoystick
direction.Inourscenario,wepreferredtomakepushing stickOneleftandrightrotatethe
vehiclecounterclockwiseandclockwiserespectively.Pushing stickOneforwardsand
backwardscorrelatestoforwardsandbackwardsmotion.Pushing stickTwototherightand
leftcorrelatestostrafingrightandleft.
CustomProgram(MecanumDrive)
136
FRCElectricalBible
//y-axismotion
//Activatesifyislargest
if(fabs(y)>fabs(x)&&fabs(y)>fabs(z)){
leftFront.Set(y*leftFrontPolarity);
rightFront.Set(y*rightFrontPolarity);
leftBack.Set(y*leftBackPolarity);
rightBack.Set(y*rightBackPolarity);
}
Thefirstlineisdedicatedtodeterminingifthey-component(frontandback)of stickOne’s
positionisgreaterinmagnitudethanitsz-component(leftandright)and stickTwo’sxcomponent(leftandright).Thisismeanttomaketherobotonlymoveinonedirectionata
time.Therestoftheblockisdedicatedtomakingtherobotmoveforwardandbackwards.
Sinceallwheelsrotateinthesamedirection,nothingneedstobeflipped.
//x-axismotion
//Activatesxwhenlargest
elseif(fabs(x)>fabs(y)&&fabs(x)>fabs(z)){
if(x>0){
if(fabs(x)>=0.5){
leftFront.Set(x*leftFrontPolarity*1.1);
rightFront.Set(x*rightFrontPolarity*-0.95
leftBack.Set(x*leftBackPolarity*-1.1);
rightBack.Set(x*rightBackPolarity);
}
elseif(fabs(x)>0.35){
leftFront.Set(x*leftFrontPolarity*0.9);
rightFront.Set(x*rightFrontPolarity*-0.9);
leftBack.Set(x*leftBackPolarity*-1.1);
rightBack.Set(x*rightBackPolarity);
}
}
Muchlikethetop,thissectionisonlyactivatedwhenthex-componentof stickTwo’s
positionislargerthananyof stickOne’s.However,thissectionisdifferentasourrobot
wouldrotateslightlyclockwiseanddriftslightlybackwards.Toaddressthis,wehadto
manuallyaddmultiplierstocertainmotorstomakethemmoveslowerorfasteratcertain
intervals.Wealsohadtoseparateleftstrafingandrightstrafingbecausetheybehaved
CustomProgram(MecanumDrive)
137
FRCElectricalBible
differently.Intheblockabove,weonlyseetherightstrafingportionofthecode.Thissection
issubdividedintotwomoresections,whenthewheelsaresuppliedatleasthalfoftheir
maximumvoltage(>=.5)andwhentheyaresuppliedonlyalittlebitofvoltage(.5>v>
0.35).Thiswasduetoourdrivereactingdifferentlyatdifferentvoltages.You’llsee
multiplierslike1.1,-0.95and0.9intheabovecode,thisisbecausesomewheelswere
rotatingslower/fasterthanothers.Multiplierswithmagnitudesbelow1aremeanttoslow
thespeedofthatspecificmotor.Multiplierswithmagnitudesabove1aremeanttospeed
themup.Differentsigns(+or-)aremeanttoreversethedirectionofthewheelinorderfor
thevectorstomakethecardmoveinthedesireddirection.
elseif(x<0){
if(fabs(x)>=0.5){
leftFront.Set(x*leftFrontPolarity*1.05);
rightFront.Set(x*rightFrontPolarity*-1);
leftBack.Set(x*leftBackPolarity*-1);
rightBack.Set(x*rightBackPolarity);
}
elseif(fabs(x)>0.35){
leftFront.Set(x*leftFrontPolarity*1.1);
rightFront.Set(x*rightFrontPolarity*-1);
leftBack.Set(x*leftBackPolarity*-1.1);
rightBack.Set(x*rightBackPolarity);
}
}
}
Thisisthesameastheportionbeforethis,butforstrafingtotheleft.Sincethismotionhad
differenterrorsthatstrafingtotherightdid,wehadtoeditthemultipliersuntiltherobot
strafednicely.
//z-axismotion
elseif(fabs(z)>fabs(y)&&fabs(z)>fabs(x)){
leftFront.Set(z*leftFrontPolarity);
rightFront.Set(z*rightFrontPolarity*-1);
leftBack.Set(z*leftBackPolarity);
rightBack.Set(z*rightBackPolarity*-1);
}
CustomProgram(MecanumDrive)
138
FRCElectricalBible
Thissectionofthecodeisforrotatingtherobot.Again,thisisactivatedonlywhenthe
magnitudeof stickOne’sz-component(howmuchtotheleftorrightitis)islargerthanboth
thexandycomponents.Inordertorotate,therightsightmustalwaysbegoingthedirection
oppositeofwherethejoysticktellsitto.Thisiswhytheyhavea-1appliedintheir
statements.Pushing stickOnetotherightmakestherobotrotateclockwiseandpushingit
totheleftmakesitrotatecounterclockwise.
//turnleftwhenpressing5
elseif(stickOne.GetRawButton(5)){
leftFront.Set(0.5);
rightFront.Set(0.3);
leftBack.Set(0.5);
rightBack.Set(0.3);
}
//turnrightwhenpressing4
elseif(stickOne.GetRawButton(4)){
leftFront.Set(-0.3);
rightFront.Set(-0.5);
leftBack.Set(-0.3);
rightBack.Set(-0.5);
}
Thissectionofthecodeisjustaquickpresetthatwefoundtobeuseful.Theymakethe
robotmoveforwardsandrotateslightlywheneitherthe4or5-buttonispressed.Pressing
the5-buttonmakesitturnrightandpushingthe4-buttonmakesitturnleft.
//Otherwisesticksarenotpushed
else{
leftFront.Set(0);
leftBack.Set(0);
rightFront.Set(0);
rightBack.Set(0);
}
Thepurposeofthissectionistoensurethatwhenthejoysticksareattheirrestingpositions
orverynearitthatthemotorswillnotrotatethewheels.
CustomProgram(MecanumDrive)
139
FRCElectricalBible
x=0;//x-axismotion-right(+),left(-)
y=0;//y-axismotion-forward(+),backward(-)
z=0;//z-axismotion-clockwise(+),counterclockwise(-)
Sincethisportionofthecodeisoutsideofthe IsOperatorControlwhileloop,thismakes
surethatthemotorswillNOTrotatethewheelswhentherobotisnotundercontrolofthe
driver.
CustomProgram(MecanumDrive)
140
FRCElectricalBible
8.Sensors
8.1TheroboRIOaccelerometer
➠GeneralOverview
➠Specifications
➠TheCode
➠TheExplanation
8.2MicroSwitch
➠Use
➠Wiring
➠Programming
8.3OpticalEncoder
➠Use
➠Assembly
➠Mounting
➠Storage
➠Wiring
➠Programming
8.4TheGyro
➠GeneralOverview
➠Specifications
➠Wiring
➠Programming
Sensors
141
FRCElectricalBible
roboRIOAccelerometer
➠GeneralOverview
OneofthemanyfeaturesthatcomeswiththeRoboRIOisthebuilt-in3-axisaccelerometer,
whichhasthepotentialtoreplacetheADXL345accelerometerthatalsocomesinthe2015
KitofParts.Thepurposeofthisdeviceistodeterminetheproperaccelerationofanobject,
whichisitsaccelerationrelativetofreefall.Thiscanbeusedtodeterminehowmuchthe
robotistiltedorawaytomonitormotion.
➠Specifications
Axes:3(x,y,andz)
SampleRate:800Samplespersecond
Resolution:12bits
Range:±8g(gravity)
Noise:3.9mgmstypicalat25°C
roboRIOAccelerometer
142
FRCElectricalBible
➠TheCode
Thisisthecodeweusedtodeterminethedirectionofeachaxisaswellasthestabilityofthe
returnedvalues.
#include"WPILib.h"
classRobot:publicSampleRobot{
BuiltInAccelerometeraccelerometer;
constdoublekUpdatePeriod=0.005;//5milliseconds/0.005seconds.
public:
//setstherangeoftheaccelerometertobe+or-8G(unitsofgravity)
Robot():accelerometer(Accelerometer::Range::kRange_8G){
}
voidOperatorControl(){
doublexAcceleration;//accelerationonthex-axis
doubleyAcceleration;//accelerationonthey-axis
doublezAcceleration;//accelerationonthez-axis
doublepreviousX=0;//Previousrecursiveaverageonx-axis
doublepreviousY=0;//Previousrecursiveaverageony-axis
doublepreviousZ=1;//Previousrecursiveaverageonz-axis
while(IsOperatorControl()&&IsEnabled()){
xAcceleration=accelerometer.GetX();//returnsx-axisaccel
yAcceleration=accelerometer.GetY();//returnsy-axisaccel
zAcceleration=accelerometer.GetZ();//returnsz-axisaccel
SmartDashboard::PutNumber("X-AxisG:",xAcceleration);
SmartDashboard::PutNumber("Y-AxisG:",yAcceleration);
SmartDashboard::PutNumber("Z-AxisG:",zAcceleration);
SmartDashboard::PutNumber("RecrusiveX-AxisAverage:",((xAccele
//returnsarecursiveaverageforthex-axis
SmartDashboard::PutNumber(“RecursiveY-AxisAverage:",((yAccele
//returnsarecursiveaverageforthey-axis
SmartDashboard::PutNumber(“RecursiveZ-AxisAverage:”,((zAccele
//returnsarecursiveaverageforthez-axis
roboRIOAccelerometer
143
FRCElectricalBible
previousX=(xAcceleration*0.1)+(0.9*previousX);
previousY=(yAcceleration*0.1)+(0.9*previousY);
previousZ=(zAcceleration*0.1)+(0.9*previousZ);
Wait(kUpdatePeriod);//Waitashortbitbeforeupdatingagain
}
}
};
START_ROBOT_CLASS(Robot);
➠TheExplanation
BuiltInAccelerometeraccelerometer;
DeclaretheRoboRIOaccelerometerasBuiltInAccelerometer;declaredbetween public
SampleRobotand public:RobotDemo
public:
//setstherangeoftheaccelerometertobe+or-8G(unitsofgravity)
Robot():accelerometer(Accelerometer::Range::kRange_8G){
}
InitializestheroboRIOaccelerometerwitharangeof+/-8Gs,whichistheaccelerationin
unitsofgravity(9.81m/s).Thisisthemaximumrangethatthedeviceiscapableof.Thereis
noneedtoinputpwmportsastheaccelerometerisbuiltin.
voidOperatorControl(){
doublexAcceleration;//accelerationonthex-axis
doubleyAcceleration;//accelerationonthey-axis
doublezAcceleration;//accelerationonthez-axis
doublepreviousX=0;//Previousrecursiveaverageonx-axis
doublepreviousY=0;//Previousrecursiveaverageony-axis
doublepreviousZ=1;//Previousrecursiveaverageonz-axis
roboRIOAccelerometer
144
FRCElectricalBible
Inthissectionweinitializethevariablesthatwewillbeusingforoutputonthe
SmartDashboard.Sincetheaccelerometerhas3axes,weneedavariableforeachone(x,
y,andz).Thepreviousaxisvariablesareusedtodeterminearecursiveaveragethatis
explainedlaterinthisdocument.Theyaremeanttostorethevalueoftherecursiveaverage
ofallpreviouslyreturnedvalues. previousXand previousYareequalto0becausethatis
theexpectedvaluewhentheroboRIOisatrestandonaperfectlyhorizontalsurface.
previousZisequalto1becausetheroboRIOisnotinfreefall,whichiswhatan
accelerometermeasuresaccelerationinreferenceto.
while(IsOperatorControl()&&IsEnabled()){
xAcceleration=accelerometer.GetX();//returnsx-axisaccel
yAcceleration=accelerometer.GetY();//returnsy-axisaccel
zAcceleration=accelerometer.GetZ();//returnsz-axisaccel
SmartDashboard::PutNumber("X-AxisG:",xAcceleration);
SmartDashboard::PutNumber("Y-AxisG:",yAcceleration);
SmartDashboard::PutNumber("Z-AxisG:",zAcceleration);
Here,thevariables xAcceleration, yAcceleration,and zAccelerationarebeingsettothe
currentvaluesoftheaccelerometerpertainingtothex,y,andzaxis.Afterupdatingthese
values,theyarethensenttotheSmartDashboardtobereadintheformofarunningvalue
oratable.
SmartDashboard::PutNumber("RecrusiveX-AxisAverage:",((xAccele
//returnsarecursiveaverageforthex-axis
SmartDashboard::PutNumber(“RecursiveY-AxisAverage:",((yAccele
//returnsarecursiveaverageforthey-axis
SmartDashboard::PutNumber(“RecursiveZ-AxisAverage:”,((zAccele
//returnsarecursiveaverageforthez-axis
previousX=(xAcceleration*0.1)+(0.9*previousX);
previousY=(yAcceleration*0.1)+(0.9*previousY);
previousZ=(zAcceleration*0.1)+(0.9*previousZ);
Wait(kUpdatePeriod);//Waitashortbitbeforeupdatingagain
}
}
};
START_ROBOT_CLASS(Robot);
roboRIOAccelerometer
145
FRCElectricalBible
Herewecalculatetherecursiveaverageforeachaxiswhichcanbeusefulduringtesting.
Thepurposeofhavingthisrecursiveaverageistoeffectivelyreducethesensitivityofthe
returnedvaluestofluctuations.Thisallowsyoutogetamoreaccurateandstablereadingfor
eachaxisoftheaccelerometer,andcouldbeusedtotestforvaryinganglesthatthe
accelerometeristilted.
Thissimplerecursiveaveragealgorithmisdonebytaking.1ofthecurrentvalueforanaxis
andaddingitto.9ofthepreviousaverage.Thisessentiallymeansthatwehaveaconstantly
changingaverage.Notethatthesensitivityofthisalgorithmcanbeadjustedbychangingthe
“0.1”and“0.9”values.However,rememberthatthetwomultipliersmustaddtoavalueof1,
becausetheaveragewilltendtocontinueincreasingordecreasingdependingonhowthe
multipliersareadjusted.Ifyouhaveamultipliersof.01and.99,thecurrentaveragewillbe
muchlesssensitivetochangeastheweightofeachnewnumberisdrasticallydecreased.
roboRIOAccelerometer
146
FRCElectricalBible
Microswitch
➠Use
Themicroswitchisusuallyusedtokeepsomethingfromoverextendingorsurpassingsome
distance.Whentheswitchnotpushed,theswitchisNC(normallyclosed),returning1.When
theswitchpushed,theswitchisNO(NormallyOpen),returning0.
➠Wiring
Microswitch
147
FRCElectricalBible
TheswitchispluggedintotheDigitalIOsectionoftheroboRIOviaaPWMcable.
➠Programming
Declaredandinstantiatedasa DigitalInput
WhenswitchNC,returns0
WhenswitchNO,returns1
Declaration: DigitalInputswitch;
Instantiation: switch(1)//portnumberinthedigitalsidecar
Microswitch
148
FRCElectricalBible
UsingMicroswitch: switch.Get();//returnseither0or1
//ABarebonesCode
#include"WPILib.h"
//Lastmodified:February7,2014by:Vivian
classRobotDemo:publicSampleRobot{
DigitalInputlimitSwitch;
public:
RobotDemo(void):
limitSwitch(1){
}
voidAutonomous(void){
}
voidOperatorControl(void){
while(IsOperatorControl())
{
if(limitSwitch.Get()==1){
//youcandothingshereiftheswitchispressed
}
}
}
voidTest(){
while(IsTest()){
}
}
};
START_ROBOT_CLASS(RobotDemo);
Microswitch
149
FRCElectricalBible
OpticalEncoder
➠Use
TheopticalencoderisthemostcommontypeofencoderinFRCthatusesoneormore
LEDspointedatastriporslitcodewheelandtwodetectors90degreesaparttomeasure
therotationspeedofawheelorothershafts.TheencoderpicturedtotheleftisaUSDigital
E4P(am-0174)opticalencoder.
Specs
MaxRPM:10,000RPM
100-360cyclesperrevolution
400-1440pulsesperrevolution
Minimumshaftlength:.375”(⅜)
ShaftDiameter:.079”to.250”
Weight:.018lbs
➠Assembly
1. Placebaseovershaft.Securebasetomountingsurfaceusingeitherthetwoscrewson
thebaseoramountingpad.
OpticalEncoder
150
FRCElectricalBible
Mountingthebasewithoutamountpad
Mountingpadplacedunderthebaseifused.
2. Placehubdiskassemblyontoshaftwithpattern-sidedowntowardsbase.Itshouldnot
becompletelypresseddown.
3. Usethespacer(lipfacingdownwards)topushthehubdiskassemblytotheappropriate
locationontheshaft.Thediskshouldnotbetouchinganythingbesidestheshaftand
thespacer,andthereshouldbeaconsiderablegapbetweenthediskandthebase.
OpticalEncoder
151
FRCElectricalBible
4. Removethespacerwhileensuringthatthediskstaysinplace.
5. Placethehousingontopoftheencoder.Usingyourthumbandfinger,squeezeears
togethertoensurethatthecoverfullylatches.
➠Mounting
Itiseasiestiftheopticalencoderisplacedontheoutputshaftasthereisadirectcorrelation
betweentherotationoftheshaftandthemovementofwhateveritcontrols.Alsoensurethat
theopticalencoderisperfectlycenteredaroundtheshaft.
➠Storage
Theopticalencodercangetscratchedeasilysoitshouldbestoredinaspecialcaseto
preventscratchingorinaplacethatwillnotscratchthesurfaceofthedisk.
OpticalEncoder
152
FRCElectricalBible
➠Wiring
Thewiringfortheopticalencoderusestwochannels(DigitalIO;A/B)forthePDPsofour
wireshavetobesolderedtotwoPWMs.
Orange:Power------------------------------->PWM2Power
Blue:ChannelA------------------------------>PWM1Signal
Brown:Ground------------------------------->PWM2Ground
Yellow:ChannelB---------------------------->PWM2Signal
➠Programming
//CodeUsedforTestingwithroboRIO
#include"WPILib.h"
OpticalEncoder
153
FRCElectricalBible
/**
*EncoderTestUsingMotor
*/
classRobot:publicSampleRobot{
Encoderencoder;
Joysticklogitech;
Talontalon;
//updateevery0.005seconds/5milliseconds.
doublekUpdatePeriod=0.005;
public:
Robot():
encoder(1,2,false,Encoder::k4X),
logitech(0),//Initializelogitechonport0.
talon(0)//InitializetheTalononchannel0.
{
encoder.SetSamplesToAverage(5);//Usedtoreducenoiseinperiod
encoder.SetDistancePerPulse(1.0/360);//ThismakesitsothatGetDi
//makesafullrotationandthatGetRatewillbeinRevspersecond
}
voidOperatorControl(){
encoder.Reset();
while(IsOperatorControl()&&IsEnabled()){
talon.Set(logitech.GetY());
//getsthey-axisontheLEFTlogitech
while(encoder.GetDistance()<2){
talon.Set(-0.2);
SmartDashboard::PutNumber("EncoderDistance",encoder.GetDis
//printsdisplacementinrevolutions
SmartDashboard::PutNumber("EncoderRate",encoder.GetRate())
//printsrateinRevspersecond
Wait(kUpdatePeriod);
}
}
}
};
START_ROBOT_CLASS(Robot);
OpticalEncoder
154
FRCElectricalBible
OpticalEncoder
155
FRCElectricalBible
Gyro
➠GeneralOverview
Thegyromeasuresangularchangesonthetopsurfaceaxis.Thevoltageoutputdependson
theangularchangeitdetects.Itcanalsomeasuretherateofangularchange.Itnormally
wouldbeusedintandemwiththeaccelerometer,sincetheaccelerometercandetect
absoluteanglevsangularmotion.Thegyrobestfunctionsatthecenteroftherobot’saxisof
rotation.Whenmountingit,keepthegyroawayfromanythingthatmightfrythegyro,soitis
besttoelectronicallyisolateitfromthemainmountingboard.Noteworthyisthatitalso
containsatemperaturesensor,usefulfordetectingheatwithintherobotsystemduring
operationifathermaldetectorisnotavailableorduringamatch.
➠Specifications
Thegyroacceptsa+5Vforpower,canrecordupto250O/s,hasanominaloutputof2.5Vat
standstill,adds7mV/O/s.Boardcarriesafiltersetto400Hz.Containsintegrated
temperaturesensorwhichacceptsa+5Vforpowerwithnominaloutputat2.5Vat25OC,
adds9mV/OC.
➠Wiring
Gyro
156
FRCElectricalBible
WirestotheroboRIOAnalogINportsusingafemale-to-femalePWM.Ground,Power,
Signalfromoutsideinrespectively.
WirestotheGyrosensorwiththeotherendofthefemale-to-femalePWM.Ground,Power,
Signalfromoutsideinrespectively.
➠Programming
Gyro
157
FRCElectricalBible
#include"WPILib.h"
classRobot:publicSampleRobot
{
Joystickstick;//onlyjoystick
Gyrogyro;//Gyrosensor
doubleangleTurn=0.0;
doubleangleRate=0.0;
doubledriftRate=0.0;
public:
Robot():
stick(0),//thesemustbeinitializedinthesameorder
gyro(0)//astheyaredeclaredabove.
{
gyro.InitGyro();
}
voidOperatorControl(){
gyro.Reset();
while(IsOperatorControl()&&IsEnabled()){
if(stick.GetRawButton(2)){
gyro.Reset();
Wait(2);
driftRate=gyro.GetAngle();
SmartDashboard::PutNumber("driftrate",driftRate);
}
angleTurn=gyro.GetAngle();
angleRate=gyro.GetRate();
SmartDashboard::PutNumber("Gyroangle",angleTurn);
SmartDashboard::PutNumber("Rateofturning",angleRate);
Wait(0.05);
}
}
};
START_ROBOT_CLASS(Robot);
Gyro
158
FRCElectricalBible
TheD-Link
Camera
159
FRCElectricalBible
TheD-Link
LiveFeed
160
FRCElectricalBible
TheD-Link
Pneumatics
161
FRCElectricalBible
TheD-Link
Appendixes
162
FRCElectricalBible
Changelog
January10,2016,modifiedbyVivian
UpdatedPDPchapter
AddedSensorschapter
MadeformattingchangestoDriveCodechapter
AddedManualConfigurationtoD-Linksection
February23,2015,modifiedbyVivian
AddedDriveCode
FixedTableofContents
February5,2015,modifiedbyVivian
AddedDriverStationDocumentation
AddedMotorControllerDocumentation
February2,2015,modifiedbyKayliandAlex
AddedPDPDocumentation
AddedD-LinkDocumentation
Changelog
163
Was this manual useful for you? yes no
Thank you for your participation!

* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project

Download PDF

advertisement