64
ROBOTC Ultrasonic Rangefinder 1 © Carnegie Mellon Robotics Academy / For use with VEX ® Robotics Systems Sensing In this lesson, you will learn how an Ultrasonic Rangefinder (a.k.a. Sonar) works, and how to use it to move to within a specific distance of an object. Ultrasonic Rangefinder Forward till Near The Touch Sensors (Bumper and Limit Switches) allow your robot to detect physical contact. They allow the robot to keep track of the position of its arm, and can potentially detect walls or other objects in the environment if the robot bumps into them. Robot with a touch sensor on a board The Encoders allow your robot to measure rotation of motors, wheels, and other important parts. Indirectly, measuring the rotation of important parts can tell you how far the robot has traveled, in what direction, and advanced analysis can even tell you whether the robot is encountering external interference that is affecting the speed of a given wheel. Robot with encoders on a board For navigation, however, we still do not have a sensor that allows the robot to detect objects without physically hitting them. If the robot ever hopes to pick up the mines without knocking them over, “touchless” detection will be absolutely necessary.

Ultrasonic Rangefinder Forward till Near - Carnegie Mellon...education.rec.ri.cmu.edu/downloads/vex/TRC_VEX_training_pdfs... · In this lesson, you will learn how an Ultrasonic Rangefinder

Embed Size (px)

Citation preview

Page 1: Ultrasonic Rangefinder Forward till Near - Carnegie Mellon...education.rec.ri.cmu.edu/downloads/vex/TRC_VEX_training_pdfs... · In this lesson, you will learn how an Ultrasonic Rangefinder

ROBOTC

Ultrasonic Rangefinder • 1© Carnegie Mellon Robotics Academy / For use with VEX® Robotics Systems

Sensing

In this lesson, you will learn how an Ultrasonic Rangefinder (a.k.a. Sonar) works, and how to use it to move to within a specific distance of an object.

Ultrasonic Rangefinder Forward till Near

The Touch Sensors (Bumper and Limit Switches) allow your robot to detect physical contact. They allow the robot to keep track of the position of its arm, and can potentially detect walls or other objects in the environment if the robot bumps into them.

Robot with a touch sensor on a board

The Encoders allow your robot to measure rotation of motors, wheels, and other important parts. Indirectly, measuring the rotation of important parts can tell you how far the robot has traveled, in what direction, and advanced analysis can even tell you whether the robot is encountering external interference that is affecting the speed of a given wheel.

Robot with encoders on a board

For navigation, however, we still do not have a sensor that allows the robot to detect objects without physically hitting them. If the robot ever hopes to pick up the mines without knocking them over, “touchless” detection will be absolutely necessary.

Page 2: Ultrasonic Rangefinder Forward till Near - Carnegie Mellon...education.rec.ri.cmu.edu/downloads/vex/TRC_VEX_training_pdfs... · In this lesson, you will learn how an Ultrasonic Rangefinder

ROBOTC

Ultrasonic Rangefinder • 2© Carnegie Mellon Robotics Academy / For use with VEX® Robotics Systems

Sensing

Ultrasonic Rangefinder Forward till Near (cont.)

The Ultrasonic Rangefinder offers exactly this capability. Using the same physical principle as a bat or submarine’s sonar, the Ultrasonic Rangefinder measures distances using sound. It sends out a pulse of sound, then waits to hear the sound’s echo off of a solid object in the environment. By measuring how long it takes for the sound to bounce back, the sensor can calculate the distance that the sound must have traveled, and hence, how far away the object was that reflected it back.

Ultrasonic Sensor detect-ing a wall visual aid from Teaching NXT

The Ultrasonic Rangefinder will work in a very similar way to the Encoder program you wrote in the previous section, but instead of measuring the distance that the wheel has turned, it will use the Ultrasonic Rangefinder to measure the distance to the nearest object in front of the arm.

1. Add an Ultrasonic Rangefinder to the front of the robot’s arm. The design shown below will be used as the reference for the remainder of the unit. If you choose to use a design that differs significantly from this one, you may need to adjust accordingly.

Illustration or building in-structions for arm-ultrasonic attachment

Page 3: Ultrasonic Rangefinder Forward till Near - Carnegie Mellon...education.rec.ri.cmu.edu/downloads/vex/TRC_VEX_training_pdfs... · In this lesson, you will learn how an Ultrasonic Rangefinder

ROBOTC

Ultrasonic Rangefinder • 3© Carnegie Mellon Robotics Academy / For use with VEX® Robotics Systems

Sensing

Ultrasonic Rangefinder Forward till Near (cont.)

2. Create a new program.

3. Save the new program as “ForwardNear”.

4. Use the Motors and Sensors Setup Menu to configure the Ultrasonic Rangefinder on Analog Digital Port 5, and Interrupt 1. Because of the precise timing requirements of measuring the sonar sound pulses, Ultrasonic Rangefinders require both an A/D Port and an Interrupt Port to function.

2. File > NewSelect File > New to create a new program.

3a. File > Save As...Select File > Save As... to save your program under a new name.

3b. Renate programGive this program the name ForwardNear.

3c. SaveClick Save.

4a. Robot > Motors and Sensors SetupSelect Robot > Motors and Sensors Setup to open up the configuration menu.

Page 4: Ultrasonic Rangefinder Forward till Near - Carnegie Mellon...education.rec.ri.cmu.edu/downloads/vex/TRC_VEX_training_pdfs... · In this lesson, you will learn how an Ultrasonic Rangefinder

ROBOTC

Ultrasonic Rangefinder • 4© Carnegie Mellon Robotics Academy / For use with VEX® Robotics Systems

Sensing

Ultrasonic Rangefinder Forward till Near (cont.)

4b. Select A/D Sensors 1-8

4c. Set the sensor Name to “sonarSensor”The Ultrasonic Rangefinder is indexed by the number of the Analog/Digital Port it is plugged into, so enter a name for the sensor under Analog/Digital Port in5.

4d. Set the sensor Type to “SONAR”Set the type of the sensor to “SONAR”, another name for the Ultrasonic Rangefinder (because it uses sonar sound waves to measure distance).

4e. Configure the Second Port to “int1”When you select “SONAR” as the sensor Type, a column for the “second port” appears for this sensor. The second port is the other port that the sensor is plugged into, interrupt 1 (int1).

4f. Click OKClick OK to finish configuring the Ultrasonic Rangefinder.

Checkpoint

The Ultrasonic Rangefinder is now set up and recognized by the program. It will now provide sensor readings as values through SensorValue(sonarSensor). The values represent distances to the nearest detectable object (the first echo that the sensor hears), in inches. If an object is 6 inches away, in front of the sensor, SensorValue(sonarSensor) will be 6.

[illustrations of objects at various distances, with their distances and SensorValue(sonarSensor) values cap-tioned]

Page 5: Ultrasonic Rangefinder Forward till Near - Carnegie Mellon...education.rec.ri.cmu.edu/downloads/vex/TRC_VEX_training_pdfs... · In this lesson, you will learn how an Ultrasonic Rangefinder

ROBOTC

Ultrasonic Rangefinder • 5© Carnegie Mellon Robotics Academy / For use with VEX® Robotics Systems

Sensing

Let us first begin by reviewing the way a forward-for-distance Encoder behavior works, and then adapt it to use the Ultrasonic Rangefinder instead.

The forward-for-distance command below was taken from the early parts of the Encoder lesson, and moves the robot forward until the Encoder accumulates more than 5000 counts of rotation. It does so by using a while loop to repeat basic movement commands as long as the current count is still below the desired target.

Ultrasonic Rangefinder Forward till Near (cont.)

while(SensorValue[leftEncoder] < 5000) { motor[port3] = 63; motor[port2] = 63; }

In the case of the Ultrasonic Rangefinder moving until the robot is close to an object (such as the “stem” of a mine), we want the robot to move until the detected distance is below the target distance. Rephrased, the robot should keep running as long as the distance to the object is still greater than the desired distance.

AutoAuto

12345

const tSensors sonarSensor = (tSensors) in5;

task main(){ wait1Msec(2000); bMotorReflected[port2] = 1;}

5. Add task main and base code.

5. Add this codeAdd task main, an initial delay, and the motor reflection command before proceeding with the rest of the program.

AutoAuto

123456789

1011

const tSensors sonarSensor = (tSensors) in5;

task main(){ wait1Msec(2000); bMotorReflected[port2] = 1;

while() { motor[port3] = 63; motor[port2] = 63; }}

6. Add the basic structure of a move-until behavior.

6. Add this codeThe basic structure of the behavior is a while loop containing moving-forward commands. The (condition) will determine how long this loop lasts, and is left blank for now.

Page 6: Ultrasonic Rangefinder Forward till Near - Carnegie Mellon...education.rec.ri.cmu.edu/downloads/vex/TRC_VEX_training_pdfs... · In this lesson, you will learn how an Ultrasonic Rangefinder

ROBOTC

Ultrasonic Rangefinder • 6© Carnegie Mellon Robotics Academy / For use with VEX® Robotics Systems

Sensing

Ultrasonic Rangefinder Forward till Near (cont.)

7. Choose the (condition) based on the Ultrasonic Rangefinder. The (condition) should make the movement commands repeat as long as the distance to the target is still above the desired value.

AutoAuto

123456789

1011

const tSensors sonarSensor = (tSensors) in5;

task main(){ wait1Msec(2000); bMotorReflected[port2] = 1;

while(SensorValue[sonarSensor] > 3) { motor[port3] = 63; motor[port2] = 63; }}

7. Add this codeThe (condition) should be true as long as the Rangefinder’s value is above 3 inches. This will make the robot move forward as long as the Rangefinder does not detect any objects within 3 inches.

8. Download and Run.

8. Go to Compile and Download Program

Checkpoint

Your robot will run forward until it is within 3 inches of a detectable object. Not all objects are detectable, however, and the “area” of detection is only in front of the Ultrasonic Rangefinder itself. These limitations are inherent to the technology, but the sensor does seem to be able to detect the mines, as we had hoped.

robot stopping in front of object similar ot mine

Page 7: Ultrasonic Rangefinder Forward till Near - Carnegie Mellon...education.rec.ri.cmu.edu/downloads/vex/TRC_VEX_training_pdfs... · In this lesson, you will learn how an Ultrasonic Rangefinder

ROBOTC

Ultrasonic Rangefinder • 7© Carnegie Mellon Robotics Academy / For use with VEX® Robotics Systems

Sensing

Ultrasonic Rangefinder Forward till Near (cont.)

9. Upgrade this behavior to go straight while there is no obstacle nearby, rather than just run forward.

9a. Robot > Motors and Sensors SetupSelect Robot > Motors and Sensors Setup to open up the configuration menu.

9d. Press OKConfirm the new sensor configuration.

9c. Set the “Type” of both sensorsIdentify the sensor attached to both in2 and in3 as “Rotation” sensors (Encoders sense rotation).

9b. “Name” the sensorsAssign the name “leftEncoder” to the sensor in port “in3” (A/D input 3). Name the “in2” (A/D input 2) sensor “rightEncoder”.

9e. File > SaveSelect File > Save to save your program.

9f. File > Open and Compile

Page 8: Ultrasonic Rangefinder Forward till Near - Carnegie Mellon...education.rec.ri.cmu.edu/downloads/vex/TRC_VEX_training_pdfs... · In this lesson, you will learn how an Ultrasonic Rangefinder

ROBOTC

Ultrasonic Rangefinder • 8© Carnegie Mellon Robotics Academy / For use with VEX® Robotics Systems

Sensing

Ultrasonic Rangefinder Forward till Near (cont.)

123456789

10111213141516171819

void moveStraight(){ if(SensorValue[leftEncoder] > SensorValue[rightEncoder]) { motor[port3] = 50; motor[port2] = 63; } if(SensorValue[leftEncoder] < SensorValue[rightEncoder]) { motor[port3] = 63; motor[port2] = 50; } if(SensorValue[leftEncoder] == SensorValue[rightEncoder]) { motor[port3] = 63; motor[port2] = 63; } }}

9h. Highlight codeFind the void moveStraight() function and highlight it.

9g. Open MineArmStraight Instead of re-entering the moving-straight code, we’ll take a copy of it from the Encoders program.

9i. Copy this codeSelect Edit > Copy to put the highlighted code on the clipboard.

9j. Select File > Open and Compile

Page 9: Ultrasonic Rangefinder Forward till Near - Carnegie Mellon...education.rec.ri.cmu.edu/downloads/vex/TRC_VEX_training_pdfs... · In this lesson, you will learn how an Ultrasonic Rangefinder

ROBOTC

Ultrasonic Rangefinder • 9© Carnegie Mellon Robotics Academy / For use with VEX® Robotics Systems

Sensing

Ultrasonic Rangefinder Forward till Near (cont.)

9k. Open ForwardNearReturn to the Forward Till Near Ultrasonic Rangefinder program.

9l. Place cursor herePlace your cursor between task main and the AUTO code.

9m. PasteThe moving straight function is now declared, and available for use in this program.

Replace this screen shot with one

that uses squre brackets

Page 10: Ultrasonic Rangefinder Forward till Near - Carnegie Mellon...education.rec.ri.cmu.edu/downloads/vex/TRC_VEX_training_pdfs... · In this lesson, you will learn how an Ultrasonic Rangefinder

ROBOTC

Ultrasonic Rangefinder • 10© Carnegie Mellon Robotics Academy / For use with VEX® Robotics Systems

Sensing

AutoAutoAutoAuto

123456789

1011121314151617181920212223242526272829303132

const tSensors rightEncoder = (tSensors) in2;const tSensors leftEncoder = (tSensors) in3; const tSensors sonarSensor = (tSensors) in5;

void moveStraight(){ if(SensorValue[leftEncoder] > SensorValue[rightEncoder]) { motor[port3] = 50; motor[port2] = 63; } if(SensorValue[leftEncoder] < SensorValue[rightEncoder]) { motor[port3] = 63; motor[port2] = 50; } if(SensorValue[leftEncoder] == SensorValue[rightEncoder]) { motor[port3] = 63; motor[port2] = 63; }}

task main(){ wait1Msec(2000); bMotorReflected[port2] = 1;

SensorValue[leftEncoder] = 0; SensorValue[rightEncoder] = 0;

while(SensorValue[sonarSensor] > 3) { moveStraight(); }}

Ultrasonic Rangefinder Forward till Near (cont.)

9o. Modify this codeReplace the generic motor-forward commands with a call to moveStraight();.

10. Download and Run.

10. Go to Compile and Download Program

Checkpoint

Your robot now runs straight until its Ultrasonic Sonar Rangefinder detects an object within 3 inches, in its forward field of view. You can change the stopping distance by changing the 3 inch “cutoff” point.

9n. Add this codeAdd these commands to reset the values of the encoders to 0.

Page 11: Ultrasonic Rangefinder Forward till Near - Carnegie Mellon...education.rec.ri.cmu.edu/downloads/vex/TRC_VEX_training_pdfs... · In this lesson, you will learn how an Ultrasonic Rangefinder

ROBOTC

Ultrasonic Rangefinder • 11© Carnegie Mellon Robotics Academy / For use with VEX® Robotics Systems

Sensing

Ultrasonic Rangefinder Forward till Near (cont.)

robot stopping in front of object similar ot mine

This is the second sensor you have programmed to use a “cutoff” value. The Encoder program ran a movement behavior until the encoder count exceeded a certain value, and this new program runs a movement behavior until the Ultrasonic Rangefinder distance goes below a certain value.

robot with encoders driving

These “cutoff” values – called thresholds – are important in robot decision-making. Thresholds are values that set a cutoff point in a range of values, so that even though there are many possible values for encoder counts or distances, every one of them will fall either below the threshold or above it. This division of the many possible values into two distinct categories (above and below the threshold) allows the robot to make a definite decision about how to proceed for any value it may encounter.

some kind of greater than less than graphic

Page 12: Ultrasonic Rangefinder Forward till Near - Carnegie Mellon...education.rec.ri.cmu.edu/downloads/vex/TRC_VEX_training_pdfs... · In this lesson, you will learn how an Ultrasonic Rangefinder

ROBOTC

Ultrasonic Rangefinder • 12© Carnegie Mellon Robotics Academy / For use with VEX® Robotics Systems

Sensing

Ultrasonic Rangefinder Forward till Near (cont.)

Ultrasonic Rangefinder values above the threshold of 3 inches made the program continue looping and moving forward. Values below the threshold caused the robot to stop. The threshold sets the point at which the robot’s behavior will change, because it marks the point at which the (condition) in the while loop (or if-statement) will change from true to false, or false to true, and thus change which lines of code will run.

The robot is now set and ready to run for any object the Ultrasonic Rangefinder might see… but what happens when it doesn’t see anything at all? The sound waves have a limited range before the echo is too soft for the sensor to pick up. In addition, some materials or surfaces can actually deflect the sound waves away from the sensor, preventing it from hearing the echo. What happens then?

26272829303132

bMotorReflected[port2] = 1;

while(SensorValue(sonarSensor) > 3) { moveStraight(); }}

robot with aimed at pillow?

11. Making sure that your robot is turned on and plugged in, open the ROBOTC Debugger and Devices windows. Run the program.

11a. Robot > DebuggerGo to Robot > Debugger to open the Program Debug window.

11b. Robot > Debug Windows > DevicesOpen the Devices window so that you can monitor the Ultrasonic Rangefinder values.

Page 13: Ultrasonic Rangefinder Forward till Near - Carnegie Mellon...education.rec.ri.cmu.edu/downloads/vex/TRC_VEX_training_pdfs... · In this lesson, you will learn how an Ultrasonic Rangefinder

ROBOTC

Ultrasonic Rangefinder • 13© Carnegie Mellon Robotics Academy / For use with VEX® Robotics Systems

Sensing

Ultrasonic Rangefinder Forward till Near (cont.)

hand holding up robot near computer

11c. Pick up the robotPick up the robot so that it doesn’t drive away.

11d. Run the program

12. Point your robot’s sensor away from any nearby objects, or toward a very soft object, like a sweater or cushion. Observe the value that the sensor gives through the ROBOTC debugger.

robot pointed at cushion or nothing or with hand di-rectly on sensor

12a. No SignalOrient your Ultrasonic Rangefinder so that it will have difficulty getting an echo back from whatever is in front of it. This may involve aiming it at something very far away, aiming it at something soft (which absorbs sound), or simply blocking the sensor with your hand at very close range.

12b. Observe sensor valueThe sonarSensor will show a value of -1 if it is unable to measure distance for any reason.

Page 14: Ultrasonic Rangefinder Forward till Near - Carnegie Mellon...education.rec.ri.cmu.edu/downloads/vex/TRC_VEX_training_pdfs... · In this lesson, you will learn how an Ultrasonic Rangefinder

ROBOTC

Ultrasonic Rangefinder • 14© Carnegie Mellon Robotics Academy / For use with VEX® Robotics Systems

Sensing

Ultrasonic Rangefinder Forward till Near (cont.)

13. Run your straight-till-near program in a place where the robot will get a “-1” sonar reading.

robot pointed down a long hallway or toward a sound-absorbing object

13a. Position the robotPlace your robot so that it faces down a very long hallway, or toward a sound-absorbing object.

switching on vex

13b. Run the robotSwitch the robot off and back on to run the program.

robot in the same location as before, different angle 13c. Observe robot behavior

The robot stops immediately, as if it were close to an object.

Checkpoint

Why would the robot act like it was close to an object when the exact opposite was true? The SensorValue of an Ultrasonic Rangefinder is returned as -1 when there is no object in range. Consider how your robot is making its decisions:

while (SensorValue[sonarSensor] > 3) { moveStraight(); }

Page 15: Ultrasonic Rangefinder Forward till Near - Carnegie Mellon...education.rec.ri.cmu.edu/downloads/vex/TRC_VEX_training_pdfs... · In this lesson, you will learn how an Ultrasonic Rangefinder

ROBOTC

Ultrasonic Rangefinder • 15© Carnegie Mellon Robotics Academy / For use with VEX® Robotics Systems

Sensing

Ultrasonic Rangefinder Forward till Near (cont.)

The robot will move straight as long as the Ultrasonic Rangefinder detects an object farther than 3 inches away.

robot 6 inches away from object similar ot mine Object at 6 in

SensorValue(sonarSensor) is 6, therefore SensorValue(sonarSensor) > 3 is true. The loop will continue looping.

robot 2 inches away from object similar ot mine Object at 2 in

SensorValue(sonarSensor) is 2, therefore SensorValue(sonarSensor) > 3 is false. The loop will end. The next portion of the program causes the robot to stop.

robot, no object in the shotNo objectSensorValue(sonarSensor) is -1, therefore SensorValue(sonarSensor) > 3 is false. The loop will end. The next portion of the program causes the robot to stop.

Page 16: Ultrasonic Rangefinder Forward till Near - Carnegie Mellon...education.rec.ri.cmu.edu/downloads/vex/TRC_VEX_training_pdfs... · In this lesson, you will learn how an Ultrasonic Rangefinder

ROBOTC

Ultrasonic Rangefinder • 16© Carnegie Mellon Robotics Academy / For use with VEX® Robotics Systems

Sensing

Ultrasonic Rangefinder Forward till Near (cont.)

14. Change the (condition) for continuing to move forward so that the robot will run while the object is detected farther than 3 in OR too far to detect.

1920212223242526272829303132

task main(){ wait1Msec(2000); bMotorReflected[port2] = 1;

SensorValue[leftEncoder] = 0; SensorValue[rightEncoder] = 0;

while(SensorValue[sonarSensor] > 3 || SensorValue[sonarSensor] < 0) { moveStraight(); }}

14a. Modify this codeAdd a second part to the condition, using an OR (||) connector.

End of Section

The new code makes the robot move straight forward whenever it is far away from an object, even if it is so far away that it cannot detect it. It will, however, also move forward if it just can’t see an object, which can have unwanted side effects. Keep this in mind as you move on to the next lesson, where you will use this behavior as the foundation for an automatic mine-grabbing function.

Page 17: Ultrasonic Rangefinder Forward till Near - Carnegie Mellon...education.rec.ri.cmu.edu/downloads/vex/TRC_VEX_training_pdfs... · In this lesson, you will learn how an Ultrasonic Rangefinder

ROBOTC

Ultrasonic Rangefinder • 17© Carnegie Mellon Robotics Academy / For use with VEX® Robotics Systems

Sensing

Ultrasonic Rangefinder Automatic Pickup

In this lesson, you will use pseudocode to plan out a program that will automatically pick up a mine in competition.

In a test program, you created a behavior that uses the Ultrasonic Rangefinder to maneuver the robot to within a specified distance of an obstacle. This is the first step in picking up the mine.

Robot stopped 3 inches from an object

However, the remaining steps are not just a matter of simple addition of code. Let’s lay out a high-level plan of what we want this program to do. We’ll simply describe the program structure in plain English, and make sure that it does what we want it to do. Since we do know the basic Control Structures, like if-statements and while loops, we can work them into our description so it more closely matches the actual program. This hybrid of plain English descriptions and code-style flow is called pseudocode, and is used extensively by programmers to help make sense and keep track of more complex programs.

First, let’s see what the “MineArmStraight” program from the Straight Button section of the Autonomy/Encoders lesson looks like in pseudocode. You will notice that pseudocode is actually less detailed and specific than the existing code. This is okay. The point of pseudocode is to make sure your program uses sound logic, and to help make its flow readable and understandable. There are no specific words that must be used, as long as all the necessary ideas and information are communicated.

function moveStraight() { if (the left encoder is ahead of the right encoder) { move the right wheel faster than the left; }

Page 18: Ultrasonic Rangefinder Forward till Near - Carnegie Mellon...education.rec.ri.cmu.edu/downloads/vex/TRC_VEX_training_pdfs... · In this lesson, you will learn how an Ultrasonic Rangefinder

ROBOTC

Ultrasonic Rangefinder • 18© Carnegie Mellon Robotics Academy / For use with VEX® Robotics Systems

Sensing

Ultrasonic Rangefinder Automatic Pickup (cont.)

function moveStraight() { if (the left encoder is ahead of the right encoder) { move the right wheel faster than the left; } if (the right encoder is ahead of the left encoder) { move the left wheel faster than the right; } if (the two encoders are exactly aligned) { move both wheels at an equal speed forward; }}

task main() { reset timer; while (less than 120 seconds have passed) { if (the automatic-straight button is pressed on the Transmitter) { move straight, accounting for encoder reset; if (starting a new “movingStraight” behavior) { reset encoders; set“movingStraight”flagtotrue; } moveStraight(); } otherwise (the auto-straight button is not pressed) { move based on transmitter sticks, accounting for encoder reset; set“movingStraight”flagtofalse; set the motors based on the Transmitter sticks; }

Page 19: Ultrasonic Rangefinder Forward till Near - Carnegie Mellon...education.rec.ri.cmu.edu/downloads/vex/TRC_VEX_training_pdfs... · In this lesson, you will learn how an Ultrasonic Rangefinder

ROBOTC

Ultrasonic Rangefinder • 19© Carnegie Mellon Robotics Academy / For use with VEX® Robotics Systems

Sensing

Ultrasonic Rangefinder Automatic Pickup (cont.)

if (the desired armDirection is UP) { if (the upward limit switch is not hit) { move arm up; } otherwise (the upward limit switch IS hit) { hold arm steady; } if (the desired armDirection is DOWN) { if (the downward limit switch is not hit) { move arm down; } otherwise (the downward limit switch IS hit) { hold arm steady; } if (the desired armDirection is STEADY) { hold arm steady; } if (the raise-arm button is pressed on the Transmitter) { set the desired armDirection to UP; } if (the lower-arm button is pressed on the Transmitter) { set the desired armDirection to DOWN; } }}

Page 20: Ultrasonic Rangefinder Forward till Near - Carnegie Mellon...education.rec.ri.cmu.edu/downloads/vex/TRC_VEX_training_pdfs... · In this lesson, you will learn how an Ultrasonic Rangefinder

ROBOTC

Ultrasonic Rangefinder • 20© Carnegie Mellon Robotics Academy / For use with VEX® Robotics Systems

Sensing

Ultrasonic Rangefinder Automatic Pickup (cont.)

Now, think about what we are trying to add. You have a separate program that makes the robot run forward until it gets close to an object. Its pseudocode looks something like this:

while (the robot is more than 3 inches away from the object) { run both motors forward; }

This isn’t really the same as what we want to do. The robot can’t grab the mine from 3 inches away, and the program doesn’t cover the grabbing part anyway. There’s another problem too, because this program relies on a while() loop, which we know causes problems when placed within another loop. Since this will be just one of many behaviors happening within a timer loop in the final program, this behavior can’t use a while() loop.

Let’s make some changes.

while if (the robot is more than 3 inches 1 inch away from the object) { go straight forward; } otherwise (the robot is 1 inch or less from the object) { stop moving; raise the arm; }

Modify this pseudocodeReplace the “while” loop with an if-else statement, so that the looping of the while() will not interfere with the overall behavior of the robot in the main function.

Modify this pseudocodeReplace the 3-inch threshold with a 1-inch threshold to allow the robot to get within the actual reach of its arm. Remember that the 1 inch is measured from the Ultrasonic Rangefinder to the object.

Add this pseudocodeIf the robot is not outside range, then it must be close enough to start picking up the object. The robot should stop moving, and raise its arm.

Page 21: Ultrasonic Rangefinder Forward till Near - Carnegie Mellon...education.rec.ri.cmu.edu/downloads/vex/TRC_VEX_training_pdfs... · In this lesson, you will learn how an Ultrasonic Rangefinder

ROBOTC

Ultrasonic Rangefinder • 21© Carnegie Mellon Robotics Academy / For use with VEX® Robotics Systems

Sensing

Ultrasonic Rangefinder Automatic Pickup (cont.)

The two behaviors called for in the 1-inch-or-closer part of that behavior are a little opaque, so let’s break them down more.

if (the robot is more than 1 inch away from the object) { go straight forward; } otherwise (the robot is 1 inch or less from the object) { stop both wheel motors; if (the up-bumper on the arm is not pressed) { move the arm upward; } otherwise (the up-bumper on the arm IS pressed) { hold the arm in place; } }

Clarify this pseudocodeThe command to stop can easily be understood as two motor commands to turn off the wheels.

Clarify this pseudocodeRaising the arm properly consists of running the arm motor, but only if it is not already at the top of its range of motion. Using the same logic as the button-based arm raising, simply move the arm if it is not at the top, and hold it steady if it is.

Page 22: Ultrasonic Rangefinder Forward till Near - Carnegie Mellon...education.rec.ri.cmu.edu/downloads/vex/TRC_VEX_training_pdfs... · In this lesson, you will learn how an Ultrasonic Rangefinder

ROBOTC

Ultrasonic Rangefinder • 22© Carnegie Mellon Robotics Academy / For use with VEX® Robotics Systems

Sensing

Ultrasonic Rangefinder Automatic Pickup (cont.)

function autoGetMine() { if (the robot is more than 1 inch away from the object) { go straight forward; } otherwise (the robot is 1 inch or less from the object) { stop both wheel motors; if (the up-bumper on the arm is not pressed) { move the arm upward; } otherwise (the up-bumper on the arm IS pressed) { hold the arm in place; } }}

Add this pseudocode“Wrap” the behavior in a function.

Let’s build this function inside the competition program where it will be used.

1. Open the “MineArmStraight” competiton program.

1a. Select File > Open and Compile

Now, this, we know how to do. Simply put the behavior in a function, and it should be ready for use.

Page 23: Ultrasonic Rangefinder Forward till Near - Carnegie Mellon...education.rec.ri.cmu.edu/downloads/vex/TRC_VEX_training_pdfs... · In this lesson, you will learn how an Ultrasonic Rangefinder

ROBOTC

Ultrasonic Rangefinder • 23© Carnegie Mellon Robotics Academy / For use with VEX® Robotics Systems

Sensing

Ultrasonic Rangefinder Automatic Pickup (cont.)

1b. Open MineArmStraight

2. Save your program as “MineArmStraightAuto”

2a. File > Save As...Select File > Save As... to save your program under a new name.

2b. Renate programGive this program the name MineArmStraightAuto.

2c. SaveClick Save.

3. Create the framework for a new function named “autoGetMine”.

161718192021222324252627

motor[port2] = 63; }}

void autoGetMine(){}

task main(){ int armDirection; bool isMovingStraight;

3. Add this codeCreate a new function, beginning with the keyword “void”, named “autoGetMine”. Leave its {body} blank for now.

Page 24: Ultrasonic Rangefinder Forward till Near - Carnegie Mellon...education.rec.ri.cmu.edu/downloads/vex/TRC_VEX_training_pdfs... · In this lesson, you will learn how an Ultrasonic Rangefinder

ROBOTC

Ultrasonic Rangefinder • 24© Carnegie Mellon Robotics Academy / For use with VEX® Robotics Systems

Sensing

Ultrasonic Rangefinder Automatic Pickup (cont.)

Checkpoint

You have an empty “autoGetMine” function in the Competition program, and a set of pseudocode describing what commands should be placed inside the function to achieve a desired behavior. Since your pseudocode was written with an eye toward the program logic, creating the actual function is simply a matter of choosing the right commands to accomplish each task in the list.

function autoGetMine() { if (the robot is more than 1 inch away from the object) { go straight forward; } otherwise (the robot is 1 inch or less from the object) { stop both wheel motors; if (the up-bumper on the arm is not pressed) { move the arm upward; } otherwise (the up-bumper on the arm IS pressed) { hold the arm in place; } }}

Start by filling in the logic of the program, the Control Statements like the while() loops and if-else statements.

void autoGetMine() { if (SensorValue(sonarSensor) > 1) { } else { if (SensorValue(upLimit)==0) { } else { } }}

Replace pseudocode logic with program logicThe if-else statement structure and (conditions) of the statements in the pseudocode can be transferred directly, substituting the appropriate sensor values and checks in the (conditions).blank for now.

Page 25: Ultrasonic Rangefinder Forward till Near - Carnegie Mellon...education.rec.ri.cmu.edu/downloads/vex/TRC_VEX_training_pdfs... · In this lesson, you will learn how an Ultrasonic Rangefinder

ROBOTC

Ultrasonic Rangefinder • 25© Carnegie Mellon Robotics Academy / For use with VEX® Robotics Systems

Sensing

Ultrasonic Rangefinder Automatic Pickup (cont.)

void autoGetMine() { if (SensorValue(sonarSensor) > 1) { moveStraight(); } else { motor[port3]=0; motor[port2]=0; if (SensorValue(upLimit)==0) { motor[port6]=31; } else { motor[port6]=0; } }}

Nested functionsNote that the moving-straight function moveStraight() is used here. As long as moveStraight() is declared earlier in the program (before this function is declared), this will not cause any problems.

Finally, fill in the remaining commands.

4. Write out the planned function in real code in the program.

if(SensorValue[leftEncoder] == SensorValue[rightEncoder]) { motor[port3] = 63; motor[port2] = 63; }}

void autoGetMine() { if (SensorValue(sonarSensor) > 1) { moveStraight(); } else { motor[port3]=0; motor[port2]=0; if (SensorValue(upLimit)==0) { motor[port6]=31; } else { motor[port6]=0; } }}

task main(){ int armDirection;

13141516171819202122232425262728293031323334353637383940414243

4. Add this codeAdd the code to the program to create the function.

Page 26: Ultrasonic Rangefinder Forward till Near - Carnegie Mellon...education.rec.ri.cmu.edu/downloads/vex/TRC_VEX_training_pdfs... · In this lesson, you will learn how an Ultrasonic Rangefinder

ROBOTC

Ultrasonic Rangefinder • 26© Carnegie Mellon Robotics Academy / For use with VEX® Robotics Systems

Sensing

Ultrasonic Rangefinder Automatic Pickup (cont.)

Checkpoint

Your new behavior is now available as a function in the program. By planning out the behavior in pseudocode, then choosing ROBOTC commands that matched the desired steps, you were able to reason from desired outcome to required code in one unbroken sequence.

6. Call the new function from within the main program whenever the last remaining button (left hand lower button) is pressed.

5a. Robot > Motors and Sensors SetupSelect Robot > Motors and Sensors Setup to open up the configuration menu.

5b. Configure the sensorSet the name of in5 to be “sonarSensor”, the type as “SONAR”, and the second port as “int1”.

5c. Click OKClick OK to finish configuring the Ultrasonic Rangefinder.

5. Use the Motors and Sensors Setup Menu to configure the Ultrasonic Rangefinder on Analog Digital Port 5, and Interrupt 1.

motor[port3] = vexRT[Ch3]; motor[port2] = vexRT[Ch2]; } if(vexRT[Ch5] == -127) { autoGetMine(); } }

motor[port3] = 0; motor[port2] = 0;}

112113114115116117118119120121122123

6a. Add this codeLike the other buttons, this button’s behavior will be handled using an if-statement inside the main loop, which checks whether the desired button is pressed or not.

6b. Add this codeIf the button is pressed, the autoGetMine() function should run. Add the function call to the if-statement’s {body}.

Page 27: Ultrasonic Rangefinder Forward till Near - Carnegie Mellon...education.rec.ri.cmu.edu/downloads/vex/TRC_VEX_training_pdfs... · In this lesson, you will learn how an Ultrasonic Rangefinder

ROBOTC

Ultrasonic Rangefinder • 27© Carnegie Mellon Robotics Academy / For use with VEX® Robotics Systems

Sensing

Ultrasonic Rangefinder Automatic Pickup (cont.)

7. Download and run the program.

robot pointed toward a mine

7b. Align the robot with a mineIn order to test the new behavior, begin by driving or placing the robot in front of a mine, a few inches away.

finger pressing

bottom ch5 button7c. Activate behaviorPress the lower left-hand button on the Transmitter to see how the robot handles the picking up task.

7a. Go to Compile and Download Program

Like most first tries, this one will not be completely successful. Run the robot long enough that you can describe the problem’s symptoms, then turn it off and proceed to the next lesson.

Program Incomplete

picture of robot not yet picking up mine

Page 28: Ultrasonic Rangefinder Forward till Near - Carnegie Mellon...education.rec.ri.cmu.edu/downloads/vex/TRC_VEX_training_pdfs... · In this lesson, you will learn how an Ultrasonic Rangefinder

ROBOTC

Ultrasonic Rangefinder • 28© Carnegie Mellon Robotics Academy / For use with VEX® Robotics Systems

Sensing

Ultrasonic Rangefinder Automatic Pickup (cont.)

End of Section

You formulated an idea of what this program should do, implemented it in pseudocode, and began testing it. Testing, however, showed that there are still bugs to be worked out in the details of the code. This is to be expected: pseudocode deals with high-level ideas and organization, but the low-level workings of the program often require additional support or tuning. The goal of testing, a critical part of any project, is to discover where the fine-tuning needs to happen.

Proceed to the next lesson to begin the debugging process.

Page 29: Ultrasonic Rangefinder Forward till Near - Carnegie Mellon...education.rec.ri.cmu.edu/downloads/vex/TRC_VEX_training_pdfs... · In this lesson, you will learn how an Ultrasonic Rangefinder

ROBOTC

Ultrasonic Rangefinder • 29© Carnegie Mellon Robotics Academy / For use with VEX® Robotics Systems

Sensing

Ultrasonic Rangefinder Debugging the Behavior

In this lesson, you will examine the robot’s behavior to identify and fix the bugs in its program.

picture of button on back of Transmitter, drawing of a key, checkmark on picture

Button Start

picture of Transmitter be-ing held in background while robot is “moving” in foreground, checkmark on picture

Manual Driving

(picture of robot from side, showing arm clearly, arced double-headed arrow in-dicating arm movement in both directions, checkmark on picture

Arm Control

Page 30: Ultrasonic Rangefinder Forward till Near - Carnegie Mellon...education.rec.ri.cmu.edu/downloads/vex/TRC_VEX_training_pdfs... · In this lesson, you will learn how an Ultrasonic Rangefinder

ROBOTC

Ultrasonic Rangefinder • 30© Carnegie Mellon Robotics Academy / For use with VEX® Robotics Systems

Sensing

picture of robot from rear, straight movement indicated with perspective-correct ar-row on ground in front of robot, checkmark on picture

Automatic Straight

Ultrasonic Rangefinder Debugging the Behavior (cont.)

Let’s look at the robot’s behavior. It drives okay, and all the old functions still work. Arm up, arm down, automatic straight... but when we try to apply the robot’s new autoGetMine behavior, what comes out is stuttering and jerky.

[Picture of robot near mine, autoGetMine button held, dotted direction arrow with ? marker, crossout mark in cor-ner of picture where check-mark would go

finger pressing

bottom ch5 button

Page 31: Ultrasonic Rangefinder Forward till Near - Carnegie Mellon...education.rec.ri.cmu.edu/downloads/vex/TRC_VEX_training_pdfs... · In this lesson, you will learn how an Ultrasonic Rangefinder

ROBOTC

Ultrasonic Rangefinder • 31© Carnegie Mellon Robotics Academy / For use with VEX® Robotics Systems

Sensing

Ultrasonic Rangefinder Debugging the Behavior (cont.)

Using the Debugger

0.1a Lift robot off table “Block up” the robot by placing it on top of a tall object so that its wheels do not reach the ground.

0.1b Attach cable The robot must be connected to the computer through the Programming Cable in order for the debugger to monitor it.

0.1c Run the program Run the program by pressing the Start button in ROBOTC, or by toggling the power off and back on, on the robot.

0.1 (Optional) Use the ROBOTC real-time debugger to track down the problem.

Page 32: Ultrasonic Rangefinder Forward till Near - Carnegie Mellon...education.rec.ri.cmu.edu/downloads/vex/TRC_VEX_training_pdfs... · In this lesson, you will learn how an Ultrasonic Rangefinder

ROBOTC

Ultrasonic Rangefinder • 32© Carnegie Mellon Robotics Academy / For use with VEX® Robotics Systems

Sensing

Ultrasonic Rangefinder Debugging the Behavior (cont.)

Using the Debugger (cont.)

0.1d Open debugger windows If the debugger windows are not showing at all, open them by going to Robot > Debugger. Some of the additional debugger windows may not show up, but we do not need them right now.

0.1e “Trigger” the robot Press the top button on the left-hand side of the Transmitter to signal your robot to start the main body of the program.

0.1f Step through program Press the Step button on the Program Debug window to run your program one line at a time. The line in your main ROBOTC code window that highlights in yellow is the next one that will run when you press Step.

Pay close attention to which lines in the program are run, and which are skipped (never turn yellow). In particular, look for lines that control motors 2 and 3, the drive motors.

Page 33: Ultrasonic Rangefinder Forward till Near - Carnegie Mellon...education.rec.ri.cmu.edu/downloads/vex/TRC_VEX_training_pdfs... · In this lesson, you will learn how an Ultrasonic Rangefinder

ROBOTC

Ultrasonic Rangefinder • 33© Carnegie Mellon Robotics Academy / For use with VEX® Robotics Systems

Sensing

Ultrasonic Rangefinder Debugging the Behavior (cont.)

Checkpoint

By stepping through your code, you should notice that the robot is running the lines in the code that set the motor powers based on Transmitter input. [code window with yellow highlight: motor[port3]=vexRT[ch3]; and ch2]

Since you are not holding down any of the automatic behavior buttons, this is the desired behavior.

Using the Debugger (cont.)

0.1g Engage autoGetMine behavior Press and hold the bottom left-hand button on the Transmitter. This is the signal that we programmed to activate the autoGetMine function, which is the place in the program where the malfunction seems to be occurring.

0.1h Step through program While continuing to hold the Transmitter button for autoGetMine, step through the program again. Pay attention to lines where the motor power is set for ports 2 and 3.

End of Optional Section

This time, four different lines are being reached that attempt to set the powers of the drive motors on each pass through the main program loop. [code window showing the motor commands inside autoGetMine, then a wavy space, then the radio control motor commands again] This means that each motor is set twice, and it seems that it is being set to two different values each time (once to 63 by the autoGetMine function, and then to a Transmitter-defined value by the main loop).

Page 34: Ultrasonic Rangefinder Forward till Near - Carnegie Mellon...education.rec.ri.cmu.edu/downloads/vex/TRC_VEX_training_pdfs... · In this lesson, you will learn how an Ultrasonic Rangefinder

ROBOTC

Ultrasonic Rangefinder • 34© Carnegie Mellon Robotics Academy / For use with VEX® Robotics Systems

Sensing

Ultrasonic Rangefinder Debugging the Behavior (cont.)

We have identified the source of the conflict: two different parts of the code are fighting for control of the motors, and negating each other’s efforts. The jerky motion of the robot is caused by the back-and-forth between the two sets of commands that are trying to take control. Return to the main lesson sequence to fix the problem.

Using the Debugger (cont.)

The robot is running both the autoGetMine motor commands and the Radio Control motor commands while the autoGetMine button is held on the Transmitter. The Radio Control commands should not run while this button is held. We must modify the program’s logic so that it will only run the Radio Control joystick behaviors if neither of the autonomous-assist behaviors are engaged (right now, it only checks whether the moveStraight is being held).

1. Move the autoGetMine if-statement inside the “else” portion of the moveStraight if-else statement.

113114115116117118119120121122123124125

1a. Highlight this codeSelect the autoGetMine if-statement.

1b. Cut this codeSelect Edit > Cut to move the highlighted code to the clipboard.

motor[port3] = vexRT[Ch3]; motor[port2] = vexRT[Ch2]; } if(vexRT[Ch5] == -127) { autoGetMine(); }

}

motor[port3] = 0; motor[port2] = 0;}

Page 35: Ultrasonic Rangefinder Forward till Near - Carnegie Mellon...education.rec.ri.cmu.edu/downloads/vex/TRC_VEX_training_pdfs... · In this lesson, you will learn how an Ultrasonic Rangefinder

ROBOTC

Ultrasonic Rangefinder • 35© Carnegie Mellon Robotics Academy / For use with VEX® Robotics Systems

Sensing

else { moveStraight(); } } else { | isMovingStraight = false; motor[port3] = vexRT[Ch3]; motor[port2] = vexRT[Ch2]; }

}

motor[port3] = 0; motor[port2] = 0;}

105106107108109110111112113114115116117118119120121122

Ultrasonic Rangefinder Debugging the Behavior (cont.)

1d. Paste

1c. Place your cursor hereMake a new line for the if-statement to go and place your cursor there.

2. Add an “else” portion to the autoGetMine if-statement, and move the Radio Control commands inside.

else { moveStraight(); } } else { if(vexRT[Ch5] == -127) { autoGetMine(); } else { isMovingStraight = false; motor[port3] = vexRT[Ch3]; motor[port2] = vexRT[Ch2]; } }

}

105106107108109110111112113114115116117118119120121122123124125

2a. Modify this codeAdd an “else” portion to convert the autoGetMine if-statement to an if-else.

2b. Modify this codeMake sure the old Radio Control commands are inside the “else” portion of the if-else. Add additional tabs if necessary to update the whitespace.

Page 36: Ultrasonic Rangefinder Forward till Near - Carnegie Mellon...education.rec.ri.cmu.edu/downloads/vex/TRC_VEX_training_pdfs... · In this lesson, you will learn how an Ultrasonic Rangefinder

ROBOTC

Ultrasonic Rangefinder • 36© Carnegie Mellon Robotics Academy / For use with VEX® Robotics Systems

Sensing

Ultrasonic Rangefinder Debugging the Behavior (cont.)

3. Download and run to test your code.

picture of a the robot lined up with a mine, just a few inches away

finger pressing

bottom ch5 button

3a. Go to Compile and Download Program

3b. Align the robot with a mineDrive or place the robot in front of a mine, a few inches away.

3c. Activate behaviorPress the lower left-hand button on the Transmitter to see how the robot handles the picking up task.

Pseudocode

Check whether (the automatic-straight button is pressed on the Transmitter)… if it is,{ move straight, accounting for encoder reset;}otherwise (the auto-straight button is not pressed){ check whether (the auto-grab button is pressed on the Transmitter)… if it is, { autoGetMine(); } otherwise (the auto-grab button is not pressed on the Transmitter… AND we already know the automatic-straight button is not pressed) { move based on transmitter sticks, accounting for encoder reset; }}

For reference, the pseudocode to describe this part of the function would now look like:

Page 37: Ultrasonic Rangefinder Forward till Near - Carnegie Mellon...education.rec.ri.cmu.edu/downloads/vex/TRC_VEX_training_pdfs... · In this lesson, you will learn how an Ultrasonic Rangefinder

ROBOTC

Ultrasonic Rangefinder • 37© Carnegie Mellon Robotics Academy / For use with VEX® Robotics Systems

Sensing

It is interesting to note that the original Radio Control behaviors are being made more and more secondary to the newly-introduced autonomous assistance behaviors. Partly, this is because this is the way the program needs to be structured: the autonomous behaviors cannot function correctly if operator input is being accepted at the same time. Partly, it reflects a more general trend in the operation of the robot itself: as robots become more advanced, it is not unusual for autonomous operation to replace more and more of the mundane aspects of human control.

Your little robot is growing up, but there are still many obstacles left to be overcome. Proceed to the next steps!

Pseudocode (cont.)

Ultrasonic Rangefinder Debugging the Behavior (cont.)

Checkpoint

The joysticks will no longer be used in motor commands while either of the autonomous-assist functions is running. Testing the robot on the course, however, reveals two new problems: first, that the robot is now suffering from the off-course problem that the moveStraight originally had when used in conjunction with the Radio Control commands – that is, it is not resetting the encoders before engaging the autoGetMine behavior. Second, and perhaps more troubling, the robot, now moving at the correct autoGetMine speed, is going too fast.

4. Modify the code inside of the the autoGetMine if-else statement to check and set isMovingStraight.

else { moveStraight(); } } else { if(vexRT[Ch5] == -127) { if(isMovingStraight == false) { SensorValue[leftEncoder] = 0; SensorValue[rightEncoder] = 0; isMovingStraight = true; } else { autoGetMine(); } } else { isMovingStraight = false; motor[port3] = vexRT[Ch3]; motor[port2] = vexRT[Ch2]; }

105106107108109110111112113114115116117118119120121122123124125126127128129130

4. Modify this codeIf the autoGetMine button is pressed, then check whether the program should reset the encoders to start a new moving-straight behavior as part of autoGetMine. Reset if necessary, otherwise go ahead (or continue) with the autoGetMine behavior.

Page 38: Ultrasonic Rangefinder Forward till Near - Carnegie Mellon...education.rec.ri.cmu.edu/downloads/vex/TRC_VEX_training_pdfs... · In this lesson, you will learn how an Ultrasonic Rangefinder

ROBOTC

Ultrasonic Rangefinder • 38© Carnegie Mellon Robotics Academy / For use with VEX® Robotics Systems

Sensing

Ultrasonic Rangefinder Debugging the Behavior (cont.)

Checkpoint

And now let’s address the second problem. The robot makes a valiant effort to pick up the mine, but ultimately barrels into it. With the signal to stop coming only after the robot is within one inch of the mine, it cannot react in time, and the robot crashes on through. Clearly, the robot needs to slow down.

picture of a the robot and a knocked over mine in front of it.

The program uses the moveStraight() function to move straight during the autoGet behavior. moveStraight, however runs at nearly full speed. We could change the speed in that function, but then all the other parts of the program that use moveStraight(), such as the upper-left-hand button behavior, would also be affected. In fact, we just went through the trouble of making that part go faster.

void moveStraight(){ if(SensorValue[leftEncoder] > SensorValue[rightEncoder]) { motor[port3] = 50; motor[port2] = 63; } if(SensorValue[leftEncoder] < SensorValue[rightEncoder]) { motor[port3] = 63; motor[port2] = 50; } if(SensorValue[leftEncoder] == SensorValue[rightEncoder]) { motor[port3] = 63; motor[port2] = 63; }}

Many similar behaviors are just that: similar, but not identical. Functions must be adapted to either recognize the similarities or work around the differences. Recognizing the similarities and integrating them into a more comprehensive type of function can be accomplished through the addition of parameters, which let you create “configurable” functions in your program. This approach is longer, but more sound. You can learn more about parameters and parameterized functions in the supplemental guide on parameters.

Page 39: Ultrasonic Rangefinder Forward till Near - Carnegie Mellon...education.rec.ri.cmu.edu/downloads/vex/TRC_VEX_training_pdfs... · In this lesson, you will learn how an Ultrasonic Rangefinder

ROBOTC

Ultrasonic Rangefinder • 39© Carnegie Mellon Robotics Academy / For use with VEX® Robotics Systems

Sensing

Ultrasonic Rangefinder Debugging the Behavior (cont.)

For the time being, though, we have a task that we need to complete. We can implement a short-term solution now, and come back later to upgrade it to a better long-term solution. For now, let’s simply make a new function that will do the moving-straight behavior, but at a lower speed.

5. Create a new function called slowStraight(). It will be identical to the existing moveStraight(), but with lower motor power levels.

motor[port2] = 63; }}

void slowStraight(){

}

void autoGetMine() { if (SensorValue(sonarSensor) > 1)

161718192021222324252627

5a. Add this codeCreate the framework of the function.

Auto123456789

10111213141516171819

5b. Highlight this codeHighlight the body of the existing moveStraight() function in preparation to copy it.

void moveStraight(){ if(SensorValue[leftEncoder] > SensorValue[rightEncoder]) { motor[port3] = 50; motor[port2] = 63; } if(SensorValue[leftEncoder] < SensorValue[rightEncoder]) { motor[port3] = 63; motor[port2] = 50; } if(SensorValue[leftEncoder] == SensorValue[rightEncoder]) { motor[port3] = 63; motor[port2] = 63; }}

5c. Copy this codeSelect Edit > Copy to copy the highlighted code to the clipboard.

Page 40: Ultrasonic Rangefinder Forward till Near - Carnegie Mellon...education.rec.ri.cmu.edu/downloads/vex/TRC_VEX_training_pdfs... · In this lesson, you will learn how an Ultrasonic Rangefinder

ROBOTC

Ultrasonic Rangefinder • 40© Carnegie Mellon Robotics Academy / For use with VEX® Robotics Systems

Sensing

Ultrasonic Rangefinder Debugging the Behavior (cont.)

motor[port2] = 63; }}

void slowStraight(){ |}

void autoGetMine() { if (SensorValue(sonarSensor) > 1)

161718192021222324252627

5d. Place your cursor here

5e. PasteSelect Edit > Paste to paste the code from the clipboard.

motor[port2] = 63; }}

void slowStraight(){ if(SensorValue[leftEncoder] > SensorValue[rightEncoder]) { motor[port3] = 25; motor[port2] = 31; } if(SensorValue[leftEncoder] < SensorValue[rightEncoder]) { motor[port3] = 31; motor[port2] = 25; } if(SensorValue[leftEncoder] == SensorValue[rightEncoder]) { motor[port3] = 31; motor[port2] = 31; }}

1617181920212223242526272829303132333435363738

5f. Modify this codeChange the motor powers in the behavior to lower values.

Page 41: Ultrasonic Rangefinder Forward till Near - Carnegie Mellon...education.rec.ri.cmu.edu/downloads/vex/TRC_VEX_training_pdfs... · In this lesson, you will learn how an Ultrasonic Rangefinder

ROBOTC

Ultrasonic Rangefinder • 41© Carnegie Mellon Robotics Academy / For use with VEX® Robotics Systems

Sensing

6. Change the autoGetMine() function to use the new slowStraight() function instead of the moveStraight() function.

Ultrasonic Rangefinder Debugging the Behavior (cont.)

void autoGetMine(){ if (SensorValue(sonarSensor) > 1) { slowStraight(); } else { motor[port3]=0; motor[port2]=0; if (SensorValue(upLimit)==0) { motor[port6]=31; } else { motor[port6]=0; } }}

38394041424344454647484950515253545556575859

6. Modify this codeChange the function call from moveStraight() to slowStraight().

7. Download and run.

picture of a the robot lined up with a mine, just a few inches away

finger pressing

bottom ch5 button

7a. Go to Compile and Download Program

7b. Align the robot with a mineDrive or place the robot in front of a mine, a few inches away.

7c. Activate behaviorPress the lower left-hand button on the Transmitter to see how the robot handles the picking up task.

Page 42: Ultrasonic Rangefinder Forward till Near - Carnegie Mellon...education.rec.ri.cmu.edu/downloads/vex/TRC_VEX_training_pdfs... · In this lesson, you will learn how an Ultrasonic Rangefinder

ROBOTC

Ultrasonic Rangefinder • 42© Carnegie Mellon Robotics Academy / For use with VEX® Robotics Systems

Sensing

Ultrasonic Rangefinder Debugging the Behavior (cont.)

Checkpoint

The robot, properly aligned and slowed down, can now move up to the mine and almost pick it up. The arm, however, seems to be exhibiting the same confused behavior as the drive motors did earlier. Most likely, it is for a similar reason...

Using the Debugger (2)

0.7a Lift robot off table “Block up” the robot by placing it on top of a tall object so that its wheels do not reach the ground.

0.7b Attach cable The robot must be connected to the computer through the Programming Cable in order for the debugger to monitor it.

7.1 (Optional) Use the ROBOTC real-time debugger to track down the problem.

Page 43: Ultrasonic Rangefinder Forward till Near - Carnegie Mellon...education.rec.ri.cmu.edu/downloads/vex/TRC_VEX_training_pdfs... · In this lesson, you will learn how an Ultrasonic Rangefinder

ROBOTC

Ultrasonic Rangefinder • 43© Carnegie Mellon Robotics Academy / For use with VEX® Robotics Systems

Sensing

Ultrasonic Rangefinder Debugging the Behavior (cont.)

Using the Debugger (2) (cont.)

7.1d Open debugger windows If the debugger windows are not showing at all, open them by going to Robot > Debugger. Some of the additional debugger windows may not show up, but we do not need them right now.

7.1e “Trigger” the robot Press the top button on the left-hand side of the Transmitter to signal your robot to start the main body of the program.

7.1c Run the program Run the program by pressing the Start button in ROBOTC, or by toggling the power off and back on, on the robot.

Page 44: Ultrasonic Rangefinder Forward till Near - Carnegie Mellon...education.rec.ri.cmu.edu/downloads/vex/TRC_VEX_training_pdfs... · In this lesson, you will learn how an Ultrasonic Rangefinder

ROBOTC

Ultrasonic Rangefinder • 44© Carnegie Mellon Robotics Academy / For use with VEX® Robotics Systems

Sensing

Ultrasonic Rangefinder Debugging the Behavior (cont.)

Using the Debugger (2) (cont.)

7.1h Step through program While continuing to hold the Transmitter button for autoGetMine, step through the program again. Pay attention to lines where the motor power is set for port 6, the arm motor.

7.1g Engage autoGetMine behavior Press and hold the bottom left-hand button on the Transmitter. This is the signal that we programmed to activate the autoGetMine function, which is the place in the program where the malfunction seems to be occurring.

7.1f Move robot into pickup position We want to see what’s happening when the robot is trying to pick up the mine, so place it in a position where it will attempt to do so.

Page 45: Ultrasonic Rangefinder Forward till Near - Carnegie Mellon...education.rec.ri.cmu.edu/downloads/vex/TRC_VEX_training_pdfs... · In this lesson, you will learn how an Ultrasonic Rangefinder

ROBOTC

Ultrasonic Rangefinder • 45© Carnegie Mellon Robotics Academy / For use with VEX® Robotics Systems

Sensing

Using the Debugger (2) (cont.)

7.1j Release autoGetMine button Release the autoGetMine button and watch what the arm does.

7.1i End Step mode Press the “Resume” button on the Program Debug window to resume normal robot operation.

Ultrasonic Rangefinder Debugging the Behavior (cont.)

Checkpoint

Again, two different lines are being reached that attempt to set the powers of the arm motor on each pass through the main program loop. [code window showing the motor commands inside autoGetMine, then a wavy space, then the armDirection code] Since the armDirection code is not checking whether or not an autonomous behavior is running, it will try to run the motors at the same time. However, the problem runs deeper this time...

Page 46: Ultrasonic Rangefinder Forward till Near - Carnegie Mellon...education.rec.ri.cmu.edu/downloads/vex/TRC_VEX_training_pdfs... · In this lesson, you will learn how an Ultrasonic Rangefinder

ROBOTC

Ultrasonic Rangefinder • 46© Carnegie Mellon Robotics Academy / For use with VEX® Robotics Systems

Sensing

Using the Debugger (2) (cont.)

Ultrasonic Rangefinder Debugging the Behavior (cont.)

7.1k Step through program Step through the program again to see which line is making the arm drop.

End of Optional Section

The robot also has a problem with dropping the arm after the autoGetMine behavior ends. The culprit appears to be the armDirection code again... but this time for a legitimate reason. When there is no autonomous-assist behavior in effect, the armDirection code should be controlling the arm... or should it? Return to the main lesson sequence to fix the problem.

The parts of the code that check armDirection are simply not cooperating with the autoGetMine behavior. They run while the autonomous-assist function is running, and they take back control with undesired results after the autoGetMine function is done! But they should continue to run while the moveStraight behavior is running... so moving them inside the if-else statements would cause problems as well.

some graphic illustrating conflict be-tween autogetmine and movestraight

Furthermore, even if we were to change the armDirection checking to be disabled while the autonomous behaviors are in effect, the arm would still snap to the up or down position (whichever was set) after the autoGetMine button is released. If the robot is carrying a mine as autoGetMine ends, this will cause the robot to drop it.

Page 47: Ultrasonic Rangefinder Forward till Near - Carnegie Mellon...education.rec.ri.cmu.edu/downloads/vex/TRC_VEX_training_pdfs... · In this lesson, you will learn how an Ultrasonic Rangefinder

ROBOTC

Ultrasonic Rangefinder • 47© Carnegie Mellon Robotics Academy / For use with VEX® Robotics Systems

Sensing

Ultrasonic Rangefinder Debugging the Behavior (cont.)

Fortunately, there is an easy solution which takes care of both problems we have noted. We will simply define a new possible value for the armDirection: 100. A value of 100 will indicate that the arm should simply not be touched unless it is hitting one of the limit switches. If the autoGetMine button sets the armDirection to 100 when it runs, the other arm commands will know not to try to control the arm until an operator command sets the direction to -1 or 1 again .

8. Add an if-statement to the armDirection section that checks for the armDirection value 100.

if(armDirection == 0) { motor[port6] = 0; } if(armDirection == 100) { if(SensorValue(downLimit)==1 || SensorValue(upLimit)==1) { motor[port6] = 0; } }

if(vexRT[Ch6] == 127) { armDirection = 1; }

100101102103104105106107108109110111112113114115116117118

8. Add this codeThe arm should stop if it has reached either of the two limit switches, but do nothing otherwise.

9. Change the autoGetMine button behavior to also set the armDirection to 100.

{ if(vexRT[Ch5] == -127) { if(isMovingStraight == false) { SensorValue[leftEncoder] = 0; SensorValue[rightEncoder] = 0; isMovingStraight = true; } else { armDirection = 100; autoGetMine(); } }

136137138139140141142143144145146147148149150151

9. Add this codeSet the armDirection to 100 when the button is pressed so the regular Radio Control code will know not to interfere.

Page 48: Ultrasonic Rangefinder Forward till Near - Carnegie Mellon...education.rec.ri.cmu.edu/downloads/vex/TRC_VEX_training_pdfs... · In this lesson, you will learn how an Ultrasonic Rangefinder

ROBOTC

Ultrasonic Rangefinder • 48© Carnegie Mellon Robotics Academy / For use with VEX® Robotics Systems

Sensing

Ultrasonic Rangefinder Debugging the Behavior (cont.)

10. Download and run.

picture of a the robot lined up with a mine, just a few inches away

finger pressing

bottom ch5 button

10a. Go to Compile and Download Program

10b. Align the robot with a mineDrive or place the robot in front of a mine, a few inches away.

10c. Activate behaviorPress the lower left-hand button on the Transmitter to see how the robot handles the picking up task.

End of Section

Your robot, with the conflicts between its autonomous-assist and basic Radio Control code resolved, can now take care of the pickup task for you. This is a great help in situations where the robot has a better “view” of the situation than the human operator. The robot uses its own on-board sensors, including the Ultrasonic Rangefinder and the Limit Switch, to safely maneuver into position and and pick up the ball.

picture of the robot picking up the mine from the post

Page 49: Ultrasonic Rangefinder Forward till Near - Carnegie Mellon...education.rec.ri.cmu.edu/downloads/vex/TRC_VEX_training_pdfs... · In this lesson, you will learn how an Ultrasonic Rangefinder

ROBOTC

Ultrasonic Rangefinder • 49© Carnegie Mellon Robotics Academy / For use with VEX® Robotics Systems

Sensing

Ultrasonic Rangefinder Debugging the Behavior (cont.)

if (the robot is more than 1 inch away from the object) { go straight forward;}otherwise (the robot is 1 inch or less from the object, OR the sensor value is -1 (error)) { if (the sensor value is -1 (error)) { stop moving; } otherwise (the robot is 1 inch or less away from the object, and not reporting an error) { stop moving; raise the arm; }}

Finally, note that the (condition) of the distance-checking behavior inside the autoGetMine() function does not include the “too far to see” -1 value that we took care to handle in the previous section. Think carefully about how the robot SHOULD behave when it can’t see an object in front of it… would you want it to move, would you want it to stop and raise the arm? Would you rather it do something different altogether… and if so, how would you program the robot to check for this additional possibility?

You have begun to add serious autonomous control to your program. The robot is now capable of performing a significant part of the challenge task on its own with human assistance only needed to set up the initial positioning. The final step will be to hand over full control of your robot to the program during the 20-second Autonomous Period, and see how well you’ve really taught the robot.

Fine Tuning

Page 50: Ultrasonic Rangefinder Forward till Near - Carnegie Mellon...education.rec.ri.cmu.edu/downloads/vex/TRC_VEX_training_pdfs... · In this lesson, you will learn how an Ultrasonic Rangefinder

ROBOTC

Ultrasonic Rangefinder • 50© Carnegie Mellon Robotics Academy / For use with VEX® Robotics Systems

Sensing

Ultrasonic Rangefinder Autonomous Period

In this lesson, you will learn about the Autonomous Period, and how its scale of “autonomy” is different from your previous autonomous behaviors.

The final test is to let your robot go on its own, giving it the opportunity to score nearly triple points during the Autonomous Period under its own power and direction. Recall that the Autonomous Period is a special 20-second period at the beginning of the match where the robot will attempt to score without human assistance.

Autonomous Period (20 Seconds)

Radio Control Period (100 Seconds)

Competition Time Associated Behaviors

Autonomous1. Robot Selects2.

Autonomous1. Direct Control 2. Operator Selects3.

0

20

120

“Autonomous Period” and “autonomous behaviors” sound related, but refer to two significantly different aspects of the robot that will be made “autonomous”.

The “autonomous” in autonomous behaviors refers to the fact that the robot is carrying out a sequence of actions under its own control, rather than through an intensive series of direct commands by the human operator. The autoGetMine() function is a good example where the execution of a behavior is handled by the robot, as opposed to the same task being done by a human in earlier programs.

void autoGetMine(){ if (SensorValue(sonarSensor) > 1) { slowStraight(); } else { motor[port3]=0; motor[port2]=0; if (SensorValue(upLimit)==0) { motor[port6]=31; } else

38394041424344454647484950515253

Page 51: Ultrasonic Rangefinder Forward till Near - Carnegie Mellon...education.rec.ri.cmu.edu/downloads/vex/TRC_VEX_training_pdfs... · In this lesson, you will learn how an Ultrasonic Rangefinder

ROBOTC

Ultrasonic Rangefinder • 51© Carnegie Mellon Robotics Academy / For use with VEX® Robotics Systems

Sensing

Ultrasonic Rangefinder Autonomous Period (cont.)

The “autonomous” in Autonomous Period, on the other hand, refers to the robot’s role as the overall planner and decision-maker in addition to its role in autonomously carrying out the behaviors selected. When pressing a button to engage the autoGetMine() function, the human operator was making the decision about what behavior to run. By contrast, the Autonomous Period will give that responsibility to the robot, removing the human from the loop entirely. No doubt the robot will choose to use the already-programmed behaviors to complete the actual tasks, but the decisions about when to run each behavior will be made by the robot during the Autonomous Period.

picture of the robot navigat-ing the board, maybe with a question mark grphic over top of the VEX

Right now, your robot has no code to handle the Autonomous Period. It must be programmed to observe a period of time at the beginning of its run where it must move itself without human input, and then switch over after the appropriate amount of time.

different picture of the robot navigating the board, maybe with a timer graphic

Remember, the Autonomous Period is 20 seconds at the beginning of the program. A Transmitter signal may be used to signal the start of the period, but no input may be given after that point. After the 20 seconds have elapsed, the Competition referees will tally the Autonomous Period score, and then a Transmitter signal can be used to start the 100-second Radio Control Period.

Page 52: Ultrasonic Rangefinder Forward till Near - Carnegie Mellon...education.rec.ri.cmu.edu/downloads/vex/TRC_VEX_training_pdfs... · In this lesson, you will learn how an Ultrasonic Rangefinder

ROBOTC

Ultrasonic Rangefinder • 52© Carnegie Mellon Robotics Academy / For use with VEX® Robotics Systems

Sensing

Ultrasonic Rangefinder Full Program

In this lesson, you will revisit a very early lesson about Behaviors and programmatic thinking, and use those principles to plan and write the last remaining pieces of the full competition program.

Consider where we are now. The code you have written is dedicated to providing the best possible performance during the Radio Control Period. When we initially talked about the Fundamentals of Programming, we said that complex programs are built out of smaller, simpler ones. By simply changing our perspective, we can see what we have in context, and what needs to be done next.

Program

Autonomous Period Remote Control Period

Wait for starting button press

Autonomous Period timer loop

Stop Wait for starting button press

Radio Control timer loop

Stop

Drive up to mine

Pick up mine

Take mine to disposal bin

Set arm motor based on buttons, unless autonomous-assist is/was recently in effect

Take care of any full-autonomy assistance functions that are being requested

Handle manual driving commands if no full-autonomy functions are in use

Automatic Straight, if requested

Automatic Grab, if requested

Set driving motors based on joysticks

Old task main()

New task main()

This is a pseudocode plan for the entire program, but organized into a chart that shows which behaviors are parts of others. It doesn’t go all the way down to the most specific levels, but as you can see, it’s pretty clear that what we do have done is the Radio Control Period code. Right now, it’s sitting in task main(), but if we were to zoom out our perspective to consider the whole task, we see that it’s really just going to be another function within task main, and task main must handle both the Autonomous and Radio Control Periods.

Page 53: Ultrasonic Rangefinder Forward till Near - Carnegie Mellon...education.rec.ri.cmu.edu/downloads/vex/TRC_VEX_training_pdfs... · In this lesson, you will learn how an Ultrasonic Rangefinder

ROBOTC

Ultrasonic Rangefinder • 53© Carnegie Mellon Robotics Academy / For use with VEX® Robotics Systems

Sensing

Therefore, we need to:Move the Radio Control behaviors to a function, rather than taking up the entirety of task • main()Add the Autonomous Period behaviors into another function• Modify task main to correctly manage the time limits on both functions•

Let’s begin.

Ultrasonic Rangefinder Full Program (cont.)

1. Make sure that the “MineArmStraightAuto” program is open.

1a. File > Open and Compile

1b. Open the programSelect the “MineArmStraightAuto” program and open it.

2. Save the program as “MinePeriods” before making changes.

2a. File > Save As...

12. Rename the programSave the program under the name “Mine Periods”.

Page 54: Ultrasonic Rangefinder Forward till Near - Carnegie Mellon...education.rec.ri.cmu.edu/downloads/vex/TRC_VEX_training_pdfs... · In this lesson, you will learn how an Ultrasonic Rangefinder

ROBOTC

Ultrasonic Rangefinder • 54© Carnegie Mellon Robotics Academy / For use with VEX® Robotics Systems

Sensing

Ultrasonic Rangefinder Full Program (cont.)

3. Create functions for both Radio Control and Autonomous Period code. Remember, “Autonomous Period” is not the same as “autonomous behaviors,” although they will overlap.

else { motor[port6]=0; } }}

void autonomousPeriodBehaviors(){}

void radioControlPeriodBehaviors(){}

task main(){ int armDirection; bool isMovingStraight;

53545556575859606162636465666768697071

3a. Add this codeCreate the framework for the Autonomous Period function.

3b. Add this codeCreate the framework for the Radio Control Period function.

4. Examine the current task main. Identify the portion of the code which should properly be part of the “radioControlPeriod” function. Move that section of code into the function you created.

77787980818283848586878889909192

158159160161162163164165166167168169170171

bMotorReflected[port2] = 1;

armDirection = 0; isMovingStraight = false; ClearTimer(T1); while(time10[T1] < 12000) {

if(armDirection == 1) { if(SensorValue(upLimit) == 0) { motor[port6] = 31; } else

else { isMovingStraight = false; motor[port3] = vexRT[Ch3]; motor[port2] = vexRT[Ch2]; } }

}

motor[port3] = 0; motor[port2] = 0;}

4a. Highlight this codeThe code inside the “Radio Control Timer Loop” is the best match for the function code. Select the appropriate code inside the timer while() loop.

Page 55: Ultrasonic Rangefinder Forward till Near - Carnegie Mellon...education.rec.ri.cmu.edu/downloads/vex/TRC_VEX_training_pdfs... · In this lesson, you will learn how an Ultrasonic Rangefinder

ROBOTC

Ultrasonic Rangefinder • 55© Carnegie Mellon Robotics Academy / For use with VEX® Robotics Systems

Sensing

Ultrasonic Rangefinder Full Program (cont.)

4b. Edit > Cut

}}

void autonomousPeriodBehaviors(){}

void radioControlPeriodBehaviors(){ |}

task main(){ int armDirection; bool isMovingStraight;

53545556575859606162636465666768697071

4c. Place cursor herePlace your cursor between the braces of the radioControlPeriodBehaviors() function.

4d. Edit > Paste

Checkpoint

Trying to compile the code at this point will result in a long list of errors [picture of failed compile errors, highlight the undefined variable errors]. The biggest source of these errors is “undefined variables”. According to ROBOTC, the variables you’re using in the radioControlPeriodBehaviors() function don’t exist! But, they’re still declared in task main, so why wouldn’t they exist?

Page 56: Ultrasonic Rangefinder Forward till Near - Carnegie Mellon...education.rec.ri.cmu.edu/downloads/vex/TRC_VEX_training_pdfs... · In this lesson, you will learn how an Ultrasonic Rangefinder

ROBOTC

Ultrasonic Rangefinder • 56© Carnegie Mellon Robotics Academy / For use with VEX® Robotics Systems

Sensing

Ultrasonic Rangefinder Full Program (cont.)

The problem is not that they variables don’t exist, it’s that they don’t exist in the right context, or scope. Variables in ROBOTC are limited in how broadly they apply. A variable declared in task main cannot be seen by a function, and vice versa. Functions cannot see variables declared in other functions. Every variable declaration has a certain scope associated with it, a certain code domain in which it “exists”. Outside the boundaries of that domain, it is “out of scope” and invisible. ROBOTC will treat it as if it does not exist in those places.

Scope is an important concept in programming, because it allows pieces of code to function as independently as possible. Scope rules are necessary to prevent “separate” pieces of code from interfering with each other. They don’t have to worry about names of variables inside other functions, or even within other copies of themselves if the same function is called more than once. Scope leaves functions much more free to do what they need to do.

Sometimes, however, scope makes things very inconvenient. ROBOTC offers the option of using global variables to circumvent the rules of scope. Using global variables is typically considered a poor coding practice, because it inevitably leads to the undesired interference that scope is meant to prevent. However, for the sake of simplifying this program’s initial translation, we will use global variables now with the understanding that they should be removed as soon as possible (when you learn about parameterized functions).

Variables are made global by moving their declarations outside all functions and tasks, and declaring them in the base level of the program itself.

Page 57: Ultrasonic Rangefinder Forward till Near - Carnegie Mellon...education.rec.ri.cmu.edu/downloads/vex/TRC_VEX_training_pdfs... · In this lesson, you will learn how an Ultrasonic Rangefinder

ROBOTC

Ultrasonic Rangefinder • 57© Carnegie Mellon Robotics Academy / For use with VEX® Robotics Systems

Sensing

5. Move all the variable declarations in task main to the global level. This is only a temporary solution!

146147148149150151152153154

5a. Highlight this codeHighlight the variable declaration code.

Ultrasonic Rangefinder Full Program (cont.)

}

task main(){ int armDirection; bool isMovingStraight; bIfiAutonomousMode = false; while(vexRT[Ch5] == 0) {

4b. Edit > Cut

const tSensors downLimit = (tSensors) in1;const tSensors rightEncoder = (tSensors) in2;const tSensors leftEncoder = (tSensors) in3;const tSensors upLimit = (tSensors) in4; const tSensors sonarSensor = (tSensors) in5;

|

void moveStraight(){ if(SensorValue[leftEncoder] > SensorValue[rightEncoder]) { motor[port3] = 50; motor[port2] = 63;

AutoAutoAutoAutoAutoAuto

123456789

1011

4c. Place cursor hereMake a few lines of whitespace and place your cursor on the first line of your program.

4d. Edit > Paste

Checkpoint

The Radio Control Period behaviors have been transferred into a new function which will handle all of their functionality. Remember that this was done to put them in the proper context, as the scope of the program expanded as a whole. The Autonomous Period function must now be created.

Page 58: Ultrasonic Rangefinder Forward till Near - Carnegie Mellon...education.rec.ri.cmu.edu/downloads/vex/TRC_VEX_training_pdfs... · In this lesson, you will learn how an Ultrasonic Rangefinder

ROBOTC

Ultrasonic Rangefinder • 58© Carnegie Mellon Robotics Academy / For use with VEX® Robotics Systems

Sensing

Ultrasonic Rangefinder Full Program (cont.)

As always, begin by pseudocoding the behavior. Remember that because it is a function, it must not use any while() loops, in order to avoid getting the program “stuck”.

function autonomousPeriodBehaviors() { pick up mine; drop off mine;}

And again, elaborate on the needed behaviors. In this case, picking up the mine is already an available behavior, thanks to the autoGetMine() function you already programmed! If this particular program is designed to go for the Autonomous Period Mine, it will always know the initial direction of the mine, and the direction and distance to the disposal bin afterwards.

picture with robot in base, also showing location of the first mine

The implementation of this second behavior, getting to the disposal bin, will be up to you! We will assume that you will implement your behavior in a function called dropOffMine(). Knowing what you know now about using pseudocode to guide your code development, you should be able to do this in no time! You can write this now, but we recommend completing it after the end of this lesson, since there’s still more work to do here.

This function still needs to decide whether it should be trying to pick up the ball, or drop it off. Since it is looped by task main, it cannot rely on a while() loop to keep it from getting to the second function. Instead, it needs to keep track of whether the ball has been picked up or not. A new variable is needed. We will call it minePickedUp, and it will be either true or false, so its type will be bool (Boolean). If the mine is not picked up to start, then the robot should be running autoGetMine(). If the mine has been picked up, then it should be running dropOffMine() instead.

Page 59: Ultrasonic Rangefinder Forward till Near - Carnegie Mellon...education.rec.ri.cmu.edu/downloads/vex/TRC_VEX_training_pdfs... · In this lesson, you will learn how an Ultrasonic Rangefinder

ROBOTC

Ultrasonic Rangefinder • 59© Carnegie Mellon Robotics Academy / For use with VEX® Robotics Systems

Sensing

bool minePickedUp;

function autonomousPeriodBehaviors() { if (minePickedUp is false) { autoGetMine(); } otherwise (minePickedUp is true) { dropOffMine(); }}

Ultrasonic Rangefinder Full Program (cont.)

How will the program know when the mine has been picked up? The autoGetMine() behavior needs to be changed as well to signal when the pickup has completed. The pickup is complete when the arm has reached the top position.

function autoGetMine() { if (the robot is more than 1 inch away from the object) { go straight forward; } otherwise (the robot is 1 inch or less from the object) { stop both wheel motors; if (the up-bumper on the arm is not pressed) { move the arm upward; } otherwise (the up-bumper on the arm IS pressed) { hold the arm in place; set minePickedUp to true; } }}

Page 60: Ultrasonic Rangefinder Forward till Near - Carnegie Mellon...education.rec.ri.cmu.edu/downloads/vex/TRC_VEX_training_pdfs... · In this lesson, you will learn how an Ultrasonic Rangefinder

ROBOTC

Ultrasonic Rangefinder • 60© Carnegie Mellon Robotics Academy / For use with VEX® Robotics Systems

Sensing

Ultrasonic Rangefinder Full Program (cont.)

else { motor[port6]=0; } }}

void dropOffMine(){}

void autonomousPeriodBehaviors(){}

void radioControlPeriodBehaviors(){

53545556575859606162636465666768697071

6. Add this codeThis empty function is called a “stub” because it is just a placeholder for code that is yet to be developed. You need to fill this in with the correct code later!

6. Create the “stub” function dropOffMine() that you will fill in yourself later!

7. Create the global Boolean variable minePickedUp that will be used to keep track of whether the mine has been picked up. The robot needs to keep track of this rather than the human, so that it knows when it should be getting the mine, as opposed to dropping it off.

int armDirection;bool isMovingStraight;bool minePickedUp;

void moveStraight(){ if(SensorValue[leftEncoder] > SensorValue[rightEncoder])

1234567

7. Add this codeCreate a global variable named minePickedUp. It is a Boolean variable, holding only a true or false value.

8. Fill in the code for the autonomousPeriodBehaviors() function, based on the pseudocode developed above.

void autonomousPeriodBehaviors(){ if(minePickedUp == false) { autoGetMine(); } else { dropOffMine(); }}

67686970717273747576777879

8a. Add this codeStart with the basic if-else statement frame that will check whether the mine has been picked up or not.

8b. Add this codeIn the “mine not picked up” (false) side, run the autoGetMine() behavior.

8c. Add this codeIn the “mine already picked up” (true) side, run the dropOffMine() behavior.

Page 61: Ultrasonic Rangefinder Forward till Near - Carnegie Mellon...education.rec.ri.cmu.edu/downloads/vex/TRC_VEX_training_pdfs... · In this lesson, you will learn how an Ultrasonic Rangefinder

ROBOTC

Ultrasonic Rangefinder • 61© Carnegie Mellon Robotics Academy / For use with VEX® Robotics Systems

Sensing

Ultrasonic Rangefinder Full Program (cont.)

void autoGetMine(){ if (SensorValue(sonarSensor) > 1) { slowStraight(); } else { motor[port3]=0; motor[port2]=0; if (SensorValue(upLimit)==0) { motor[port6]=31; } else { motor[port6]=0; minePickedUp = true; } }}

42434445464748495051525354555657585960616263

10. Change the autoGetMine() function so that it matches the pseudocode and signals when the mine has been picked up.

10. Add this codeSet minePickedUp equal to true.

task main(){ bIfiAutonomousMode = false; while(vexRT[Ch5] == 0) {

}

bMotorReflected[port2] = 1;

armDirection = 0; isMovingStraight = false; minePickedUp = false; ClearTimer(T1); while(time10[T1] < 12000)

163164165166167168169170171172173174175176177178

9. Notice how the autonomousPeriodBehaviors() function checks to see if minePickedUp is equal to false, but the variable has never actually been set. Make it equal to false inside of task main().

9. Add this codeSet minePickedUp equal to false.

Page 62: Ultrasonic Rangefinder Forward till Near - Carnegie Mellon...education.rec.ri.cmu.edu/downloads/vex/TRC_VEX_training_pdfs... · In this lesson, you will learn how an Ultrasonic Rangefinder

ROBOTC

Ultrasonic Rangefinder • 62© Carnegie Mellon Robotics Academy / For use with VEX® Robotics Systems

Sensing

Ultrasonic Rangefinder Full Program (cont.)

Checkpoint

Your program is almost done.

Program

Autonomous Period Remote Control Period

Wait for starting button press

Autonomous Period timer loop

Stop Wait for starting button press

Radio Control timer loop

Stop

Drive up to mine

Pick up mine

Take mine to disposal bin

Set arm motor based on buttons, unless autonomous-assist is/was recently in effect

Take care of any full-autonomy assistance functions that are being requested

Handle manual driving commands if no full-autonomy functions are in use

Automatic Straight, if requested

Automatic Grab, if requested

Set driving motors based on joysticks

task main()

All that’s left (aside from the dropOffMine() behavior you need to make later) is to make sure that task main calls the two Period functions at the right times.

bIfiAutonomousMode = false; while(vexRT[Ch5] == 0) {

}

bMotorReflected[port2] = 1;

armDirection = 0; isMovingStraight = false; minePickedUp = false; ClearTimer(T1); while(time10[T1] < 2000) { autonomousPeriodBehaviors(); }

167168169170171172173174175176177178179180181182183184

11. Add the timer loop for the Autonomous Period to task main.

11b. Add this codeInside this loop, call the Autonomous Period function.

11a. Add this codeCreate a 20-second timer loop after the initial button press. This timer loop will run the Autonomous Period code.

Page 63: Ultrasonic Rangefinder Forward till Near - Carnegie Mellon...education.rec.ri.cmu.edu/downloads/vex/TRC_VEX_training_pdfs... · In this lesson, you will learn how an Ultrasonic Rangefinder

ROBOTC

Ultrasonic Rangefinder • 63© Carnegie Mellon Robotics Academy / For use with VEX® Robotics Systems

Sensing

Ultrasonic Rangefinder Full Program (cont.)

12. Add the code for the transition between the Autonomous and Radio Control Periods. Remember that the robot must stop, and wait for a Transmitter signal to begin the next period.

ClearTimer(T1); while(time10[T1] < 2000) { autonomousPeriodBehaviors(); }

motor[port3] = 0; motor[port2] = 0; while(vexRT[Ch5] == 0) {

}

ClearTimer(T1); while(time10[T1] < 12000)

178179180181182183184185186187188189190191192193

12b. Add this codeWait for the Transmitter button to be pressed before continuing.

12a. Add this codeStop the robot’s motors following the end of the Autonomous Period.

13. Include the Radio Control Period and adjust the time limit.

motor[port2] = 0; while(vexRT[Ch5] == 0) {

}

ClearTimer(T1); while(time10[T1] < 10000) { radioControlPeriodBehaviors(); }

motor[port3] = 0; motor[port2] = 0;}

178179180181182183184185186187188189190191192193

13b. Add this codeCall the Radio Control Period Behaviors within the while 100 second while loop.

13a. Modify this codeChange the Radio Control Period to its correct length of 100 seconds.

14. Download and run.

10. Go to Compile and Download Program

Page 64: Ultrasonic Rangefinder Forward till Near - Carnegie Mellon...education.rec.ri.cmu.edu/downloads/vex/TRC_VEX_training_pdfs... · In this lesson, you will learn how an Ultrasonic Rangefinder

ROBOTC

Ultrasonic Rangefinder • 64© Carnegie Mellon Robotics Academy / For use with VEX® Robotics Systems

Sensing

Ultrasonic Rangefinder Full Program (cont.)

End of Section

Your robot is almost ready to compete!

[picture: robot stuck after picking up the ball]

As you can see, it is missing the portion of the code that tells it what to do after picking up the mine. You will need to plan and write that portion. However, after completing the 20 seconds of Autonomous Period, it is ready to move on to the Radio Control Period with the press of a button, and all your programmed behaviors from behavior are available again through the Transmitter.

Your robot is functional, but we have left so many improvements undone, and so many topics uncovered. For now, focus on completing the competition program by writing the dropOffMine() function. Afterwards, consider looking at the Reference pages and Bonus Lessons to put the polish back on your program. A number of advanced programming techniques can help to make your robot’s performance stronger, and its code more intuitive. Here are a few good places to start… and may the best robot win!