0
1
1.1
1.2
1.3
1.4
1.5
1.6
2
2.1
2.2
2.3
2.4
3
3.1
3.2
3.3
3.4
4
4.1
4.2
4.3
5
5.1
5.2
5.3
5.4
6
6.1
6.2
TableofContentsIntroduction
TheroboRIO
GeneralroboRIOOverview
ConfiguringtheroboRIO
ConnectingtotheroboRIOWirelessly
UploadingCodetotheroboRIO
TheCANBus
TheRobotSignalLight
ThePowerDistributionBoard(PDP)
ThePDP
120ACircuitBreaker
TheVoltageRegulatorModule
ThePowerConverter
TheD-Link
ThePhysicalLayer
AutomaticConfiguration
ManualConfiguration
TroubleshootingtheD-Link
DriverStation
Introduction
TheInterface
PrintingtoDriverStation
ACrashCourseonC++
Variables
Functions
ObjectUsage
TheJoystick
MotorControllers
GeneralOverview
Motors
FRCElectricalBible
2
6.3
6.4
6.5
6.6
6.7
6.8
7
7.1
7.2
7.3
7.4
8
8.1
8.2
8.3
8.4
9
9.1
9.2
10
10.1
10.2
10.3
11
11.1
11.2
11.3
12
12.1
13
Jaguar
Victor888
Talon
TalonSRX
Spike
Fans
DriveCode
BoxonWheels
BoxonWheelsTemplatevsCustomProgram
CustomProgram(TankDrive)
CustomProgram(MecanumDrive)
Sensors
roboRIOAccelerometer
Microswitch
OpticalEncoder
Gyro
Camera
Hardware
SettinguptheCamera
LiveFeed
TheCode
UsingNIVisionAssistant
DevelopingCameraCode
Pneumatics
ThePhysicalLayer
PneumaticsCircuit
PneumaticsCode
Appendixes
AppendixA:GeneralWiringDiagram
Changelog
FRCElectricalBible
3
TheElectricalBible-Beta
WelcometoourElectricalFIRSTopedia!
WecreatedthisguideinhopesofcombiningabasicunderstandingofalltheelectroniccomponentstheFRCrobotusesintoonecohesiveandcomprehensiveguide.ThisguidewasmadewiththepowerofGoogleDocs,GitBook,ourphones’camerasandendlessGooglesearches.
Thisguidehasbeenupdatedtoincludethe2015controlsystem.Ourolderdocumentcanbefoundhere,andincludesdocumentationonthecRIO.
SomethingtonoteisthatweprograminC++,soreferencestoclasseslike“Encoder”andoursamplecodesarewritteninC++.However,classesareinterchangeableinJavaandC++,andtherearetopicscoveredinthisguidethatarenotlanguage-exclusiveliketheroboRIOandtheDriverStationitself.Wehopethisisguideservestobeusefulforyou!
Team2853Electrical/ProgrammingTeam
IfyouareviewingthisonGitHub,pleaseusetheGitBooklink:https://mililanirobotics.gitbooks.io/frc-electrical-bible/content/index.html
FRCElectricalBible
4Introduction
1.TheroboRIO
1.1GeneralroboRIOOverview
➠WhatisaroboRIO?
➠Connectors
➠WiringDiagram
1.2ConfiguringtheroboRIO
➠Installing/UpdatingNewFirmware
➠Imaging/ReimagingaroboRIO
1.3ConnectingtotheroboRIOWirelessly
1.4UploadingCodetotheroboRIO
1.5TheCANBus
➠Introduction
➠WiringtheCAN
FRCElectricalBible
5TheroboRIO
GeneralroboRIOOverview
➠WhatisaroboRIO?
AroboRIOisamorerecentversionofthecRIO(compactReconfigurableInput/Output)thatwasintroducedtoFRCteamsinthe2015season.Itisafaster,smaller,andmorepowerfulversionofthepreviouscontroller.LikethecRIO,itactsasthebrainoftherobot,andconnectstoaD-Linkrouterusinganethernetcable.Additionally,theroboRIOcombinesthefunctionsofthedigitalsidecarincludingthedigitalandanalogmodulesofthepreviouscontrolsystem.TheroboRIOismorerobustthanthedigitalsidecar,andisprotectedfromshortsbetweenitsexternalpins.
Specs
BasicOverview
Dual-CoreARMCortex667MHzprocessor256MBRAM512MBNANDstoragememoryLinuxOperatingSystemwithreal-timeextensionsSupportsLABVIEW,C++,andJava
Physical/ElectricalCharacteristics
6.8Vto16Vinputpower(stagedbrownoutfrom4.5Vto6.8V)3.3Vuseroutput(with1.5Amaximum)5Vuseroutput(with1Amaximum)6Vservooutput(with2.2Amaximum)Operatingtemperature0°C-40°CStoragetemperature-20°C-70°C5.7inchesby5.6inches,weighs12ouncesI/OandCommunicationPorts
10dedicatedPWMchannels
FRCElectricalBible
6GeneralroboRIOOverview
10DIOdedicatedchannels4bi-directionalRelayControlchannels2USBHostports1USBDeviceport1Ethernetport1CANPort1Integrated,3-axisaccelerometer12VRobotsignallightchannel
➠Connectors
WeidmullerConnectorsareusedtosupplypowertotheroboRIO,PCM(PneumaticControlModule),andVRM(VoltageRegulatorModule).Theconnectoracceptswiregaugesfrom16AWGto24AWG.WirescanbeinsertedintoorremovedfromtheWiedmullerconnectorbypushingdownonthewhitetabusingatinyflathead.
➠WiringDiagram
FRCElectricalBible
7GeneralroboRIOOverview
Notes:
TheCANPortsontheroboRIOareusedtoconnecttothePCMandPDPTheroboRIOisconnectedtothePDPthroughitsinputpowerports.DonotconnecttheroboRIOdirectlytotherobotbattery.TheUSBDeviceportcanbeusedtoconnecttoacomputertoupdatetheroboRIOfirmwareandtoreimagetheroboRIO.TheLEDsindicatethecurrentstatusoftheroboRIO.TheroboRIOcanbemountedusingzip-tiesthroughthemountingfeatures.PleaseseetheAppendixforanexamplewiringofthewholecontrolsystem.
FRCElectricalBible
8GeneralroboRIOOverview
ConfiguringtheroboRIOBeforeabrandnewroboRIOcanbeputintoaction,youmustfirstinstallthelatestroboRIOfirmwareandthenre-imagethesoftwareusingthelatestversion.Beforeyoubegin,ensurethattheNI(NationalInstruments)suiteisupdated.TheNIupdateaswellasinstructionsfordownloadingitcanbefoundbelow:https://wpilib.screenstepslive.com/s/4485/m/13503/l/144150-installing-the-frc-2015-update-suite-all-languages
➠InstallingandUpdatingtheroboRIOfirmware
PriortotheimagingoftheroboRIO,thefirmwareontheroboRIOmustbeupgradedtothelatestversion.Thisprocesswillprovidethebootloader,safemode,andfirmwarefortheroboRIO.Whileitispossibletodothisusinganethernetconnection,itisnotrecommended.Thefirmwarecanbeupdatedusingyoursystem’swebbrowserinthefollowingsteps:
FRCElectricalBible
9ConfiguringtheroboRIO
1. Asshownintheelectricallayoutbelow,connecttheroboRIOtoyourcomputerusingaprinterUSBcableandsupplypowertotheroboRIO.
2. Thedrivershouldinstallautomatically.Oncethedownloadiscomplete,openawebbrowseronyourcomputer.
3. Intheaddressbarofthewebbrowser,type“172.22.11.2”andpressenter.
4. Clicklogin.“admin”willbetheusernameandleavethepasswordfieldblank.Then,click“UpdateFirmware”
5. LookfortheroboRIO(.cfgfileinyourNationalInstrumentsfolder.Thedefaultlocationofthisfileisunder“ProgramFiles\NationalInstruments\Shared\Firmware\cRIO\76F2”
FRCElectricalBible
10ConfiguringtheroboRIO
6. Click“BeginUpdate”
➠ImagingandReimagingtheroboRIO
TheroboRIOImageloadstheFPGA,operatingsystem,linuxfilesystem,anddefaultsettingsfortheroboRIO.NowthattheroboRIOhasthelatestfirmwareinstalled,itisnowpossibletoimagetheroboRIOinthefollowsteps:
1. EnsurethattheroboRIOisstillpoweredfromthePDP(PowerDistributionPanel)andisstillsecurelypluggedintothecomputerusingaprinterUSBcable.
2. LookfortheroboRIOImagingtool(.exefile)asshownbelow.ItislocatedwithintheNationalInstrumentsfilefolder,anditsdefaultlocationis“NationalInstruments\LabVIEW2014\project\roboRIO”
3. Doubleclicktorunthe“roboRIO_ImagingTool.exe”application,andthetheinterfacewillattempttoidentifyconnectedroboRIOdevices.
4. Enteryourteamnumberunder“SystemInformation.”SelectthelatestversionoftheroboRIOImage(indicatedbythehighestversionnumber)andthenameoftheroboRIOyouintendtoimage.
5. SelecttheFormatTargetoptionbutmakesurethattheConsoleOutandDisableRTStartupAppoptionsarenotselected.Click“Reformat”
6. OncetheImagingiscomplete,click“OK”onthecompletionmessageandRebootthe
FRCElectricalBible
11ConfiguringtheroboRIO
roboRIOusingtheResetbutton.
FRCElectricalBible
12ConfiguringtheroboRIO
ConnectingtotheroboRIOWirelessly1. ChangetheIPaddressandsubnetmaskofyourcomputer.TheIPaddressshouldbe
“10.xx.yy.100”,withxxandyybeingyourfourdigitteamnumber,andthesubnetmaskshould“255.0.0.0”
2. Connecttotheteam’swirelessrouter.It’sthateasy!
FRCElectricalBible
13ConnectingtotheroboRIOWirelessly
FRCElectricalBible
14ConnectingtotheroboRIOWirelessly
UploadingCodetotheroboRIOWiththeintroductionoftheroboRIOtoFRCteamsin2015,uploadingcodetotherobotismadeeasy!Here’sthesteps:
1. Establishanetworkconnectiontoyourrobotnetwork.Onyourcomputer,gotoyournetworkconnectionsandconnecttotherouterthatisconnectedtotheroboRIO.Don’tworryifyou’realreadyconnectedtoanothernetwork,asyouwillautomaticallydisconnectfromthatnetworkconnection.
Connectingtoanetwork
2. BuildyourProject.Clickthe“Project”optionandthenclick“BuildProject.”TouploadcodetotheroboRIO,itisonlynecessarytobuildtheprojectforuploadingcodethathasn’tbeenbuildinthepastorwasmodified,butit’sagoodhabittoalwaysbuildyourprojectsbeforeuploadingthemtotherobot.Therefore,werecommendedhavingyour
FRCElectricalBible
15UploadingCodetotheroboRIO
projectsbeforeuploadingthemtotherobot.Therefore,werecommendedhavingyour“BuildAutomatically”settingenabled.
BuildinganEclipseproject
3. Runyourcode.PressCtrl+F11,andwhenpromptedhowyouwouldliketorunyourcode,selectthe“WPILibC++Deploy”optionandpressOK.Nowyou’redone!WaitfortheDriverStationtoshowthatcommunicationshasbeenestablished,andyou’llbeonyourwaytotestingyourcode!
Runningyourcodeusing“WPILibC++Deploy”
FRCElectricalBible
16UploadingCodetotheroboRIO
FRCElectricalBible
17UploadingCodetotheroboRIO
TheCANBus
➠IntroductionAsofthe2015FRCgame,RecycleRush,teamsarerequiredtousetheCANbusontheroboRIOwhenconnectingtothePCM,PDP,TalonSRXs,andJaguars(R60-62).
ThissectionwillnotgooverhowtouseCANontheTalonSRX(youcanreadCTR’sTalonSRXUserguide)ortheJaguar,becauseourteamdoesnothaveexperiencewiththeseitems.
ByconnectingthecontrolsystemtogetherwithCAN,thePDPandPCMcancommunicatewitheachother.ThePDPprovidesmonitoringforeachofitsoutputs.AmainadvantageofthissystemisthatcompressorsandpressureswitchesnolongerneedtobeconnectedtoaRelaySpike.
➠WiringtheCAN
Whenwiring,werecommendtwistingthetwowirestogether.Therearenospecificbusesforinput/outputbutbyconvention,weusetheleftbusasinputandrightbusasoutput.
IfyouarenotusingtheroboRIOorPDPasterminalsfortheCANchain,terminatetheCANchainbyinsertinga120ΩresistorintotheWeidmullerterminals.
FRCElectricalBible
18TheCANBus
TheRobotSignalLight
➠IntroductionTheRobotSignalLight(RSL)ismandatoryduringcompetitionandactsasasignaltowhethertherobotisconnectedtotheFCS,inteleopmode,etc.
➠WiringtheRSL
AseparatewireactsasajumperbetweenLaandLb.ConnectLato'S'andNtoGroundontheroboRIO.
➠RSLIndicators
FRCElectricalBible
19TheRobotSignalLight
LightCode Meaning
SolidON Autonomousenabled
SolidONbutblinksoffevery1.5sec
Teleopenabled
Slowblink(900msON/900msOFF)
Systemdisabledbysystemwatchdog,userwatchdog,ordriverstationsettodisabled
Fast-slow(200msON/900msOFF)
Lowbattery(<12V)ornousercodeANDsystemdisabledeitherbysystemwatchdog,userwatchdog,orDriverStationsettodisabled.
Fast(200msON/200msOFF)
Systemerror;noDriverstationcommunication;badcRIOimage,badteamID,extensivecommunicationerrors
FRCElectricalBible
20TheRobotSignalLight
2.ThePDP
2.1ThePDP
➠Wiring
2.2120ACircuitBreaker
2.3TheVoltageRegulatorModule
➠Wiring
2.4ThePowerConverter
FRCElectricalBible
21ThePowerDistributionBoard(PDP)
ThePDP
ThePDPisaneweriterationofthePDBthatwasintheKitofPartsgiventoteamsinthe2015FRCseason.ThemaindifferencebetweenthetwoisthatthePDPisslightlysmaller,lighter,andhasupdatedconnectors,whichincludestheWeidmullerConnectorsusedontheCANbus.Ingeneral,thePDPservesthesamefunctionasthePDB,distributingpowertothesystem,butisimprovedtobetterreflecttheupdatesmadetotherestofthecontrolsystem.
Specs
Dimensions:7.586”x4.748”x1.442”tall(rough)Weight:1lband5.3oz4Mountingholes(oneateachcorner,smallerthan1/4-20andlargerthan10-32fasteners)Connectors
MainBatteryInput2BushinglugsThreadM6x1(size6mm)
PowerChannels(0-15)
FRCElectricalBible
22ThePDP
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
4PositionWeidmullerConnectors2YellowCANHigh2GreenCANLow
StatusLightsBothLightsarealwaysthesamecolor/blinkingpatternwiththeexceptionofbootingupFastGreenBlink-RobotisenabledSlowGreenBlink-RobotisdisabledSlowOrangeBlink-Robotisdisabled&StickyFaultpresent(lowvoltage,<6.5VSlowRedBlink-NoCANcommunicationBootStatuslights(COMMLEDonly)
Green/OrangeBlink-Deviceisinboot-loader/Field-upgradenecessaryBothLEDsoff-DeviceisNOTpowered
FRCElectricalBible
23ThePDP
120ACircuitBreakerCurrentlyneedstobedocumented.
FRCElectricalBible
24120ACircuitBreaker
TheVoltageRegulatorModule
➠GeneralVRMOverview
Imagecourtesyofhttp://khengineering.github.io/
➠WhatisaVRM?
TheVoltageRegulatorModule(VRM)isanewcomponentintroducedinthe2015FRCseasonaspartoftheKitofParts.Thisreplacesthe12Vand5VregulatorandspecialprotectedandunprotectedpoweroutputsontheoldPDB.ThepurposeoftheVRMistoactasaDCtoDCconverter,andbothboostandbuckvoltageregulation.TheVRMisrequiredwhenusingcomponentsthatrequirespecialprotectedpower.
Specs
Dimensions:2.220”x2.030”x0.784”Tall
Weight:1.8oz
4mountingholes(oneateachcorner,6-32fasteners)
Connectors(alluseWeidmullerconnectors,accepting24-16AWG)
FRCElectricalBible
25TheVoltageRegulatorModule
4xconnectorsforregulated12V/2Amaxsurge/1.5Alimitpoweroutput
4xconnectorsforregulated12V/500mAmaxsurgepoweroutput
4xconnectorsforregulated5V/2Amaxsurge/1.5Alimitpoweroutput
4xconnectorsforregulated5V/500mAmaxsurgepoweroutput
2xconnectorsforunregulated12Vinput
StatusLights
5V/500mAStatusLEDOn-5VchannelsarepoweredOff-Breakerhastripped
12V/500mAStatusLEDOn-12VchannelsarepoweredOff-Breakerhastripped
LEDsnotaffectedwhen2Achannelsarelimited
Flickering-Lowvoltage(<4V)
➠Wiring
AllportsuseWeidmullerconnectors,accepting24-16AWG
Note:Therearetwoseparatepowersupplies,12Vand5V.ThereisjustenoughpowertorunbothaD-LinkandCameraonthe5Vrail,butyoumayneedtouseaseparate12Vto5Vadapter.
FRCElectricalBible
26TheVoltageRegulatorModule
ThePowerConverter
Althoughwehavethevoltageregulatormodule,ifyouarelookingtopower>1camera,youwillneedapowerconvertersothecameracanoperateunderit'snecessaryvoltage.ThepowerconverterplugsintothePDPwitha20Acircuitbreaker.
FRCElectricalBible
27ThePowerConverter
WiringthePowerConverter
FRCElectricalBible
28ThePowerConverter
FRCElectricalBible
29ThePowerConverter
3.TheD-Link
3.1ThePhysicalLayer
➠Introduction
➠TheVoltageRegulatorModule
3.2AutomaticConfiguration
➠2015ConfigurationPrerequisites
➠FRCConfigurationBridgeUtility
3.3ManualConfiguration
➠Setup:LANSettings
➠SetaDeviceName
➠SettheLANConnectionType
➠ConfiguretheIPv4Address,SubnetMask,andDefaultGateway
➠WirelessSettings
3.4TroubleshootingtheD-Link
FRCElectricalBible
30TheD-Link
ThePhysicalLayer
➠Introduction
WecontroltherobotthroughaLogitechgamepadcontroller.Generally,wewouldn’twanttofollowtherobotaroundwithanethernetcable,sowesolvethisproblembyconnectingwirelessly.WeusetheD-Linkasamediumtocommunicatewiththerobotinthisfashion.
➠TheVoltageRegulatorModuleAsofthe2015FRCgame,RecycleRush,theDLinkisrequiredtobepoweredbythe5V/2AAKA“Radio”portontheVoltageRegulatorModule.YoucanreadmoreaboutittheThePowerDistributionPanelsection.
FRCElectricalBible
31ThePhysicalLayer
TheD-Linkitselfisconnectedtoapoweradapterthatis:
5VOutputPowerCabletoD-LinkModelNo:AMS3-0502000FU
Barrel5.5/2.1mm
AndyMark-PowerConverter|
TheD-LinkconnectstothecRIOviaaStandardCAT-5EthernetCable.Itcanalsoactasthe“middle-man”withanEthernetcableconnectingtotheDriverStationlaptop.
FRCElectricalBible
32ThePhysicalLayer
MakesuretherouterhaspowerMakesuretheethernetcablesarepluggedinsecurely(onbothends)
NOTE:Itdoesn’tmatterwhichLANPortstheethernetcablesarepluggedinto.However,byconventionweusuallymakesurethattheroboRIOconnectstoport2andacomputerplugsintoport1.
FRCElectricalBible
33ThePhysicalLayer
AutomaticConfiguration
➠2015ConfigurationPrerequisites1. MakesurethattherouterisswitchedtotheAccessPointmodeyourequest(2.4Ghz,
5.0Ghz,Bridge).Asettingof2.4GhzisappropriateformostFRCteamsandshouldbeusedasthedefault.
2. EnsurethatyourcomputerhasJavainstalled.Ifyou’reunsureorneedtocheckordownloadtheJavasoftware,usethislink:http://www.java.com/en/download/index.jsp
3. AlsoensurethattheNISuiteisupdated,whichincludestheFRCBridgeConfigurationUtilitytoconfigurearoutertouseinFRC.TodownloadtheNewFRCSoftware,usethislink:http://wpilib.screenstepslive.com/s/4485/m/13503/l/144150-installing-the-frc-2015-update-suite-all-languagesNOTE:Toresettherouterpressandholdtheresetbuttonfor30secondstoperformafactoryresettowipeanypreviousconfigurations
➠FRCBridgeConfigurationUtilityNOTE:Iftherouterisnotbrandnew,itisnotnecessarytopressandholdtheresetbuttonfor30secondstoperformafactoryresettowipeanypreviousconfigurationsbecausetheFRCsoftwarewilldosoforyou.
1. TurnofftheWifionyourcomputer2. Makesurethephysicallayerontherouterissetupproperly.3. LaunchtheFRCBridgeToolsoftware.ItislocatedundertheNationalInstruments
folder,anditsdefaultlocationisC:\ProgramFiles\NationalInstruments\LabVIEW2014\project\FRCBridgeConfigurationUtility.exe
FRCElectricalBible
34AutomaticConfiguration
4. UndertheNetworkInterfacespopupfromtheBridgeConfigurationUtility,Select“LocalAreaConnection”andpressOK.Iftherearenonetworkinterfacesshown,clicktherefreshbutton.
FRCElectricalBible
35AutomaticConfiguration
5. UndertheFRCBridgeConfigurationUtility,TypeinyourFRCteamnumberaswellasapasswordtobesetunderthesectionfor“WPAKey.”EnsurethattheRadiooptionissettoDAP1522RevB,andthattheModeoptionissettothecurrentprerequisitesetting(defaultof2.4GHzAccessPointshouldbeused).Nowclick“Configure.”
6. WaituntiltheConfigurationProgressiscomplete,andthenpressOKonceitisdone!NotethattherouterSSIDcanbeconfiguredthroughtheD-Linkap
FRCElectricalBible
36AutomaticConfiguration
ManualConfiguration
1. Openupyourwebbrowser(Firefox,Chrome,etc.)2. Intheaddressbar,typeintheIPaddressoftherouter.It’seither:
192.168.1.1,thedefaultIPaddress8OR10.xx.yy.1,wherexxisthefirsttwodigitsofyourteam’s#(itcanbeonedigitifyourteamhasathree-digit#)andyyisthelasttwoORtypeindlinkap/andhitenter.
3. You’llgetapromptfortherouternameandpasswordliketheoneshownbelow.Onabrandnewrouterorarouterthatwasreseted,thelogininfowillbethis:UserName:AdminNoPassword(bydefault)
FRCElectricalBible
37AutomaticConfiguration
➠Setup:LANSettings
FRCElectricalBible
38AutomaticConfiguration
➠SetaDeviceName:Teamxxxx-yxxxx=Yourteamnumbertoavoidconfusion.y=Arbitrarybutuniquenumbertoyourroutertoavoidconfusion.Youshouldbaseitonthenumberofroutersyourteamowns.ExampleDeviceName:Team2853-1➠SettheLANConnectiontype:“StaticIP"➠ConfiguretheIPv4Address,SubnetMask,andDefaultGatewayIPAddress:10.xx.yy.1xx.yy=YourTeamNumberxxcanbothbetheonedigitifyourteamhasathree-digitnumberExampleIPAddress:10.28.53.1SubnetMask:255.0.0.0DefaultGateway:10.28.53.4
FRCElectricalBible
39AutomaticConfiguration
➠WirelessSettings
EnableWireless:CheckmarktheBoxSettoAlways
WirelessNetworkName:Nameitto(whateveryouwant)
FRCElectricalBible
40AutomaticConfiguration
WirelessSecurityMode:SecuritytoWPAPersonalWPAmodetoWPA2OnlyCipherTypetoAESPre-sharedkeyistheNetworkSecurityKey
FRCElectricalBible
41AutomaticConfiguration
ManualConfiguration1. Openupyourwebbrowser(Firefox,Chrome,etc.)2. Intheaddressbar,typeintheIPaddressoftherouter.It’seither:
192.168.1.1,thedefaultIPaddressOR10.xx.yy.1,wherexxisthefirsttwodigitsofyourteam’s#(itcanbeonedigitifyourteamhasathree-digit#)andyyisthelasttwoORtypeindlinkap/andhitenter.
3. You’llgetapromptfortherouternameandpasswordliketheoneshownbelow.Onabrandnewrouterorarouterthatwasreseted,thelogininfowillbethis:
UserName:Admin
NoPassword(bydefault)
➠Setup:LANSettings
FRCElectricalBible
42ManualConfiguration
➠SetaDeviceName:Teamxxxx-y
xxxx=Yourteamnumbertoavoidconfusion.
y=Arbitrarybutuniquenumbertoyourroutertoavoidconfusion.Youshouldbaseitonthenumberofroutersyourteamowns.
ExampleDeviceName:Team2853-1
➠SettheLANConnectiontype:“StaticIP”
➠ConfiguretheIPv4Address,SubnetMask,andDefaultGateway:
IPAddress:10.xx.yy.1xx.yy=YourTeamNumber
FRCElectricalBible
43ManualConfiguration
xxcanbothbethefirstdigitifyourteamhasathree-digitnumberExampleIPAddress:10.28.53.1SubnetMask:255.0.0.0DefaultGateway:10.28.53.4
➠WirelessSettings
(red)EnableWireless:
CheckmarktheBoxSettoAlways
FRCElectricalBible
44ManualConfiguration
(green)WirelessNetworkName:
Nameitto(whateveryouwant)-youmaywanttoimplementanamingsystemsoyoudon'tgetmultipleroutersconfused.
(blue)WirelessSecurityMode:
SecuritytoWPAPersonalWPAmodetoWPA2OnlyCipherTypetoAESPre-sharedkeyistheNetworkSecurityKey
FRCElectricalBible
45ManualConfiguration
TroubleshootingtheD-LinkEnsurethatallnecessarycables(Powerand/orEthernetcables)arepluggedinsecurely.Ensurethattheswitchonthebackoftherouterissetto“AP2.4GHz”unlessyouhavespecificallysettherouteranditsconfigurationtoadifferentmode.EnsureyourrouterisnotlabeledBROKENwithelectricaltape.(Teamspecific)Tryresettingthepowerontherouter.Removeitspowersource,wait10seconds,thenplugthepowercablebackin.Sometimeswizardscomeandmagicallyfixtherouterwhenyoudothis.Trypoweringthroughanoutletusingthepoweradapterthatcamewithyourrouter.Tryresettingtherouter’sdata.Getatoothpickorsomeotherthinobject,thenuseittoholdtheresetbuttondownfor10seconds.Waitabout30secondsforittoreboot.Then,refertotheinitialconfigurationprocessabove.Routersdobreakdownanditspossiblethatit’ssimplybusted.However,thesethingsareexpensivesomakesureit’sbrokenbeforedeclaringthatyouneedtogetanewone.
AdditionalResources
GettingStartedwiththe2015ControlSystem
WPILib-GettingStartedwiththe2014FRCControlSystem
GettingStartedwiththe2013FRCControlSystem
D-LinkDAP-1522UserManual
AndyMarkProductPage
FRCElectricalBible
46TroubleshootingtheD-Link
4.DriverStation
4.1Introduction
4.2TheInterface
➠MainDisplay
➠OperationTab
➠DiagnosticsTab
➠SetupTab
➠Power&Can
➠Messages&Charts
4.3PrintingtotheDriverStation
FRCElectricalBible
47DriverStation
IntroductionThisisyourinterface--neat,organizedsimplicity.Itisn’tnecessarytoknowhowtowritecodeinordertousetheDriverStation,yousimplyneedtoknowthefollowing:
1. Howtodeploycode(connectingtotherobotisagiven)
2. Whatdeployedcodedoes
ThisistheprogramthatallowstototestanduseyourcodeonFRCcomponents.TheDriverStationisthemiddle-manbetweenyouandtherobot!,thisisyourmiddlemanbetweenyourcodeandtherobot!
DriverStationdefinitelygotanupdate:revisedappearance,morefeatures,what’snottolove?TogetherwecanrelearnthisadjustedDriverStation,itshouldn’tbeallthatdifferentcomparedtoitslastiteration,dependingonhowyoulookatit.
FRCElectricalBible
48Introduction
TheInterface
➠MainDisplayThisdisplayisindependentfromthesectionsleftandrightofthisdisplay,itwillalwaysbeinview(whileDriverStationisopenofcourse)evenifyouswitchtabsontheDriverStation(SeeTabSelection,alsoCharts&Messages)
1. YourTeam#,thiscanbeconfiguredpersonallyintheSetupTab(SeeTabSelectionSection:➠SetupTab)
2. CurrentvoltageofthebatteryinV(volts)hasavisualindicatortotheleftintheformofapictorialrepresentationofabattery(fillslikeabartorepresentamountofcharge).
3. LightsindicatingtheDriverStation’sstatusondetectingit:Redmeansthereisnoconnection,greenmeansaconnectionhasbeenestablished.Ifyouhoverovereachofthe3lines,atroubleshootingmessageappearsinthemessagestab(SeeCharts&Messages)iflightisred.
4. Displayscurrentmodeenabledordisabledunlessthefirsttwolightsarered,inorder,“NoRobotCommunication”,“NoRobotCode”(SeeTabSelection:➠OperationTabformodes)
➠TabSelection
FRCElectricalBible
49TheInterface
Redboxesindicatetabselectionandthehighlightedtabisthecurrenttab,intheblueboxisthecurrentlydisplayedtab(automaticallydisplaysOperationsTabwhenDriver
➠OperationTab
1. Thedepressedbuttoniswhatstatetheperiodisin;canpress[]\toquicklyenable,canpressEnterbuttontoquicklydisableifthefirsttwolightsinMainDisplayarelit(Communications&RobotCode)
2. Availablemodes,currentmodeisdepressed(Teleoperatedbydefault),youcanswitchmodesbyclickingoneofthe3buttons
3. NEW:VisualindicatorofyourPCCPU%usageElapsedTimesinceyouclicked“Enable”untildisabled
FRCElectricalBible
50TheInterface
➠DiagnosticsTab
1. WhattheDriverStationhascommunicationswith;ifpluggedthroughEthernetdirectlytosomething(routerorroboRIO),EnetLinkwilllightup.DSRadioisalegacyindicatorofpingstatusofanexternalradioat10.TE.AM.4(ComparedtolastDriverStation,thislightwillusuallynotbelitexceptunderspecificcircumstances[TESTING])Bridgewillbelitifconnectedtotherouter,RobotwillbelitifitcancommunicatewiththeroboRIO.FMSshouldbelitifatcompetitionsinceitismandatorytocommunicatewiththeFieldManagementSystem.Ifunlit,youcanhoveroverthemfortroubleshootingtipsinthemessagesbox(SeeMessages&Charts)
➠SetupTab
FRCElectricalBible
51TheInterface
1. Configureyourteam#here,clickontheboxtypeitinandboom
2. PracticetimingcontrolshowlongCountdowntillstartofeachperiod,Autonomous,Teleoperated,andhowlongendgameis.DelayishowmuchtimeisinbetweenAutonomousandTeleoperated.
3. Typeofdashboardyouwanttobringup,defaultautobringsupFRCPCDashboard(ScreenStepsacknowledgesanissuewithsettingDashboardtypetoJavaorC++sotostartuptheSmartDashboardwouldrequiresettingthedefaulttoSmartDashboard),LabviewbringsupFRCPCDashboard,C++andJavashouldbringupSmartDashboard,andremoteisifthedashboardisonaseparatecomputer/device
4. FieldManagementSystemprotocol,protocolforDStoFieldManagementSystemcommunication;shouldbeautosetto‘15whichrequiredfor2015competition.Unlessyouwereparticipatinginweekzeroeventsin2014,thiswon’thavetobetouched
➠USBDevicesTab
1. USBSetuplistholdsallcompatibledeviceshookeduptotheDriverStation(AKA,Laptop,usually2,butwithUSBsplitter,youcanconnectmore)Ifyoupressabuttononaconnecteddevice,itshouldbeprecededbytwoasterisks(**)andhighlightedingreen.TherescanbuttonforcesasearchoforforUSBdevices.Whiledisabled,itautomaticallyupdatesUSBdevices.UsetherescanbuttonorpressF1toforcesearchduringamatch.
Locking&Rearranging
FRCElectricalBible
52TheInterface
1. TorearrangeUSBdevices,drag&drop.Whenyoudrag&dropordoubleclickononeofthedevices,itunderlinesthedevicemeaningitis“locked”Lockeddevicesreservetheslotevenwhiledisconnecteduntilreconnected,representedbygreyedoutandunderlined.
➠Power&CAN
1. AmountoffaultsthatoccurredsincelastconnectiontoDriverstation;CommsmeanDStorobotcommunication,12VisBrownouts(SeeroboRiofordetails),6V/5V/3.3VareUserVoltageRailfaults(typicallyshortcircuits)
2. Utilization%isasitstatesandtheother4aretypesofCANfaultssincelastconnectiontoDriverStation
➠Messages&Charts
FRCElectricalBible
53TheInterface
1. LogsisanindependentbuttonofthetabsonthissectionoftheDS
2. Clearsallmessagescurrentlyinthebox
3. MessageFilter:Fillediniconfiltersoutwarningsfrombeingpostedinmessagebox,Outlinepostseverything
4. Themessagebox,troubleshootingtipsappearhere,messageswillappearhere
Logs
LoadsuptheDSLogFileViewer,youcanviewmessages&eventdatainonedisplay,atoolusuallyusedfortroubleshooting.Thistoolhasitsownsectiontobeaddedelsewhere.
5.Chartstriptimefordatatorobotwithagreenlinevstherightaxis,lostdatapacketstotherobotisin“blue”vstheleftaxis
6.Graphsbatteryvoltagewithayellowlinevstheleftaxis,roboRIOcpu%usagewitharedlinevstherightaxis
7.Timescaleforthetimeaxisofthegraphs(12s,1m,5m)
FRCElectricalBible
54TheInterface
PrintingtoDriverStationWiththe2015updateoftheDriverStation,amaximumof10linesofstrings(eachallowingfor21characters)canbemanipulatedtoprinttotheDriverStationconsole.NotethattheDriverStationLCDClasswasremovedentirely,andnowprintingisdonethroughtheSmartdashboard.
UnliketheDiverStationLCDprintconsole,itispossibletotypedirectlyintothestringfieldsaswellasreadthesestringswithinyourrobotcode.Someteamsmayfindthisusefulwhentestingtheirrobotcode.
StringscanbesenttotheSmartdashboardprintconsoleusingthefollowingcode:
SmartDashboard::PutString("DB/String0","Thisisastring");
SmartDashboard::PutString("DB/String1","Thisisanotherstring");
SmartDashBoard::PutStringiscallingtheSmartdashboardandallowsyoutosendstringstotheDriverStationprintingconsole.EachlineisassignedanamefromDB/String0toDB/String9fromtoptobottomthenlefttoright.Thesecondsetofquotationscanbemanipulatedtosendvariousstrings.
StringsthatareonorweresenttotheSmartdashboardcanthenberetrievedusingthefollowingcode:
std::stringdashData=SmartDashboard::GetString("DB/String0","myDefaultData"
std::stringdashData=SmartDashboard::GetString("DB/String1","myDefaultData"
HerewearecreatingastringwithinthecodecalleddashDatathatissettothestringthatwasinthefirstandsecondlineontheSmartDashboardprinterconsole.
FRCElectricalBible
55PrintingtoDriverStation
FRCElectricalBible
56PrintingtoDriverStation
5.ACrashCourseonC++
5.1Variables
➠DefiningVariables
➠Instantiating
➠Constants
5.2Functions
➠ArithmeticFunctions
➠RelationalOperators
➠LogicalOperators
5.3ObjectUsage
➠DefiningObjects
➠InstantiatingObjects
➠UsingMethods
5.4TheJoystick
➠SampleCode
➠Explanation
FRCElectricalBible
57ACrashCourseonC++
VariablesAvariableisalocationinthecomputer’smemorywhichallowsyoutostoreavaluewhichcanlaterbereceived.Variablesareassignednames,whichallowyoutoquicklyandeasilyaccessthelocationinmemorywherethevariable’sdataisstoredwithouthavingtoknowtheactualmemoryaddress.
Whenyoudefineavariable,youmustalsodeclarethedatatypeofthatvariable.Thedatatypeofthevariabledetermineswhatkindofdatathevariableisholdingaswellashowmuchmemorymustbesetasideforthatvariable.Anexampleofadatatypewouldbeanintegerwhichisdeclaredwiththe‘int’command.Integervariablesstorewholenumbervalues.
Differentdatatypesrequireadifferentamountofmemory,butsincetheuseofC++inthiscompetitiondoesnotrequireyoutoknowthedetailstodatatypememoryitwillnotbereviewedinthissection.
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
➠DefiningVariablesDefiningavariableisveryeasy.Generally,theformatfordefiningavariableisthedatatypefollowedbythenameyouwanttoassignyourvariablefollowedbyasemicolon.
FRCElectricalBible
58Variables
inttheExample;
booliAmAmazing;
Youmustrememberthattherearerulesandguidelinestonamingvariables.Amongprogrammers,thereispropernamingetiquettewhichallowssomeonewhoisreadingyourcodetoeasilyunderstandwhyyounamedavariableacertainway.Hereisalistofrulesandguidelinestofollowtosuccessfullynameavariable:
Rules:
1. Variablenamescanbemadewithanycombinationofletters
2. Variablenamescannotcontainspaces,symbols,orpunctuationmarks
3. Variablenamesmayincludeunderscores
4. Variablenamescannotbeginwithanumberbutmaycontainanumberelsewhereinthename
5. Variablenamescannotbethesameasreservedkeywords.Seebelowtableforacompletelistingofreservedwords.
6. C++iscasesensitivesokeepthisinmindwhilenamingvariables(intmyIntreferstoadifferentlocationthanintMyIntorintmyint)
Guidelines:
1. Constantsareusuallywritteninallcaps
2. Variablesareusuallystartedwithlowercaseandifanamecontainsmorethanoneword,thefirstletterofthenextwordiscapitalized(eg:intthisIsAnExample)
3. Variablesshouldbenamedsomethingthedescribeswhatthevariableisgoingtobeusedfor
4. Avoidgivingvariableslongnames,itisokaytoabbreviatelongwords
ReservedWords(C++)
alignas(sinceC++11)
alignof(sinceC++11)
and
and_eq
asm
auto(changedinc++11)
bitand
FRCElectricalBible
59Variables
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
FRCElectricalBible
60Variables
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
FRCElectricalBible
61Variables
BelowisanexampleofhowtodefinevariablesintheC++language:
main()
{
inta;
intohMyLord;
charmyChar;
}
Todefinemorethanonevariableofthesamedatatype,youcanusethecommapunctuation.
main()
{
inta,b,c;
charohMahGlob,lumpySpacePrincess,partyTime;
booldownLieToMe,cats;
}
➠InstantiatingInstantiatingavariableisalsoknownasassigningavariablewithavalue.Theoperatorusedtoassignvaluestoavariableistheequalssign,(=).
Thevariablethatthedataisbeingassignedtoisalwaysontheleftside,whilethedatathatisbeingassignedtothevariableisontheright.Itisimportanttonotmixthisupbecausevariablescanalsobeassignedvaluesfromsimilarvariabletypes.Thisiscommonwhileusingmathfunctionswithothervariables.
main()
{
inta=5;
intb=10;
intc=a;
charcharacter=‘A’;
boolcounter=true;
}
➠Constants
FRCElectricalBible
62Variables
Sometimesinprogramming,wehavevariableswithdatathatwedonotwanttochangeatall.Althoughyoucouldeasilyjustnotchangethevariabledata,itissafertodeclareaconstantvariable.Aconstantvariableisavariablethatcannotbechangedonceitisinstantiated.
main()
{
constintTHIS_IS_A_CONSTANT=100;
}
FRCElectricalBible
63Variables
FunctionsInC++,therearebasicallythreetypesoffunctions:arithmeticfunctions,relationalfunctions,andlogicalfunctions.
➠ArithmeticFunctions
Thesetypesoffunctionsareyourbasicmathfunctionsandareusedinconjunctionwithnumericdatavaluesandvariables(int,double,float).Itisimportanttorememberthatorderofoperationsdoesapplytothesefunctions.
Youshouldbeabletorecognizethesefunctionsasyouhaveusedthemsinceelementaryschool.Theonlyonethatyoumaynotbefamiliarwithisthemodulusfunction,whichdividestwonumberstogetherandreturnstheremainder.Thisfunctioniscommonlyusedintrue-falsestatementsorloopstorecognizewhenanumericalvariablebeinganalyzedispositiveornegativeoramultipleofacertainnumber.Parenthesesareusedlikeinalgebratosaywhichoperationsshouldbedonefirstifthoseactionsdifferfromthedefaultorderofoperations.
Inprogramming,itisalsoquiteoftentousevariablesinconjunctionwitharithmeticfunctions.Tousevariablesinthisway,allyouneedtodoisusethevariable’sdefinednamewherenumberswouldusuallybeused.It’sthesameasbasicalgebra.
Sign Meaning
+ Addition
- Subtraction
/ Division
* Multiplication
% Modulus
= AssignmentOperator
(operatorhere) Parenthesis(orderofoperation)
++/-- Increment/decrementnumericvalueby1
FRCElectricalBible
64Functions
main()
{
inta=5;
intb=10;
intc=a+b;
intd=c*a;
inte=a(3+b);
intf=b%2;
a++;
}
intaisassignedthevalue5andintbisassignedthevalue10.intc,isthesumofaandb.Becauseaandbareassignedthevalue5and10,respectively,ciscurrentlyatavalue15.Itcanbesubjecttochangeintheeventthevaluesaandbchange.intdistheproductofcanda,(15*5).inteistheproductofaandthesumof3+b.intfistheremainderofbdividedby2(itwillreturnavalueofeither0or1).
➠RelationalOperatorsRelationaloperatorsareusedtodeterminewhethertwonumbersareequal,orwhetheroneisgreaterorlessthantheother.Everyrelationalexpressionreturnseither1(true)or0(false).Theseoperatorsareusedinstatements(if,else,while)inordertocreateexpressionsthatsetconditionsforthatcodeinsidethestatement.Besurenottoconfusetheassignmentoperator(=)withtherelationoperatorofequality(==).
FRCElectricalBible
65Functions
Name Operator Sample Evaluation
Equals == 100==50; false
50==50; true
NotEquals != 100!=50; true
50!=50; false
Greaterthan > 100>50; true
50>50; false
Greaterthanorequals >= 100>=40; true
50>=50; true
Lessthan < 100<50 false
50<50; false
Lessthanorequals <= 100<=50 false
50<=50 true
➠LogicalOperatorsLogicaloperatorsareusedinconjunctionwithrelationaloperatorstocreatemorecomplexstatementexpressions.
OPERATOR SYMBOL EXAMPLE
AND && 2:2
OR (2pipes) 2:3
NOT ! 2:4
AlogicalANDstatementevaluatestwoexpressions,andifbothexpressionsaretrue,thelogicalANDstatementistrueaswell.
AlogicalORstatementalsoevaluatestwoexpressions.Ifeitherorbotharetrue,theentireexpressionistrue.
ANOTstatementcompareswhetheraconditionisNOTwhatisstated(i.e.switchesthereturnvaluefromtruetofalseandviceversa).
Whenusinglogicaloperatorstoformstatements,makesureyouuseparenthesestomaketheorderofprecedenceclearertothecompilertoavoidanyerrors.Forexample,
if(x>5&&y>5||z>5)
FRCElectricalBible
66Functions
Thisstatementgoestoshowhowambiguousthesestatementscangetifparenthesesarenotused.Doyouwantthestatementtoreturntrueifx>5andy>5orwhenjustz>5,ordidyouwantthestatementtoreturntruewhenx>5andwheneithery>5orz>5?Ifyouwantedthelatter,thenyoushouldrewritethestatementtomakethingsclearer:
if((x>5&&y>5)||z>5)
FRCElectricalBible
67Functions
ObjectUsageInobject-orientedprograms(OOP),objectsarebasicallyobjectslikethatoftherealworld,andthushavecertainbehaviorsandcharacteristics.CharacteristicsofanobjectinOOPincludeanyvariablesorotherobjectsthataredeclaredintheclassthattheobjectiswrittenin.Behaviorsofanobjectaremethodsthattheobjectcontainsinitsclasscode.
WewillusetheJaguarclassfromtheWPIlibrarytohelpexplainthissection.Clickheretoviewit.
➠DefiningObjectsDefiningobjectsisasimilartodefiningvariables,butinsteadthedatatypeisreplacedbythenameoftheobject.Aftertheobjectnamecomesthenamethatyouassigntotheaddresslocationoftheobject.IntermsoftheJaguarclass,aJaguarobjectisdefinedas:
Jaguarjag1;
Jaguarjag2;
Jaguarexample;
RememberthateachJaguarobjectthatyoucreateisadifferentinstanceoftheobjectandthatdifferentspacesinmemoryarecreatedforinstancevariablesofeachJaguarobject.ThenameyougavetoaJaguarobjectistheonlythingyouhavetodistinguishbetweenJaguars.
➠InstantiatingObjectsInstantiatinganobjectisquitedifferentfromdefiningavariable.Wheninstantiatinganobject,youmustusethenewoperator.Followedbythenewoperatoristheobject’sconstructorsignature.Anobject’sconstructorsignaturemaylooklikethis:
Jaguar(UINT32channel)
Asyoucanseetheobjectnameisdisplayedalongwithsomecodeinsideparentheses.Thecodeinsidetheparenthesesiscalledaparameter.Parametersarewhereyoupassdataintotheobjectsothattheobjectcanuseit.Noticethatdatainparametersareseparatedbycommas.Intheabovecase,theobjectconstructorasksyoutoinputafloatandachannelnumber.Soanexampleinstantiationwouldlooksomethinglikethefollowing:
FRCElectricalBible
68ObjectUsage
jag1(1)
Where1isthenumberofaUINT32channel(thePWMOUTportthejaguaroccupiesonthedigitalsidecar).
Objectclassesoftenhavemultipleconstructorswhichaskfordifferentsetsofparameters.InthecaseoftheSolenoidclass,herearethefollowingconstructorsforaSolenoidobject.
Solenoid(uint32_tchannel)//ConstructorusingthedefaultPCMID
Solenoid(uint8_tmoduleNumber,uint32_tchannel)//ConstructorthatspecifiesthePCMID.
Youshouldseethattheonlythingdifferentistheparametersthatmustbecalled.ThefirstcallsforthePCMchannelonly(assumesthePCMIDas0).Tocallthefirstconstructorafterdefiningsol1,youwouldtype:
sol1(1)
whichmeanssol1isassignedtoPWMport1onthePCMandisautomaticallyassumedtobeonthePCMIDof0.
BecausetheroboRIOcansupportmorethanonePCM,anythingconnectedaPCMwithanIDthatisnot0willneedtousethesecondconstructor.
➠UsingMethodsInprogramming,objectsalonedonomorethantheydoinreality.Simplystating“theJaguarexists!”willnotmakeyourrobotmove,norwillmerelydeclaringitinyourcodemakeanythinghappen.
Therealworkisdonethroughmethods,auniquesetofcommandsthateachobjecthas.Thesearenotedbya.afterthenameofaparticularobjectandarealwaysfollowedby(),thoughoftentherearesomevaluespassedintotheparentheses.IntheJaguarclass,forexample,onemightseethefollowingcodefragment:
jag1.Set(0.5);
Thenameoftheobjectisjag1,whichhaspreviouslybeendeclaredtobeaJaguar.ThemethodisSet,which,asonemightexpect,setsthespeedofthemotor.The0.5insidetheparenthesesiscalledtheparameter,whichvariesdependingonthemethodused.Here,
FRCElectricalBible
69ObjectUsage
itisafloatvaluefrom-1to1,inclusive,butoftenyoumustpassanint,bool,orevenanotherobjectasaparameter.Forobject-specificinformationonmethodsandparameters,seethesectiononthatparticularobjectorusetheWPILibrary.
Notethatjustaseachobjectwillhavemultiplemethods,differentobjectscanhavemethodsofthesamenameandmayormaynotdodifferentthings.TheVictorclass,forexample,alsohasaSetmethodthatfunctionsexactlythesame,buttheRelayclasstakesanentirelydifferentdatatypeandfunctionspurelyasanon/offswitch.
FRCElectricalBible
70ObjectUsage
TheJoystickLogitechGamepadF310
Logitechhasmadeahome-touch-feelycontrollerasitappearstobeastandardcontroller.Mostpeoplehaveplayedvideogameswithacontrollerlikethis,sothere’snothingnewtolearnaboutit.Onthebackisalittleslidebutton,makesureitissettotherightandtapeitlikethattopreventincidentsofbadjoystick.Makesuremodelightisoff.
AndyMark
FRCElectricalBible
71TheJoystick
LogitechAttack3USBJoystick
ThisAttack3Joysticklooksawesome,doesn’titexudethefeelingofrobotics?Onehandtomovethesinglejoystick,theothertopressthebuttonsonthebottom.ThejoystickclassintheWPILibrarydoessupportthisjoystickandallifitsmanyinputs.
FIRSTChoice
JoystickClass(C++)
➠SampleCode
FRCElectricalBible
72TheJoystick
#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);
FRCElectricalBible
73TheJoystick
➠Explanation
Joystickstick;
DeclareoneJoystickobject.DeclaredbetweenclassRobotDemo:publicSampleRobotandpublic:RobotDemo(void):
stick(0);
InstantiateoneJoystickobjectinUSBportofcomputer(limitedto#ofUSBportsoncomputer).Instantiationoccursbetweenthepublic:RobotDemo(void):andthebraces({}).Ifnotthelastinstantiatedobjectinlist,itneedsacommaafterinstantiationstatementlikelisting.Ifitis,itdoesnotneedanypunctuationaftertheinstantiationbeforethebraces;nocomma,nosemicolon,noperiod,etc.Ifsyntaxnotfollowed,erroroccurs.
FRCElectricalBible
74TheJoystick
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))
{
}
}
}
}
JoystickfunctionsarethesauceforconditionsinOperatorControl.Bydoingcertainactionsonthejoystickobject(thisinstanceisusingaLogitechF310Gamepad),itexecutesthecodethatwouldbewritteninthebraces.Forexample,GetRawAxis(1)correspondstotheleftsticky-axis(upanddown)oftheF310Gamepadorthey-axisoftheExtreme3DProjoystick;the||(or)correspondstopositive(up)ornegative(down)input.Theaxisisusuallyassociatedwithdrivingtherobot.GetRawButton()onlyreturns1ifitisbeingpressed;GetRawButton(1)isthex-buttonontheF310GamepadorthetriggeroftheExtreme3DProjoystick.GetTopisthesmallerstickontheExtreme3DPro,anditonlyreturns1iftopisbeingusedor0ifnot,soextraconditionsforaxis3&4,y-axisandx-axisoftoprespectively.FortheF310Gamepaditwouldbeaxis6&5,y-axisandx-axisrespectively.
FRCElectricalBible
75TheJoystick
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
FRCElectricalBible
76MotorControllers
6.9Fans
FRCElectricalBible
77MotorControllers
GeneralOverviewMotorcontrollersarewhattheysoundlike;theyallowustocontroltheamountofpowersenttothemotor.TheyserveasthemiddlemenfromthePDBtothemotoritself.
FRCElectricalBible
78GeneralOverview
Motors
CIMmotor
PhysicalSpecs
Size:2.5inchdiameter,4.34inchlongbodyOutputShaftsize:0.313+/-0.0004,with2mmkeywayWeight:2.82poundsMountingHoles:#10-32tappedholes(2),ona2"boltcircle
Performance
Voltage:12voltDCNoloadRPM:5,310(+/-10%)FreeCurrent:2.7ampsMaximumPower:337Watts(at2655rpm,172oz-in,and68amps)StallTorque:2.42N-m,or343.4oz-inStallCurrent:133amps
AndyMark
mini-CIMmotor
FRCElectricalBible
79Motors
⅔powerofCIM,similarformfactorandsamemounting
PhysicalSpecs
OutputShaftsize:8mm(0.314in)with2mmkeywaySize:2.5”diameter,3.36”longWeight:2.16lbs
Performance
FreeSpeed:6,200rpm(+/-10%)FreeCurrent:1.5AMaximumPower:230WStallTorque:12.4in-lbs[1.4N-m]StallCurrent:86AMountingHoles:(4)#10-32tappedholesona2"boltcircle
Vex
WindowMotor
FRCElectricalBible
80Motors
Makesureyouremovethelockingpins.
StallTorque:9.3NmFreeSpeed:92RPMFreeCurrent:2.5AStallCurrent:25A
Servo
ShouldnotbehookeduptoANYmotorcontrollersanddirectlytothePWMportintheroboRIO.
AndyMark
➠MotorControllerVarieties
FRCElectricalBible
81Motors
Itispossibletocontrolallthemotorsabove(excepttheservo)withthebelowmotorcontrollers;however,thebreakersusedhavetobeabletoprotectthewiresandprovideenoughpowerforthemotorused.Forexample,itispossibletoconnect16gaugewirewitha20ampCBtoatalon,butwouldnotprovideenoughpowerifconnectedtosayaCIM.Therearetwosidewiresthatconnecttoeachmotorcontroller:theM-/M+andtheV-/V+side.The‘M’standsforMotor,whichdenotesthewiresattachedhereshouldbetheonesalsoattachedtothemotor.TheothersideconnectstothePDB.Inbothcases,thepowergoestothe+andgroundtothe-.ThereisalsoathinslotwherePWMcablesplugintofromtheDigitalSidecar,withitsdirectionbasedonthesmallnotationsonthemotorcontrollers(often,groundisfacingthesidemarkedwitha‘B’).
FRCElectricalBible
82Motors
Jaguar
Therearejumpersthatcanbeusedintwoplaces,themotorcoast/brake,andtheLimitSwitches.Themotorcoast/brakecontrolsifaftertherobotstopsitslowlydecelerates(coasts),orimmediatelydecelerates(brakes).Thejumpersaretobeinstalledinthelimitswitchareaiftherearenolimitswitchesbeingused.JaguarsusetheCANnetworkfolder.ThestatusLEDindicatesmanythingslikeoperation,fault,calibration,andotherconditionsusingyellow,red,andgreenlights.
FRCElectricalBible
83Jaguar
FRCElectricalBible
84Jaguar
➠SampleCode
JaguarClass(C++)
FRCElectricalBible
85Jaguar
#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;
DeclareJaguarmotorcontrollerasjaguar;declaredbetweenpublicSampleRobotandpublic:RobotDemo
jaguar(1),
FRCElectricalBible
86Jaguar
InitializeJaguarmotorcontrollerasport#1inDigitalSidecar(PWMOut),initializedbetweenpublic:RobotDemoandthebraces({}).Ifitisnotthelastobjectinitialized,itneedsacommalikealist.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.Motorcontrollersareputintoresultsofconditionsbecauseafree-spinningmotorisawasteofpowerandthereisnocontroloverthemotor(whichiswhyitisamotorcontroller)The.Setmethodoftheclassacceptsafloatbetween-1.0to1.0asaparameterandsetsthespeedofthemotortothatfloat.1.0isfullspeed“forward”,-1.0isfullspeed“backward.”Themotorwheninitializedbeginsat.Set(0).Theelsejaguar.Set(0)istostopthemotorbecauseunlessthemotorcontrollerissetto0,themotorremainsatthelast.Set()value.
FRCElectricalBible
87Jaguar
Victor888
Thevictorissimilartothejaguar,butsacrificescomputingpowerforalighterweightandasmallersize.
FRCElectricalBible
88Victor888
Whenwiring,makesurethatthePWMispluggedinsothattheblackwireisfacingtheinside(towardsthefan).PayspecialattentiontotheM+M-V+andV-onthesidesoftheVictorwhenwiringittothemotorandthepowerdistributionboard.
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
FRCElectricalBible
89Victor888
Victorvictor;
Declarevictormotorcontrollerasvictor;declaredbetweenpublicSampleRobotandpublic:RobotDemo
victor(1),
Initializevictormotorcontrollerasport#1inDigitalsidecarPWMOut.Thisisstatedbetweenpublic:RobotDemoandthebraces({}).Ifitisnotthelastobjectinitialized,itneedsacommalikealist.Ifitisthelastobjectinitialized,nopunctuation;nocomma,nosemicolon,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.Motorcontrollersareputintoresultsofconditionsbecauseafree-spinningmotorisawasteofpowerandthereisnocontroloverthemotor(whichiswhyitisamotorcontroller)The.Setmethodoftheclassacceptsafloatbetween-1.0to1.0asaparameterwhichsetsthespeedofthemotortothatfloat.1.0isfullspeed“forward”,-1.0isfullspeed“backward.”Themotorwheninitializedbeginsat.Set(0).Theelsevictor.Set(0)istostopthemotor;unlessthemotorcontrollerissetto0,themotorremainsatthelast.Set()value.
NOTE:The883,884and885modelshavebeendiscontinued,butthemanufacturer’sdocumentationcanbefoundbelow.
Victor883/885UserManual
Victor884UserManual
FRCElectricalBible
90Victor888
Talon
Thetalonisinterchangeablewiththejaguar.Ithasapeakoutputof100Aand60Acontinuouscurrent.Therearemountingholesforanoptional40mmfan.TheLEDonthetalonisastatusindicator.
TalonUserManual
➠SampleCode
FRCElectricalBible
91Talon
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;
Declaretalonmotorcontrollerastalon;declaredbetweenclass:SampleRobotandpublic:RobotDemo.
talon(1),
FRCElectricalBible
92Talon
Initializetalonmotorcontrollerasconnectedtoport#1intheDigitalSidecar(PWMOut);initializedbetweenpublic:RobotDemoandthebraces({}).Ifitisnotthelastobjectinitialized,itneedsacommalikealist.Ifitisthelastobjectinitialized,nopunctuation;nocomma,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.Motorcontrollersareputintoresultsofconditionsbecauseafree-spinningmotorisawasteofpowerandthereisnocontroloverthemotor(whichiswhyitisamotorcontroller)The.Setmethodoftheclassacceptsafloatbetween-1.0to1.0asaparameterwhichsetsthespeedofthemotortothatfloat.1.0isfullspeed“forward”,-1.0isfullspeed“backward.”Themotorwheninitializedbeginsat.Set(0).Theelsetalon.Set(0)istostopthemotor;unlessthemotorcontrollerissetto0,themotorremainsatthelast.Set()value.
FRCElectricalBible
93Talon
TalonSRX
TheTalonSRXisanewiterationoftheTalonmotorcontrollerseriesthatwasintroducedinthe2015FRCseason.TheSRXisuniqueasitisCANenabledandcapableofoperatingwiththeroboRIO,PCM,andVRM,whichalluseCANprotocols.BecausetheTalonSRXwasdesignedwithoutabuilt-inventilationsystem,youshouldmountitinanareawithadequateairflow.Theuserguiderecommendsmountingittotherobot’smetalframebecauseitwillactlikeagiantheatsink.
Specs
Dimensions:2.75”x1.85”x.96”tallWeight:.2lbsincludingwires15kHzoutputswitchingfrequency60AmpContinuouscurrent,100Amp2xMountingHoles(oneateachend,6-32fasteners)SupportsCAN(ControllerAreaNetwork),SPI(SerialPeripheralInterface),DigitalI/O,andUSART(UniversalSynchronous/AsynchronousReceiver/Transmitter)
➠Wiring
FRCElectricalBible
94TalonSRX
➠Can
FRCElectricalBible
95TalonSRX
TalonSRXUserManual
➠SampleCode
TalonSRXClass(C++)
FRCElectricalBible
96TalonSRX
#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;
DeclareTalonSRXmotorcontrollerastalon;declaredbetweenpublicSampleRobotandpublic:RobotDemo
talonsrx(1),
InitializetalonSRXmotorcontrollerasconnectedtoport#1intheDigitalSidecar(PWMOut);initializedbetweenpublic:RobotDemoandthebraces({}).Ifitisnotthelastobjectinitialized,itneedsacommalikealist.Ifitisthelastobjectinitialized,nopunctuation;nocomma,nosemicolon,noperiod,etc.oryouwillgetanerror.
FRCElectricalBible
97TalonSRX
voidOperatorControl(){
if(stick.GetRawButton(1)){
talonsrx.Set(1.0);
}
elseif(stick.GetRawButton(2)){
talonsrx.Set(-1.0);
}
else{
talonsrx.Set(0);
}
}
Joystickclassisgoneintodepthinanearliersectionofthismanual.Motorcontrollersareputintoresultsofconditionsbecauseafree-spinningmotorisawasteofpowerandthereisnocontroloverthemotor(whichiswhyitisamotorcontroller)The.Setmethodoftheclassacceptsafloatbetween-1.0to1.0asaparameterwhichsetsthespeedofthemotortothatfloat.1.0isfullspeed“forward”,-1.0isfullspeed“backward.”Themotorwheninitializedbeginsat.Set(0).Theelsetalonsrx.Set(0)istostopthemotor;unlessthemotorcontrollerissetto0,themotorremainsatthelast.Set()value.
FRCElectricalBible
98TalonSRX
Spike
BindicatesthatthegroundsideofthePWMfacesinward
Spikesaremotorcontrollersusedindrivingsmallmotorsinforward,reverse,orstop(brake).Itusesa20Acircuitbreaker.Itcanalsobewiredtocompressorsandsolenoidsanditsindicatorlightsaredifferentformotorsandsolenoids,asshowninthetablebelow.
FRCElectricalBible
99Spike
SpikeUserManual
➠SampleCode
RelayClass(C++)
FRCElectricalBible
100Spike
#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;
Declarespikerelayasnamespikeblue.ThedeclarationoccursbetweenclassRobotDemo:publicSampleRobotandpublic:RobotDemo():
FRCElectricalBible
101Spike
spikeblue(1,Relay::kForward),
Instantiatethespikerelaywiththeparameters[DigitalSidecarPort#],[directionofcurrent[kForward,kBackward,orkBothDirections]]Thisisinstantiatedbetweenpublic:RobotDemo():andthebraces({}).Ifitisnotthelastobjectinitialized,itneedsacommalikealist.Ifitisthelastobjectinitialized,nopunctuation;nocomma,nosemicolon,noperiod,etc.oryouwillgetanerror.
voidAutonomous(){
spikeblue.Set(Relay::kOn);
}
voidOperatorControl(){
while(IsOperatorControl()){
if(stick.GetRawButton(1)){
spikeblue.Set(Relay::kOn);
}
else{
spikeblue.Set(Relay::kOff);
}
}
}
TheJoystickclasshasalreadybeencoveredinaprevioussectionofthemanual.Controlscurrenttowhateverisontheothersideofthespike(onesideconnectedtothePDB).Inautonomous,ifthereissomethingwiredtothespikethatneedstobeturnedon,itcanbeSet(Relay::kOn).Toturnitoff,useSet(Relay::kOff).Notethatitwillnotshutoffautomaticallyandhencemanualoffcommand.InOperatorControl,therelaywilloftenbeinsertedinsidecontrolstatementstopreventlooserelayon/off.Usuallyturningitonifbuttonsetinifconditionispressedotherwiserelayoff.Orviceversaifneedbe.
FRCElectricalBible
102Spike
Fans
Beforethepedanticcommentregardingourtableofcontents,no,fansarenotmotorcontrollers.Theyare,however,securedontopofmotorcontrollerstocoolthemdown;beingfansandall.TalonsandVictorshavemountingholesthatrequire6-32inchscrews.TheterminalsconnecttotheV+/-sideonthemotorcontroller(youdon’twantyourfansturningoffandoninunisonwithyourmotors).
FRCElectricalBible
103Fans
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
FRCElectricalBible
104DriveCode
BoxonWheelsYouhavenowopenedupabarebonestemplatetowriteyourrobotcode;congratulationsyou’vemadeaboxonwheels,nowtounderstandwhatyou’reboxonwheelsdoes,beforeyoudestroyitandcreateyourowncompletelyimprovedcode.Itisnecessarytounderstandtheclassesthatcreatedthisboxonwheelssoyouknowthatyoujustdidn’tcreateanotherboxonwheelsprogram,butitisagoodstart.
➠TheCodeThedriveprograminit’sentirety:
#include“WPILib.h”
//Lastmodified:January19,2014by:Alan
/*
ThisisademoprogramshowingtheuseoftheRobotBaseclass.TheSampleRobotclassisthebaseofarobotapplicationthatwillautomaticallycallyour
AutonomousandOperatorControlmethodsattherighttimeascontrolledbytheswitchesonthedriverstationorthefieldcontrols.
*/
classRobotDemo:publicSampleRobot{
RobotDrivemyRobot;//robotdrivesystem
Joystickstick;//onlyjoystick
public:
RobotDemo(void):
myRobot(1,2),//thesemustbeinitializedinthesameorder
stick(1)//astheyaredeclaredabove.
{
myRobot.SetExpiration(0.1),//youcaninitializethingsherelikegyrosatconstruction
}
//Driveleft&rightmotorsfor2secondsthenstop
voidAutonomous(void){
myRobot.SetSafetyEnabled(false);
myRobot.Drive(0.5,0.5);//driveforwardathalfspeed
Wait(2);//for2seconds
myRobot.Drive(0.0,0.0);//stoprobot
}
FRCElectricalBible
105BoxonWheels
//Runsthemotorswitharcadesteering
voidOperatorControl(void){
myRobot.SetSafetyEnabled(true);
while(IsOperatorControl())
{
myRobot.ArcadeDrive(stick);//drivewitharcadestyle(userightstick)
Wait(0.005);//waitforamotorupdatetime
}
}
//Runsduringtestmode
voidTest(){
}
};
START_ROBOT_CLASS(RobotDemo);
➠TheExplanationBreakdownofthecodefollowsasso:
#include“WPILib.h”
ThisincludingoftheWPILibraryistheinclusionofaspellbookforalmosteveryclassneededfortherobot:motors,pneumatics,Axiscameras,etc.NOTE:Therewillstillbemuchtimespentusingthe“WPILibC++Reference”,buttheuseofthebasicmanualreducesmostofthetimespentbypresentingsample/properusagesothelearningprocessdoesnotneedtorepeatitselfandtimecanbebestallocatedelsewhere.
/*
ThisisademoprogramshowingtheuseoftheRobotBaseclass.TheSampleRobotclassisthebaseofarobotapplicationthatwillautomaticallycallyour
AutonomousandOperatorControlmethodsattherighttimeascontrolledbytheswitchesonthedriverstationorthefieldcontrols.
*/
Ifyou’vecommentedinprogramming,thenyouknowwhatyoushouldbedoing,ifyouarelazyandhavesomepersonalbeliefordogmathat,“Toughbeans,figureoutmygiantprogram,”youareimpedingtheprogressofyoursubteamandyouareabsolutelyterrible.
FRCElectricalBible
106BoxonWheels
However,ifyou’rejustinthemoodandhavestartedaprogram,commentwhatneedstobeunderstoodbecauseyouneverknowwhenyoumightbegonethenextdayandsomeoneelsehastorunyourprogram.
classRobotDemo:publicSampleRobot
Thisisyourphysicalrobot,RobotDemoisthenameoftheclass,SampleRobotisthe
{
RobotDrivemyRobot;//robotdrivesystem
Joystickstick;//onlyjoystick
Declarationoftherobotsparts,RobotDriveisasimplifieddrivesystemclassthatdeclaresmotorsforyouandhaspreprogrammeddrivefunctions;Joystickalsodeclaredlastbecauseitisapartoftherobot,buthowelseareyougoingtocontrolit?Withyourmind?ITHINKNOT!
public:
RobotDemo(void):
myRobot(1,2),//thesemustbeinitializedinthesameorder
stick(1)//astheyaredeclaredabove.
{
myRobot.SetExpiration(0.1),//youcaninitializethingsherelikegyrosatconstruction
}
RobotDemoistheconstructorofyourrobot,itwillnowinitializewhatyoudeclaredpreviouslyasportsinthesidecarformostofthedeclaredobjects,withtheexceptionofthejoystick.Asnoted,RobotDemohasthesamenameastheclassbecauseofhowobjectswork,anditisvoid,butyoudon’thavetoputvoidasinC++itautomaticallyassumesvoid.Thepairofbracesafteryouinstantiatetheportsofyourcontrollersallowsyoutoinitialize/runcommands(likesensors)attheverybeginning.
FRCElectricalBible
107BoxonWheels
//Driveleft&rightmotorsfor2secondsthenstop
voidAutonomous(void){
myRobot.SetSafetyEnabled(false);
myRobot.Drive(0.5,0.5);//driveforwardathalfspeed
Wait(2);//for2seconds
myRobot.Drive(0.0,0.0);//stoprobot
}
ThisistheAutonomousmethodoftheRobotDemoclass,anditwasinheritedfromSampleRobot.ItwillonlyrunduringtheAutonomousperiodofthegame.SetSafetyEnabledistoprotecteveryoneincaseoflossofcommunicationorotherproblemswhensettotrueinthe().Drivesetsthespeedofthemotorsintheorderinitializedrespectively,fromavalueof(-1.0to1.0).Waitisamethodthatstopstheprogramfromreadinganyfurtherlinesforthetimespecifiedinthe()inseconds.Tostoptherobot,themotorsafterbeingsettomovemustbesetbacktozero.
//Runsthemotorswitharcadesteering
voidOperatorControl(void){
myRobot.SetSafetyEnabled(true);
while(IsOperatorControl()){
myRobot.ArcadeDrive(stick);//drivewitharcadestyle(userightstick)
Wait(0.005);//waitforamotorupdatetime
}
}
OperatorControlisamethodoftheRobotDemoclass,thismethodwasalsoinheritedfromSampleRobot.Thisiswherethecodeforyourtele-opordrivercontrolperiodgoes.SetSafetyEnabledwasalreadymentioned,butasareminder,it’sforthesafetyofallothersandtherobotincaseofcommunicationproblemswiththerobot.Thewhileloopistheretomakesurethatyouarealwaysincontrolduringtheperiod,withouttheloop,thecodewouldonlyrunonceandyourrobotwouldthenbecomeastationerybox.ArcadeDriveisthetypeofdriveusingarcadejoystick,therobotwillmoveaccordingtothejoystickinput.
//Runsduringtestmode
voidTest(){
}
FRCElectricalBible
108BoxonWheels
Thisiswhereyouwouldinputtestcodethatyouwouldn’tputintoeitherAutonomousorTele-opwithoutbeingsureitwouldworkfirstorifitwouldconflictwithotherpartsofthecodeinsidethosemethods.
};
START_ROBOT_CLASS(RobotDemo);
START_ROBOT_CLASSsetsupa"userclassfactory",whichisafunctionthatreturnsapointernewinstanceofyourrobotclass.Italsocreatestheentrypointfunction,FRC_UserProgram_StartupLibraryInit.
FRCElectricalBible
109BoxonWheels
BoxonWheelsTemplatevsCustomProgramWhileBoxonWheelsTemplateisalreadymade,thereisnotalotofroomtoeditthisdrivecodeunlessyouareusingtwoLogitechExtreme3DProUSBJoysticks.IfyousearchintheWPILibReferenceforRobotDrive,theconstructorsanddrivemethodsaredesignedforsomethingliketheabove.Alsoyourchoicesof#ofmotorsfordriveisonlyeither2or4.IfyouwishtouseaLogitechF310Gamepad,youarebetteroffwritingyourowndrivecode.WhenImeancustom,deletetheunnecessarypartsofthetemplatethatwouldbenotconducivetothewordcustom.Belowisbarebonescodethatyoumaymodifytomeetyourowndesires.
➠TheCode
FRCElectricalBible
110BoxonWheelsTemplatevsCustomProgram
#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);
➠TheExplanationHere’sapancakesandwichwithsprinkles.
#include"WPILib.h"
Thisisyourspellbook.Liveit,breatheit.
classRobotDemo:publicSampleRobot
TheRobotDemoclass+SampleRobotfromthetemplategivesyoutheinheritedmethodstouseintheDriverStation,willneedit
FRCElectricalBible
111BoxonWheelsTemplatevsCustomProgram
Joystickstick;
Youwillalwaysneedajoystick,again,unlessyoucancontrolyourrobotwithyourmind,oritiscompletelyautonomous,makethejoystick.
public:
RobotDemo(void):
stick(1)
{
}
Instantiatethestick,youcan’tuseitifyoudon’tinstantiateit.Thebraceshavetobethere,partofthecompiling.Whenyoustartaddinginmotorsandsensors,theirexpirations/initializationwillbesetinthosebraces.
voidAutonomous(void){
}
Stillneedautonomoussection,partoftheinheritance.Ifyouuseitornotisuptothatyear’sgame,butyoustillneedthis!
voidOperatorControl(void){
while(IsOperatorControl()){
Wait(0.005);//waitforamotorupdatetime
}
}
Thisiswhereyouwritethegodcode,whereyouletyourdriverfeellikeakingmovingtherobot...withyourcode:DMakesurethecodethatwillletthedriverexecutecommandsisinthewhileloop,wouldn’titsuckthattheycanonlydoitoncebecauseitwasnotintheloop?Beforetheloopiswhenyoucaninstantiatespecificthingssuchastheresolutionofanaxiscamera.
voidTest(){
}
Testingspaceforsmallportionsofquestionablecode.Alsopartofinheritance,required.
FRCElectricalBible
112BoxonWheelsTemplatevsCustomProgram
};
START_ROBOT_CLASS(RobotDemo);
Closesbracefromthebeginningoftheclass.START_ROBOT_CLASS(RobotDemo);noticehowRobotDemoisintheparameter,isn’tthattheclass?Sothisisalsoimportantforitrunstheclass.
FRCElectricalBible
113BoxonWheelsTemplatevsCustomProgram
CustomProgram(TankDrive)AnexampleofwherethedriverusestheLogitechF310Gamepad,butbecauseofthewaytheRobotDriveclassismade,itispreferabletomakeone’sowncode.
➠TheCode
#include"WPILib.h"//WPILibrary.h
#include"Math.h"//Math.hrequiredforfabsfunction
//Lastmodified:January30,2014by:Alan
classRobotDemo:publicSampleRobot{
TalonfrontLeft,frontRight,backLeft,backRight;//TalonMotorControllers
Joysticklogitech;//LogitechF310Gamepad/Controller
public:
RobotDemo(void):
frontLeft(1),
frontRight(2),
backLeft(3),
backRight(4),
logitech(1)
/*
*Setmotorexpirationtopreventunwarrantedmovementifconnectionlostor
*disabled
*/
{
frontLeft.SetExpiration(0.1),
frontRight.SetExpiration(0.1),
backLeft.SetExpiration(0.1),
backRight.SetExpiration(0.1);
}
voidAutonomous(void){
}
/**
*Runsthemotorswithtanksteering
*/
FRCElectricalBible
114CustomProgram(TankDrive)
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
FRCElectricalBible
115CustomProgram(TankDrive)
WPILib.hisalwaysourspellbook.Math.hisadifferentlibrarythatisgenerallyusedinC++formathfunctions.Asstatedinthecomment,itisusedforthefabs(floatabsolutevalue)functionthatappearsinthetankdriveportionofthiscode.
classRobotDemo:publicSampleRobot
{
TalonfrontLeft,frontRight,backLeft,backRight;//TalonMotorControllers
Joysticklogitech;//LogitechF310Gamepad/Controller
RobotDemoclasswithinheritedmethodsfromSampleRobotmakestemplatingeasier.Thetalonsareoneofseveralmotorcontrollersexplainedinanearliersectionofthismanual.RobotDriveintheoriginaltemplatedeclarestheminthebackground,butthenyouarelimitedtoit’sdrivemethods.Thiscustomprogramusesalogitechgamepadwhichisonejoystickobject.IfyoulookintheWPILibreference,itwillshowthattousethetankdrivemethodoftheRobotDrive,youneedtwojoysticks.
public:
RobotDemo(void):
frontLeft(1),
frontRight(2),
backLeft(3),
backRight(4),
logitech(1)
//Setmotorexpirationtopreventunwarrantedmovementifconnectionlostordisabled
{
frontLeft.SetExpiration(0.1),
frontRight.SetExpiration(0.1),
backLeft.SetExpiration(0.1),
backRight.SetExpiration(0.1);
}
Nowintheconstructor,themotorcontrollersareinstantiatedintheportsofthedigitalsidecarcorrespondingtothenumberintheparentheses.ThejoystickisinstantiatedusingtheUSBport.Asmentionedinthecomment,insidetheotherbraces,thereareSetExpirationstopreventcontinuedmovementineventofdisablementorlostconnection.Itdoesthisbyshuttingdownpowertotheobjectthathasexpired;nowaslongasyou’reconnected,themotorsare“fed”andtheexpirationsrefresh.
FRCElectricalBible
116CustomProgram(TankDrive)
/**
*Insertowncomment
*/
voidAutonomous(void){
}
Autonomouscodegoeshere.Howeverthiscustomprogramistoshowtankdrivenotfullautopilot.
/**
*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,onejoystickcontrolsonesideofthedrive,sowhenonestickispushed,onlyonesidemovesandtheotherjoystickcontrolstheotherrespectiveside.Thisiswherethefabsfunctionis
FRCElectricalBible
117CustomProgram(TankDrive)
usedtoshortencodinglines.Normallytherewouldhavetobetwoconditionsinthoseifsfortankdrivetowork;ifthejoystickisgreaterthanathresholdORifthejoystickisbelownegativethreshold.Itwouldlooklikejoystick.GetRawAxis(2)>0.2||joystick.GetRawAxis(2)<-0.2.Comparedtowhatisinthere,itismucheasiertocode,butlessunderstandable.Reasoningiswhenyoutiltthejoystickbackitisnegative,butitdoesnotpass>0.2.Usefabsorabsolutevalue(forfloats,justabsforints),lesscoding.
/**
*Runsduringtestmode
*/
voidTest(){
while(IsTest()){
}
}
};
START_ROBOT_CLASS(RobotDemo);
Closesbracefromthebeginningoftheclass.START_ROBOT_CLASS(RobotDemo);noticehowRobotDemoisintheparameter,isn’tthattheclass?Sothisisalsoimportantforitrunstheclass.
FRCElectricalBible
118CustomProgram(TankDrive)
CustomProgram(MecanumDrive)
➠Introduction&WheelConfiguration
TheMecanumDriveallowstherobottomoveforward,backward,andstrafe.Thisispossibleduetothenatureofthewheels,whichslipbecauseoftherollersonthem.Theywillnaturallytravelina45degreemotioninthedirectionthattheentirewheelisrotating.Whenworkingwithmecanumwheels,itisimportanttoconsidertheweightdistributionoftherobotframebecausemecanumwheelsaredesignedforrobotswithanevenweightdistribution.Anunevenweightdistributionwillcausewheelssupportingmoreweighttohavemoretractionthanthewheelssupportinglessweight.Thisdifferenceintractionwillmodifytheeffectiverotationofeachwheel,andtheeffectofthemecanumdriveislost.
Leftconfiguration
RotatingForwards:motion45degreesnorthofeastRotatingBackwards:motion45degreessouthofwestUsedby:Wheel1,frontleft,andWheel4,backright.
RightConfiguration
RotatingForwards:motion45degreesnorthofwestRotatingBackwards:motion45degreessouthofeast
FRCElectricalBible
119CustomProgram(MecanumDrive)
Usedby:Wheel2,frontright,andWheel3,backleft.
➠MovementConfiguration
DrivingForward
Wheels1,2,3,and4arerotatingforwardtoallowthedriveframetodriveforward.
DrivingBackward
Wheels1,2,3,and4arerotatingbackwardtoallowthedriveframetodrivebackward.
FRCElectricalBible
120CustomProgram(MecanumDrive)
StrafingLeft
Wheels2and3arerotatingforward,Wheels1and4arerotatingbackwardtoallowthedriveframetostrafetowardtheleft.
FRCElectricalBible
121CustomProgram(MecanumDrive)
StrafingRight
Wheels1and4arerotatingforward,Wheels2and3arerotatingbackwardtoallowthedriveframetostrafetowardtheright.
FRCElectricalBible
122CustomProgram(MecanumDrive)
TurningClockwise
FRCElectricalBible
123CustomProgram(MecanumDrive)
Wheels1and3arerotatingforward,Wheel2and4arerotatingbackwardtoallowthedriveframetorotateclockwiseaboutitscenter
TurningCounter-Clockwise
Wheels2and4arerotatingforward,Wheels1and3arerotatingbackwardtoallowthedriveframetorotatecounter-clockwiseaboutitscenter
FRCElectricalBible
124CustomProgram(MecanumDrive)
➠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
FRCElectricalBible
125CustomProgram(MecanumDrive)
{
}
voidOperatorControl(){
intleftFrontPolarity=1;//Thesevariablesflipthesignvalueof
intleftBackPolarity=1;//themotorsinthesituationthattheyare
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))//Activatesifyislargest{
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))//Activatesifxislargest{
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);
FRCElectricalBible
126CustomProgram(MecanumDrive)
}
//Otherwisesticksarenotpushed
else{
leftFront.Set(0);
leftBack.Set(0);
rightFront.Set(0);
rightBack.Set(0);
}
Wait(0.005);
}
}
};
START_ROBOT_CLASS(RobotDemo);
➠TheExplanationBreakdownofthecodefollowsasso:
#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
Hereweinstantiatethe4motorcontrollersweareusingtomanipulatethe4mecanumwheelsontherobotundertheVictorclass(hereweusedVictormotorcontrollers).WealsoinstantiatedourLogitechGamepadControllerundertheJoystickclass.
FRCElectricalBible
127CustomProgram(MecanumDrive)
public:
RobotDemo():
leftFront(1),//leftFrontmotorusesPWMport1
leftBack(2),//leftBackmotorusesPWMport2
rightFront(3),//rightBackmotorusesPWMport3
rightBack(4),//rightBackmotorusesPWMport4
logitech(1)//LogitechGameControllerwithDriverstationport1
{
}
Wefurtherdefineourconstructorsbyassociatingeachpieceofhardwaretotheirrespectiveports.TheVictorClass,whichisacategoryofmotorcontrollers,utilizePWMportswhiletheJoystickClassutilizedfortheLogitechGamepadControllerutilizesthedriverstation(USB)ports
voidOperatorControl()
{
DriverStationLCD*screen=DriverStationLCD::GetInstance();
intleftFrontPolarity=1;//Thesevariablesflipthesignvalueof
intleftBackPolarity=1;//themotorsinthesituationthattheyare
intrightFrontPolarity=-1;//flipped
intrightBackPolarity=-1;
Thesevariablesareinplacetocontrolthepolarityofthemotors(whethertheyrotateforwardsorbackwardswhenpushingtheleftandrightsticksinacertaindirection).Thismakesiteasiertofixthecodeintheeventofamotorbeingreversed.
while(IsOperatorControl()){
floatx=0;//x-axismotion-right(+),left(-)
floaty=0;//y-axismotion-forward(+),backward(-)
floatz=0;//z-axismotion-clockwise(+),counterclockwise(-)
Thissplitstheaxesofthemotionsothattheycanbeassignedbasedonhowthethumbsticksarepushed.Thepushingtheleftthumbstickonit’sy-axiswillgiveay-value(+=forward,-=backward),pushingtheleftstickonit’sx-axisgivesaz-value(+=clockwise,-=backward),andpushingtherightstickonit’sx-axisgiveax-value(+=right,-=left).
FRCElectricalBible
128CustomProgram(MecanumDrive)
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.Athresholdisplacedsothattinyaccidentalmovementsdonotcausetherobottodrift.
//y-axismotion
if(fabs(y)>fabs(x)&&fabs(y)>fabs(z))//Activatesifyislargest{
leftFront.Set(y*leftFrontPolarity);
rightFront.Set(y*rightFrontPolarity);
leftBack.Set(y*leftBackPolarity);
rightBack.Set(y*rightBackPolarity);
}
Iftheleftstickispushedmoreonit’sy-axis(forward/backward)thanitortherightstickispushedontheirx-axis,thentherobotwillmoveforwardorbackwardsdependingonthedirectionofthethumbstick.Pushingforwardwillmakeallwheelsrotateforwardandpushingbackwardsmakesallwheelsrotatebackward.Also,thespeedofthemotorsdependsonhowmuchtheleftthumbstickispushedalongthey-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,thentherobotwillstrafeeitherrightorleft.Pushingthethumbsticktotherightmakestheleftfrontandrightbackmotorsrotateforwardwhiletheothertworeverse(usedthevectordiagramto
FRCElectricalBible
129CustomProgram(MecanumDrive)
determinedirection).Pushingthethumbsticktotheleftmakestheoppositehappen,withtherightfrontandleftbackrotatingforwardwhiletheleftfrontandrightbackreverse.Again,thespeedofthemotorsdependsonhowlargethemagnitudeoftherightthumbstick’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-axisandtherightthumbsticksx-axis,thentherobotwillrotate.Iftheleftstickispushedtotheright,theleftwheelswillrotateforwardandtherightwheelswillrotatebackwards,makingitturnclockwise,muchliketankdrive.Theoppositehappenswhenyoupushthesticktotheleft.
else{
leftFront.Set(0);
leftBack.Set(0);
rightFront.Set(0);
rightBack.Set(0);
}
Thissetsallthemotorsto0whenthejoysticksarenotpushedinanassigneddirectionorarenotpushedpastthethreshold
AlternateCode(putthisinplaceofalloftheifelsestatements)
leftFront.Set(x-y-z);
leftBack.Set(-x-y-z);
rightFront.Set(x+y+z);
rightBack.Set(-x+y+z);
Thiscodeisusedasasimplificationoftheonepostedearlier.However,thereisafundamentaldifferenceinhowthesetwooperate.Intheoriginalcode,youcanonlymoveinspecificdirections,likeforward,backwards,right,left,androtate,whereasinthisversionyoucanmoveinanycombinationofthethreeaxes.Thisisachievedbybypassingifstatementsandjustusingadditionandsubtraction.Thiswayalsoallowsyoutobypasstheissueof
FRCElectricalBible
130CustomProgram(MecanumDrive)
makingaspecificvariableforpolarity,asyoucanjustchangethe+or-forthespecificmotor.Inthissituation,theleftmotorswerereversed,soitwasnecessarytochange+yto-yand+zto-zasitisnow.Youalsohavetoswitchthesignofthexvariable.Iftheleftmotorswerenotreversed,thecodewouldbeleftFront.Set(-x+y+z)andleftBack.Set(x+y+z).However,thereisanissuethatexistswithinthiscodeasitispossibleforthesetvalueforeachmotortoexceed1ifyouweretorotatewhilemovinginanotherdirection.
➠TestedandModifiedCode
//Thisistemporarycodethatwillbereplacedinthebibleuponfinalcodecompletion
#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;//themotorsinthesituationthattheyare
intrightFrontPolarity=-1;//flipped
intrightBackPolarity=-1;
floatx=0;//x-axismotion-right(+),left(-)
FRCElectricalBible
131CustomProgram(MecanumDrive)
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);
FRCElectricalBible
132CustomProgram(MecanumDrive)
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(-)
FRCElectricalBible
133CustomProgram(MecanumDrive)
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);
➠TheExplanationBreakdownofthecodefollowsasso:
FRCElectricalBible
134CustomProgram(MecanumDrive)
#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
Hereweinstantiatethefourmotorcontrollersweareusingtomanipulatethe4mecanumwheelsontherobotundertheVictorclass(hereweusedVictormotorcontrollers).Wealsoinstantiatedourtwojoysticksthatwillbecontrollingthemotionoftherobots
public:
RobotDemo():
leftFront(1),//leftFrontmotorusesPWMport1
leftBack(2),//leftBackmotorusesPWMport2
rightFront(3),//rightBackmotorusesPWMport3
rightBack(4),//rightBackmotorusesPWMport4
stickOne(1)//Logitechattack3withDriverstationport1
stickTwo(2)//Logitechattack3withDriverstationport2
{
}
Here,wefurtherdefineourconstructorsbyassociatingeachpieceofhardwaretotheirrespectiveports.TheVictorClass,whichisacategoryofmotorcontrollers,utilizePWMportswhiletheJoystickClassutilizedfortheLogitechAttack3utilizesthedriver-stationports.
FRCElectricalBible
135CustomProgram(MecanumDrive)
voidOperatorControl(){
DriverStationLCD*screen=DriverStationLCD::GetInstance();
intleftFrontPolarity=1;//Thesevariablesflipthesignvalueof
intleftBackPolarity=1;//themotorsinthesituationthattheyare
intrightFrontPolarity=-1;//flipped
intrightBackPolarity=-1;
floatx=0;//x-axismotion-right(+),left(-)
floaty=0;//y-axismotion-forward(+),backward(-)
floatz=0;//z-axismotion-clockwise(+),counterclockwise(-)
Thetophalfofthissectionismeanttobeinpreparationforthesituationwhereoneormorewheelsneedtohavetheirpolarity(goingforwardsorbackwards)flipped.Thebottomhalfismeanttoinstantiateandconstructthevariablesthatwillberepresentingourvariousaxesofmotion.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.Thefirstoneissettingathresholdforallaxesofmotion.Thejoysticksmustbepushedpastavalueof.2inorderforitsvaluetobeconsideredvalid.Thisismeanttopreventtherobotfromdriftingduetothejoysticknotperfectlyrestingat0.Thesecondfunctionistoassigneachaxisofmotiontoajoystickdirection.Inourscenario,wepreferredtomakepushingstickOneleftandrightrotatethevehiclecounterclockwiseandclockwiserespectively.PushingstickOneforwardsandbackwardscorrelatestoforwardsandbackwardsmotion.PushingstickTwototherightandleftcorrelatestostrafingrightandleft.
FRCElectricalBible
136CustomProgram(MecanumDrive)
//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)ofstickOne’spositionisgreaterinmagnitudethanitsz-component(leftandright)andstickTwo’sx-component(leftandright).Thisismeanttomaketherobotonlymoveinonedirectionatatime.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-componentofstickTwo’spositionislargerthananyofstickOne’s.However,thissectionisdifferentasourrobotwouldrotateslightlyclockwiseanddriftslightlybackwards.Toaddressthis,wehadtomanuallyaddmultiplierstocertainmotorstomakethemmoveslowerorfasteratcertainintervals.Wealsohadtoseparateleftstrafingandrightstrafingbecausetheybehaved
FRCElectricalBible
137CustomProgram(MecanumDrive)
differently.Intheblockabove,weonlyseetherightstrafingportionofthecode.Thissectionissubdividedintotwomoresections,whenthewheelsaresuppliedatleasthalfoftheirmaximumvoltage(>=.5)andwhentheyaresuppliedonlyalittlebitofvoltage(.5>v>0.35).Thiswasduetoourdrivereactingdifferentlyatdifferentvoltages.You’llseemultiplierslike1.1,-0.95and0.9intheabovecode,thisisbecausesomewheelswererotatingslower/fasterthanothers.Multiplierswithmagnitudesbelow1aremeanttoslowthespeedofthatspecificmotor.Multiplierswithmagnitudesabove1aremeanttospeedthemup.Differentsigns(+or-)aremeanttoreversethedirectionofthewheelinorderforthevectorstomakethecardmoveinthedesireddirection.
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.Sincethismotionhaddifferenterrorsthatstrafingtotherightdid,wehadtoeditthemultipliersuntiltherobotstrafednicely.
//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);
}
FRCElectricalBible
138CustomProgram(MecanumDrive)
Thissectionofthecodeisforrotatingtherobot.Again,thisisactivatedonlywhenthemagnitudeofstickOne’sz-component(howmuchtotheleftorrightitis)islargerthanboththexandycomponents.Inordertorotate,therightsightmustalwaysbegoingthedirectionoppositeofwherethejoysticktellsitto.Thisiswhytheyhavea-1appliedintheirstatements.PushingstickOnetotherightmakestherobotrotateclockwiseandpushingittotheleftmakesitrotatecounterclockwise.
//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.Theymaketherobotmoveforwardsandrotateslightlywheneitherthe4or5-buttonispressed.Pressingthe5-buttonmakesitturnrightandpushingthe4-buttonmakesitturnleft.
//Otherwisesticksarenotpushed
else{
leftFront.Set(0);
leftBack.Set(0);
rightFront.Set(0);
rightBack.Set(0);
}
Thepurposeofthissectionistoensurethatwhenthejoysticksareattheirrestingpositionsorverynearitthatthemotorswillnotrotatethewheels.
FRCElectricalBible
139CustomProgram(MecanumDrive)
x=0;//x-axismotion-right(+),left(-)
y=0;//y-axismotion-forward(+),backward(-)
z=0;//z-axismotion-clockwise(+),counterclockwise(-)
SincethisportionofthecodeisoutsideoftheIsOperatorControlwhileloop,thismakessurethatthemotorswillNOTrotatethewheelswhentherobotisnotundercontrolofthedriver.
FRCElectricalBible
140CustomProgram(MecanumDrive)
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
FRCElectricalBible
141Sensors
roboRIOAccelerometer
➠GeneralOverview
OneofthemanyfeaturesthatcomeswiththeRoboRIOisthebuilt-in3-axisaccelerometer,whichhasthepotentialtoreplacetheADXL345accelerometerthatalsocomesinthe2015KitofParts.Thepurposeofthisdeviceistodeterminetheproperaccelerationofanobject,whichisitsaccelerationrelativetofreefall.Thiscanbeusedtodeterminehowmuchtherobotistiltedorawaytomonitormotion.
➠SpecificationsAxes:3(x,y,andz)SampleRate:800SamplespersecondResolution:12bitsRange:±8g(gravity)Noise:3.9mgmstypicalat25°C
FRCElectricalBible
142roboRIOAccelerometer
➠TheCodeThisisthecodeweusedtodeterminethedirectionofeachaxisaswellasthestabilityofthereturnedvalues.
#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:",((xAcceleration*0.1)+(0.9*previousX)));
//returnsarecursiveaverageforthex-axis
SmartDashboard::PutNumber(“RecursiveY-AxisAverage:",((yAcceleration*0.1)+(0.9*previousY)));
//returnsarecursiveaverageforthey-axis
SmartDashboard::PutNumber(“RecursiveZ-AxisAverage:”,((zAcceleration*0.1)+(0.9*previousZ)));
//returnsarecursiveaverageforthez-axis
FRCElectricalBible
143roboRIOAccelerometer
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;declaredbetweenpublicSampleRobotandpublic:RobotDemo
public:
//setstherangeoftheaccelerometertobe+or-8G(unitsofgravity)
Robot():accelerometer(Accelerometer::Range::kRange_8G){
}
InitializestheroboRIOaccelerometerwitharangeof+/-8Gs,whichistheaccelerationinunitsofgravity(9.81m/s).Thisisthemaximumrangethatthedeviceiscapableof.Thereisnoneedtoinputpwmportsastheaccelerometerisbuiltin.
voidOperatorControl(){
doublexAcceleration;//accelerationonthex-axis
doubleyAcceleration;//accelerationonthey-axis
doublezAcceleration;//accelerationonthez-axis
doublepreviousX=0;//Previousrecursiveaverageonx-axis
doublepreviousY=0;//Previousrecursiveaverageony-axis
doublepreviousZ=1;//Previousrecursiveaverageonz-axis
FRCElectricalBible
144roboRIOAccelerometer
InthissectionweinitializethevariablesthatwewillbeusingforoutputontheSmartDashboard.Sincetheaccelerometerhas3axes,weneedavariableforeachone(x,y,andz).Thepreviousaxisvariablesareusedtodeterminearecursiveaveragethatisexplainedlaterinthisdocument.Theyaremeanttostorethevalueoftherecursiveaverageofallpreviouslyreturnedvalues.previousXandpreviousYareequalto0becausethatistheexpectedvaluewhentheroboRIOisatrestandonaperfectlyhorizontalsurface.previousZisequalto1becausetheroboRIOisnotinfreefall,whichiswhatanaccelerometermeasuresaccelerationinreferenceto.
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,thevariablesxAcceleration,yAcceleration,andzAccelerationarebeingsettothecurrentvaluesoftheaccelerometerpertainingtothex,y,andzaxis.Afterupdatingthesevalues,theyarethensenttotheSmartDashboardtobereadintheformofarunningvalueoratable.
SmartDashboard::PutNumber("RecrusiveX-AxisAverage:",((xAcceleration*0.1)+(0.9*previousX)));
//returnsarecursiveaverageforthex-axis
SmartDashboard::PutNumber(“RecursiveY-AxisAverage:",((yAcceleration*0.1)+(0.9*previousY)));
//returnsarecursiveaverageforthey-axis
SmartDashboard::PutNumber(“RecursiveZ-AxisAverage:”,((zAcceleration*0.1)+(0.9*previousZ)));
//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);
FRCElectricalBible
145roboRIOAccelerometer
Herewecalculatetherecursiveaverageforeachaxiswhichcanbeusefulduringtesting.Thepurposeofhavingthisrecursiveaverageistoeffectivelyreducethesensitivityofthereturnedvaluestofluctuations.Thisallowsyoutogetamoreaccurateandstablereadingforeachaxisoftheaccelerometer,andcouldbeusedtotestforvaryinganglesthattheaccelerometeristilted.
Thissimplerecursiveaveragealgorithmisdonebytaking.1ofthecurrentvalueforanaxisandaddingitto.9ofthepreviousaverage.Thisessentiallymeansthatwehaveaconstantlychangingaverage.Notethatthesensitivityofthisalgorithmcanbeadjustedbychangingthe“0.1”and“0.9”values.However,rememberthatthetwomultipliersmustaddtoavalueof1,becausetheaveragewilltendtocontinueincreasingordecreasingdependingonhowthemultipliersareadjusted.Ifyouhaveamultipliersof.01and.99,thecurrentaveragewillbemuchlesssensitivetochangeastheweightofeachnewnumberisdrasticallydecreased.
FRCElectricalBible
146roboRIOAccelerometer
Microswitch
➠Use
Themicroswitchisusuallyusedtokeepsomethingfromoverextendingorsurpassingsomedistance.Whentheswitchnotpushed,theswitchisNC(normallyclosed),returning1.Whentheswitchpushed,theswitchisNO(NormallyOpen),returning0.
➠Wiring
FRCElectricalBible
147Microswitch
TheswitchispluggedintotheDigitalIOsectionoftheroboRIOviaaPWMcable.
➠Programming
DeclaredandinstantiatedasaDigitalInput
WhenswitchNC,returns0WhenswitchNO,returns1
Declaration:DigitalInputswitch;
Instantiation:switch(1)//portnumberinthedigitalsidecar
FRCElectricalBible
148Microswitch
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);
FRCElectricalBible
149Microswitch
OpticalEncoder
➠UseTheopticalencoderisthemostcommontypeofencoderinFRCthatusesoneormoreLEDspointedatastriporslitcodewheelandtwodetectors90degreesaparttomeasuretherotationspeedofawheelorothershafts.TheencoderpicturedtotheleftisaUSDigitalE4P(am-0174)opticalencoder.
Specs
MaxRPM:10,000RPM100-360cyclesperrevolution400-1440pulsesperrevolutionMinimumshaftlength:.375”(⅜)ShaftDiameter:.079”to.250”Weight:.018lbs
➠Assembly
1. Placebaseovershaft.Securebasetomountingsurfaceusingeitherthetwoscrewsonthebaseoramountingpad.
FRCElectricalBible
150OpticalEncoder
Mountingthebasewithoutamountpad
Mountingpadplacedunderthebaseifused.
2. Placehubdiskassemblyontoshaftwithpattern-sidedowntowardsbase.Itshouldnotbecompletelypresseddown.
3. Usethespacer(lipfacingdownwards)topushthehubdiskassemblytotheappropriatelocationontheshaft.Thediskshouldnotbetouchinganythingbesidestheshaftandthespacer,andthereshouldbeaconsiderablegapbetweenthediskandthebase.
FRCElectricalBible
151OpticalEncoder
4. Removethespacerwhileensuringthatthediskstaysinplace.
5. Placethehousingontopoftheencoder.Usingyourthumbandfinger,squeezeearstogethertoensurethatthecoverfullylatches.
➠MountingItiseasiestiftheopticalencoderisplacedontheoutputshaftasthereisadirectcorrelationbetweentherotationoftheshaftandthemovementofwhateveritcontrols.Alsoensurethattheopticalencoderisperfectlycenteredaroundtheshaft.
➠StorageTheopticalencodercangetscratchedeasilysoitshouldbestoredinaspecialcasetopreventscratchingorinaplacethatwillnotscratchthesurfaceofthedisk.
FRCElectricalBible
152OpticalEncoder
➠Wiring
Thewiringfortheopticalencoderusestwochannels(DigitalIO;A/B)forthePDPsofourwireshavetobesolderedtotwoPWMs.
Orange:Power------------------------------->PWM2Power
Blue:ChannelA------------------------------>PWM1Signal
Brown:Ground------------------------------->PWM2Ground
Yellow:ChannelB---------------------------->PWM2Signal
➠Programming
//CodeUsedforTestingwithroboRIO
#include"WPILib.h"
FRCElectricalBible
153OpticalEncoder
/**
*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);//ThismakesitsothatGetDistancewillreturn1whentheshaft
//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.GetDistance());
//printsdisplacementinrevolutions
SmartDashboard::PutNumber("EncoderRate",encoder.GetRate());
//printsrateinRevspersecond
Wait(kUpdatePeriod);
}
}
}
};
START_ROBOT_CLASS(Robot);
FRCElectricalBible
154OpticalEncoder
FRCElectricalBible
155OpticalEncoder
Gyro
➠GeneralOverviewThegyromeasuresangularchangesonthetopsurfaceaxis.Thevoltageoutputdependsontheangularchangeitdetects.Itcanalsomeasuretherateofangularchange.Itnormallywouldbeusedintandemwiththeaccelerometer,sincetheaccelerometercandetectabsoluteanglevsangularmotion.Thegyrobestfunctionsatthecenteroftherobot’saxisofrotation.Whenmountingit,keepthegyroawayfromanythingthatmightfrythegyro,soitisbesttoelectronicallyisolateitfromthemainmountingboard.Noteworthyisthatitalsocontainsatemperaturesensor,usefulfordetectingheatwithintherobotsystemduringoperationifathermaldetectorisnotavailableorduringamatch.
➠SpecificationsThegyroacceptsa+5Vforpower,canrecordupto250O/s,hasanominaloutputof2.5Vatstandstill,adds7mV/O/s.Boardcarriesafiltersetto400Hz.Containsintegratedtemperaturesensorwhichacceptsa+5Vforpowerwithnominaloutputat2.5Vat25OC,adds9mV/OC.
➠Wiring
FRCElectricalBible
156Gyro
WirestotheroboRIOAnalogINportsusingafemale-to-femalePWM.Ground,Power,Signalfromoutsideinrespectively.
WirestotheGyrosensorwiththeotherendofthefemale-to-femalePWM.Ground,Power,Signalfromoutsideinrespectively.
➠Programming
FRCElectricalBible
157Gyro
#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);
FRCElectricalBible
158Gyro
TheD-Link
FRCElectricalBible
159Camera
TheD-Link
FRCElectricalBible
160LiveFeed
TheD-Link
FRCElectricalBible
161Pneumatics
TheD-Link
FRCElectricalBible
162Appendixes
ChangelogJanuary10,2016,modifiedbyVivian
UpdatedPDPchapterAddedSensorschapterMadeformattingchangestoDriveCodechapterAddedManualConfigurationtoD-Linksection
February23,2015,modifiedbyVivian
AddedDriveCodeFixedTableofContents
February5,2015,modifiedbyVivian
AddedDriverStationDocumentationAddedMotorControllerDocumentation
February2,2015,modifiedbyKayliandAlex
AddedPDPDocumentationAddedD-LinkDocumentation
FRCElectricalBible
163Changelog