| 1 | == Servo Motor Control |
| 2 | |
| 3 | Robots must be able to interact with the environment around them too. Many types of actuators are used in FRC robotics; one of them is the [https://wpilib.screenstepslive.com/s/currentCS/m/java/l/599703-repeatable-low-power-movement-controlling-servos-with-wpilib Servo Motor]. A servo motor is a special type of motor that can rotate to a precise position, usually between 0 and 180 degrees. They come in a variety of sizes and strengths. You can connect a servo motor to any of the [http://www.ni.com/pdf/manuals/375274a.pdf#_OPENTOPIC_TOC_PROCESSING_d443e2165 PWM ports] on the !RoboRIO. Examine the PWM ports and identify which row of pins are ground ([[Image(GroundSymbol.png,25px)]], +6V, and Signal (S). Make sure you connect them to the proper pins on the Servo motor: black or brown goes to Ground, red or orange goes to +6V, yellow/white/blue goes to Signal. You can read more about servo motors [https://learn.sparkfun.com/tutorials/servo-trigger-hookup-guide/all here] |
| 4 | |
| 5 | Create another program using the !TimedRobot java template and name it !ServoTest. Modify the generated code as follows: |
| 6 | * Add the following imports: |
| 7 | {{{ |
| 8 | import edu.wpi.first.wpilibj.XboxController; |
| 9 | import edu.wpi.first.wpilibj.GenericHID.Hand; |
| 10 | import edu.wpi.first.wpilibj.Servo; |
| 11 | }}} |
| 12 | * declare variable for the Xbox controller and [https://wpilib.screenstepslive.com/s/currentCS/m/java/l/599703-repeatable-low-power-movement-controlling-servos-with-wpilib servo motor] in the Robot class |
| 13 | {{{ |
| 14 | private XboxController xbox; |
| 15 | private Servo servo; |
| 16 | }}} |
| 17 | * in robotInit() instantiate the controller and motor objects |
| 18 | {{{ |
| 19 | xbox = new XboxController(0); // Xbox controller on port 0 |
| 20 | servo = new Servo(1); // Servo connected to PWM 1 |
| 21 | }}} |
| 22 | * in teleopPeriodic() read the xbox controller and adjust the servo motor accordingly |
| 23 | {{{ |
| 24 | // Read xbox controller left joystick x axis |
| 25 | // value returned is between -1.0 and 1.0 |
| 26 | double x = xbox.getX(Hand.kLeft); |
| 27 | // Servo motors are controlled on a scale of 0.0 to 1.0 |
| 28 | // so re-scale the X value to that range (-1.0->0, 0->0.5, 1.0->1.0) |
| 29 | x = (x + 1.0) / 2; |
| 30 | // Set servo motor position based on joystick |
| 31 | servo.set(x); |
| 32 | }}} |
| 33 | |
| 34 | Connect a Servo motor to PWM port 1 on the roboRIO and run your program. You'll need to press the Enable button on the driver station to put the robot in Teleop mode so that teleopPeriodic() is called repeatedly. |
| 35 | |
| 36 | * Extra credit: use buttons on the Xbox controller to set the servo to a specific position (e.g. 45-degrees, 90-degrees, 135-degrees). |