Lesson: Exercise: Using Servos

Overview: 
Explore programming Servos.
Objectives: 

Understand Servos and how to program them.

Content: 

Now lets look at using servos to control robot functions. The wheel motors we used in the previous exercises simply run at whatever power level they are set at. Servos are different in that they have a defined range of motion and you control them by setting the location in that range you want the servo to move to. Once in that position, servos resist movement. Servos are typically used for arms and grippers.

Servo positions range from 0 to 1. When you build your robot, you will have to experimentally determine how the position values map to the arm and gripper servos in terms up up/down and open/closed.

In this exercise, we will have two servos on our robot, one to raise and lower an arm. In our hardware configuration we name this servo "arm_servo". At the end of the arm is a simple gripper which is opened and closed by a second servo named "grip_servo". We use buttons on the controller to move the servos. Lets extend our Tank Drive example to operate these two servos:

Copy and paste this code into a new OpMode called DriveWithGripper and demonstrate servo control on your robot.
 
We operate the servos by adding or subtracting a small amount to the servo position when a gamepad button is depressed. We have to montior the position and not go over or under the servo min/max.
 
Note that the increment and decrement of the servo position variables show the two different ways to add or subtract with a numeric variable.
 
Here is more detailed information about servos on the Modern Robotics website.
 
When you test this code you will see that displaying double or float values may result in a very large number  being displayed due to the nature of these data types in Java. By default, if a double or float has places right of the decimal point, all of those places will be displayed. We can trim that down using the format function of the String class. Here we call String.format(formatstring, variable) where the format string tells Java we will be displaying a floating point number and we only want to show 2 places right of the decimal point. You can comment out the original lines and uncomment the lines with String.format() to see how this works. Finally, addData() has built in support for formatting the message so you don't have to use String.format(). Try all 3 ways. Here is a detailed discussion of formatting variables into strings for output.
 

Lesson navigation: