Cookie CodersFTC Team 39092

Autonomous // Student lesson

Auto-Learn-AprilTagApproach
AprilTag Approach

Code Lab / Auto-Learn-AprilTagApproach

Follow Auto-Learn-AprilTagApproach through acquisition, centering, and a camera-range approach to 24 inches. Learn identifies an educational example, not permission to run it. This sample sends real motor commands but has no wall guard or validated camera freshness gate; study its branches and limitations before any separately authorized hardware review.

The comments call five centered observations frames, but the source counts loop checks without deduplicating images and retains the count across missing-target checks. Its endpoint projection uses yaw in X/Y, and its autonomous back-right direction differs from the TeleOp. None of these source details should be silently rewritten into a safer imaginary program.

Before running: Ask your supervisor first. Keep Driver Station STOP ready.

Mission control

Read, predict, compare, explain.

19source-linked steps
7scored quiz checks
Start with a question

What evidence would distinguish a robot that reached its target from one that merely stopped because time ran out?

  • State machines
  • Vision feedback
  • Timeouts
  • 3D distance

Read · predict · explain

Build the idea, one block at a time

Read these steps before exploring the full program. The numbered blue comments in the diagram link back to the matching step.

Start with a question

What evidence would distinguish a robot that reached its target from one that merely stopped because time ran out?

By the end, you can…

  • Trace the 3-second acquisition, 6-second centering, and 8-second approach limits.
  • Explain complete-half target selection and the retained red/blue choice after acquisition.
  • Calculate reconstructed center range and signed steering from the source equations.
  • Distinguish zero on vision loss, loop-count centering, range completion, and timeout.

01Prepare the autonomous direction profile

Actual Blocks for this section
Blocks for Prepare the autonomous direction profile
Blocks to noticeHover, focus or tap a block to see what it does.
  • Sets which way each drive motor spins for a positive power: front-left and back-left REVERSE, front-right and back-right FORWARD.
  • Makes each drive motor resist turning when its power is 0, so the wheels stop firmly instead of coasting.
  • Lets each motor controller use wheel-encoder feedback to regulate speed. It sets no distance target; the 24-inch stop comes from camera range.
  • Sets the front-left, back-left, front-right and back-right motor powers to 0 so no wheel is commanded to move yet.
  • Asks the Driver Station to receive telemetry about every 50 milliseconds so on-screen lines refresh quickly. It is a request, not a guarantee.

The autonomous source reverses FL and BL but sets both FR and BR FORWARD. All four use BRAKE and RUN_USING_ENCODER and begin at zero. This differs from Start and AprilTagTeleOp, where BR is REVERSE. Encoder mode here is not a RUN_TO_POSITION destination, and the approach stop is chosen from camera range rather than an encoder distance.

For example: A uniform +0.25 request is intended as forward only with this autonomous mounting profile; copying the TeleOp BR setting changes the convention.

Think first

Does RUN_USING_ENCODER mean the program sets a 24-inch encoder target?

Show Answer

No. No encoder-position target controls this approach; 24 is a camera-center range in inches.

02Start the reviewed AprilTag pipeline

Actual Blocks for this section
Blocks for Start the reviewed AprilTag pipeline
Blocks to noticeHover, focus or tap a block to see what it does.
  • Asks the Limelight to report results up to 100 times per second. It is only a request, not proof that each read is a new, correct frame.
  • Selects Limelight pipeline slot 0, which this program expects to be set up to detect AprilTags. The slot's settings still need checking.
  • Starts the Limelight camera so it begins processing images and returning results to the program.
  • Adds a READY message saying the plan is to find the tag center and stop 24 inches away. It is only a message, not a check.

Setup requests 100 Hz polling and pipeline 0, then this section starts the camera and reports the intended 24-inch behavior. Verify that slot 0 detects the correct AprilTags. A fast poll request provides opportunities to read results, not proof of a new processed frame, a correct pipeline, or a current pose.

For example: Repeatedly polling one result at 100 Hz can still provide only one image's geometry.

Think first

Can a requested 100 Hz poll rate certify five independent frames for centering?

Show Answer

No. Independent frames require frame identity or timing evidence, which this source does not check.

03Preview geometry with zero drive requests

Actual Blocks for this section
Blocks for Preview geometry with zero drive requests
Blocks to noticeHover, focus or tap a block to see what it does.
  • Repeats the blocks inside while the robot is in INIT, before the driver presses START, so the camera preview keeps updating.
  • Runs the custom scanTags function, which clears old flags, reads the latest Limelight result and rebuilds tag distances and the red and blue centers.
  • Shows the R1-R8 tag distances and the red-center distance on the Driver Station. Items not seen in this scan show as not available.
  • Sends the lines added with addData to the Driver Station screen so students can read the preview.
  • Gives the robot controller a brief moment to handle other work during the loop instead of spinning as fast as possible.

INIT scans continuously and displays the red tag distances and red-center estimate while the setup's motor requests remain zero. Red display can be unavailable even if the camera sees blue; display emphasis is not target-selection policy. The later acquisition can select either complete alliance center.

For example: Only blue groups 2 and 3 can form a usable blue center while the red-center row still says not available.

Think first

Does a missing red-center INIT row force the autonomous to reject a complete blue center?

Show Answer

No. Acquisition compares complete red and blue centers, not just the displayed red row.

04Open acquisition only after START

Actual Blocks for this section
Blocks for Open acquisition only after START
Blocks to noticeHover, focus or tap a block to see what it does.
  • Pauses the program until the driver presses START on the Driver Station, so the motion phases cannot begin early.
  • Turns on selecting mode, meaning the program is still choosing between the red and blue center and has not locked onto one.
  • Records that no alliance center is chosen yet. Later 0 means red and 1 means blue; this is not a physical tag ID.
  • Starts the best-range comparison at 9999 inches so any real center range found later counts as nearer.
  • Restarts the program timer at 0 so the 3-second acquisition limit is measured from START.

waitForStart prevents the autonomous motion phases from starting early. The source then enters selecting mode with no selected alliance (-1), a 9999-inch comparison sentinel, and a fresh acquisition timer. Those are target-state variables, not physical tag IDs or sensor measurements.

For example: selectedId -1 means nothing has been acquired. IDs 30 or 38 in the image are mapped to halves before a center can be chosen.

Think first

Does pressing START automatically mean selectedId becomes 0?

Show Answer

No. A complete matching pair still has to be observed during acquisition.

05Choose the first scan with a usable nearer center

Actual Blocks for this section
Blocks for Choose the first scan with a usable nearer center
Blocks to noticeHover, focus or tap a block to see what it does.
  • Keeps searching only while the program is running, no center has been chosen yet, and fewer than 3 seconds have passed.
  • Runs scanTags to read the latest camera result and rebuild any complete red or blue center, and choose one while selecting is true.
  • Compares the red and blue center ranges and picks the nearer one. Red is tested first, so blue wins only if strictly nearer.

Acquisition scans for up to 3 seconds while selectedId stays negative. In the first usable scan it compares complete red and blue centers and picks the nearer, with red winning a tie. It does not search all three seconds for a globally best target: a selection ends the acquisition loop. Motors retain zero during this phase; no acquired center leads to the stopped result.

For example: At 0.2 seconds red is complete at 50 inches and blue is absent: red is acquired then, even if blue might appear nearer at 1 second.

Think first

If only IDs 30 and 31 appear for the whole 3 seconds, is red acquired?

Show Answer

No. Both belong to the first red half, so no red center can be built.

06Count centered checks and inspect the loss branch

Actual Blocks for this section
Blocks for Count centered checks and inspect the loss branch
Blocks to noticeHover, focus or tap a block to see what it does.
  • Locks in the choice. Later scans update only the chosen alliance, so a nearer center of the other color cannot take over.
  • Sets the centered-check counter to 0 before centering begins. Five counted checks are needed to move on to the approach.
  • Limits the centering loop to 6 seconds since the timer was reset, so it cannot run forever.
  • True when the chosen center's horizontal angle is within 2 degrees of straight ahead, ignoring whether it is left or right.
  • Adds one to the centered counter after a centered check. It counts loop checks, not proven distinct frames, and a missing target does not reset it.
  • Sets fixed turning powers when the angle is more than 2 degrees off: positive tx turns one way, negative the other, and centered resets to 0.

After acquisition, selection is locked and centering runs for at most 6 seconds. found with |tx| <= 2 degrees increments centered and requests zero; five checks permit approach. Off-center found observations reset centered and turn: positive error gives FL/BL +0.18, FR -0.24, BR -0.18; negative error reverses signs. Missing target requests zero but does NOT reset centered. No frame timestamp is deduplicated, so these are not guaranteed five consecutive distinct camera frames.

For example: Centered counts 1,2; a missing result leaves 2; three more centered checks can reach 5. Re-reading one old centered image can also increment the counter.

Math breakoutClosed-loop camera centeringmeasure → turn → measure again → stop inside ±2°

The robot repeatedly corrects fresh angle error instead of guessing one perfect turn.

Think first

Does an off-center found result at +3 degrees preserve centered = 2?

Show Answer

No. The turn branch resets it to 0; a missing-target branch, unlike this off-center branch, leaves the count unchanged.

07Approach a center range, not a bumper gap

Actual Blocks for this section
Blocks for Approach a center range, not a bumper gap
Blocks to noticeHover, focus or tap a block to see what it does.
  • Sets the goal to 24 inches, measured as camera-to-center straight-line range, not as the gap from the bumper to the target.
  • Limits the approach to 8 seconds. The loop also ends when done becomes true or the program is stopped.
  • Checks that the chosen center was found in this scan. If it was not, all four motors are told 0 and the loop tries again.
  • True when the camera-to-center range is 24 inches or less. The program then requests zero power and sets done to true.
  • Checks whether the center is more than 2 degrees to one side or the other, and picks a different steering power mix for each case.
  • Sets the four drive powers, between 0.20 and 0.36, to drive forward while nudging toward the center. These are requests, not measured speed.

After centered >= 5, the program stores startRange and targetRange = 24 inches. While active, not done, and under 8 seconds, found range <= 24 requests zero and sets done. Above 24, FL/FR/BL/BR are 0.30/0.26/0.30/0.20 for tx > 2; 0.20/0.36/0.20/0.30 for tx < -2; otherwise 0.25/0.31/0.25/0.25. Missing target requests zero but permits reacquisition of the same alliance within the timer. There is no approach angle-edge or obstacle gate. The targetRange >= 10 check always passes for the assigned 24; it is not a measured already-close check.

For example: At range 30 and tx +3 degrees, use 0.30/0.26/0.30/0.20. At range exactly 24, all powers become zero and done true. startRange minus currentRange is only a change in camera range, not verified chassis travel.

Math breakoutClosed-loop camera centeringmeasure → turn → measure again → stop inside ±2°

The robot repeatedly corrects fresh angle error instead of guessing one perfect turn.

Think first

Does a target loss at 2 seconds make done true or allow blind forward travel?

Show Answer

Neither. It commands zero without setting done; the same selected target can resume guidance before the 8-second timeout.

08Label the outcome before ending vision

Actual Blocks for this section
Blocks for Label the outcome before ending vision
Blocks to noticeHover, focus or tap a block to see what it does.
  • Shows COMPLETE if done was set by the range check, otherwise a STOPPED message. COMPLETE means the camera range threshold, not proven bumper clearance.
  • Sets all four drive motor powers to 0 at the end so no wheel is commanded to move after the approach or when the program stops.
  • Stops the Limelight camera now that the program no longer needs its results.

Range completion, acquisition failure, centering timeout, approach timeout, and Driver Station STOP are different outcomes. Cleanup requests zero from all four motors and stops the camera. COMPLETE describes reaching the source's camera-center threshold; it is not proof of a 24-inch bumper clearance, exact travel, validated fresh imagery, or competition readiness.

For example: An 8-second timeout with range still 30 inches produces a stopped outcome, not successful arrival merely because the wheels stopped.

Think first

Can Driver Station STOP during approach be counted as reaching the range goal?

Show Answer

No. Only the found-and-range <= 24 branch sets done for completion.

09Erase visibility before each scan

Actual Blocks for this section
Blocks for Erase visibility before each scan
Blocks to noticeHover, focus or tap a block to see what it does.
  • Marks that no usable target is known yet. found becomes true again only if this scan builds a complete selected center.
  • Clears the four endpoint flags so a tag seen in an earlier scan cannot count toward a center in this scan.
  • Clears the R1-R8 and B1-B8 distances and the red-center distance, so tags not seen in this scan show as not visible.

scanTags clears found, the four endpoint flags, and the displayed tag distances before inspecting a result. Red-center display becomes not available. TeleOp also clears the four sticker-distance displays. Old coordinates can remain in variables, but cleared flags prevent a missing half from completing a center. Resetting state is not the same as proving the camera returned a new frame.

For example: A scan with R4 and R5 can set found true. A later scan containing only R4 leaves r5Seen false and cannot rebuild the red center.

Think first

May yesterday's r5 coordinates complete today's red center when r5Seen is false?

Show Answer

No. Both endpoint flags must be true in this scan; stored numbers alone are insufficient.

10Read a result, then its fiducial list

Actual Blocks for this section
Blocks for Read a result, then its fiducial list
Blocks to noticeHover, focus or tap a block to see what it does.
  • Asks the Limelight for its most recent processed result. It can repeat an old result, so it does not prove a new camera frame.
  • True when the camera returned a result at all. It does not check the result's age or validity, or that any tags are in it.
  • Gets the list of AprilTags, called fiducials, recognized in the result. The list can be empty even when the result exists.
  • Stores the fiducial list in the variable list so the for-each loop can go through the tags one at a time.

The non-null branch reads the result's list of fiducials, meaning recognized markers. A non-null result can still contain an empty list. These AprilTag sources do not check IsValid, Staleness, pipeline index, or a distinct frame timestamp here. Calling getLatestResult does not itself guarantee a fresh image, so this sample is not a validated freshness guard.

For example: An empty current list builds no center. Repeated retrieval of an old nonempty result could repeat the same geometry even though all flags were reset.

Think first

Does the non-null test prove that the image is less than 250 ms old?

Show Answer

No. There is no age comparison in this scan; null handling and freshness are separate checks.

11Repeat camera-space geometry for each tag

Actual Blocks for this section
Blocks for Repeat camera-space geometry for each tag
Blocks to noticeHover, focus or tap a block to see what it does.
  • Repeats the blocks inside once for every AprilTag in the list, running the same position and distance math on each tag.
  • Gets the tag's position and rotation measured relative to the camera. It is not the robot's location on the field.
  • Saves the tag's camera-space pose in the variable pose so the next blocks can read its x, y, z, yaw and pitch.

For each fiducial, the source retrieves its TargetPoseCameraSpace: position plus orientation relative to the camera, not a robot field pose. The instructional convention calls x left/right, y up/down, and z forward/back; yaw and pitch describe rotation, not wireless transmit/receive. Later projection formulas must be read literally and checked against the SDK pose convention before any physical use.

For example: Two tags in the list produce two passes through the position, angle, ID, and offset calculations; they are not two distinct camera frames.

Think first

Is a camera-space tag pose automatically a field location of the robot?

Show Answer

No. It is a relative camera-to-tag observation; field localization would need additional transforms and references.

12Keep signs until distance is calculated

Actual Blocks for this section
Blocks for Keep signs until distance is calculated
Blocks to noticeHover, focus or tap a block to see what it does.
  • Reads the tag's left/right position from the pose, in meters. The sign shows which side of the camera the tag is on.
  • Reads the tag's up/down position from the pose, in meters, keeping its sign.
  • Reads how far forward the tag is from the camera, in meters, from the pose.
  • Stores the three signed pose values in x, y and z. Signs are kept until the range is squared, so direction is not lost.

The pose getters copy all three signed coordinates in meters. Signs matter when adding an offset and when computing steering. Squaring for range removes signs only at that later calculation; taking absolute values first would lose which side the reconstructed center lies on.

For example: A practice pose (-0.30, 0.40, 0.00) m has a 0.50 m range, but its negative x is still important to direction.

Think first

Do x = -0.30 m and x = +0.30 m contribute different amounts to x*x?

Show Answer

No. Both contribute 0.09 square meters, although their signed positions differ.

13Use degree-based yaw and pitch

Actual Blocks for this section
Blocks for Use degree-based yaw and pitch
Blocks to noticeHover, focus or tap a block to see what it does.
  • Reads the tag's left/right rotation angle in degrees from the pose and saves it as yaw for the offset projection.
  • Reads the tag's up/down tilt angle in degrees from the pose and saves it as pitch for the offset projection.
  • Takes the sine of an angle in degrees. Blocks converts the angle itself, so no radians conversion is needed. Used here with yaw and pitch.
  • Takes the cosine of an angle in degrees, with no radians conversion needed. Used here with yaw and pitch to project the strip offset.

The source copies yaw and pitch from the pose and passes them to Blocks trig operations, which use degrees. Yaw is taught as a left/right rotation and pitch as a tilt. Do not insert a student radians conversion into this chain: it would change the inputs the Blocks operations expect. Review the exact axis mapping as well as the angle units.

For example: At yaw = 0 and pitch = 0, cosines are 1 and sines are 0, so an offset changes only the source's endpoint X.

Think first

Should a 90-degree pose angle be manually replaced with about 1.57 before the COS block?

Show Answer

No. This Blocks operation expects degrees; cos(90 degrees) is 0.

14Measure the line to a tag center

Actual Blocks for this section
Blocks for Measure the line to a tag center
Blocks to noticeHover, focus or tap a block to see what it does.
  • Squares each camera-space coordinate so every contribution to the distance is positive before they are added.
  • Adds the three squared values x*x, y*y and z*z into one total for the 3D distance.
  • Takes the square root of the summed squares, giving the straight-line distance from the camera to the tag center in meters.
  • Converts that distance from meters to inches, since one meter is about 39.3701 inches.
  • Reads the AprilTag's ID number (30-45 here), which later blocks use to decide which half-group and offset the tag has.
  • Reads the tag's raw horizontal angle in degrees from the camera. Later steering uses the reconstructed center's angle instead.

Square each camera-space coordinate, add all three, take the square root, then multiply by 39.3701 inches per meter. This range is to the individual visible tag center, not yet a sticker or alliance center. The source also reads the physical tag ID and its raw TargetXDegrees; later center steering replaces that raw angle with a reconstructed-center angle.

For example: For (0.30, 0.40, 0) m: sqrt(0.09 + 0.16) = 0.50 m, or about 19.685 inches.

Math breakout3D Pythagorean distancerange = √(X² + Y² + Z²)

Three perpendicular camera measurements combine into one straight-line range.

Think first

What goes wrong if you omit y when it is 0.40 m in this example?

Show Answer

You get 0.30 m instead of 0.50 m and understate the full camera-to-tag distance.

15Require a pair of matching half-groups

Actual Blocks for this section
Blocks for Require a pair of matching half-groups
Blocks to noticeHover, focus or tap a block to see what it does.
  • Starts each tag as unassigned (group -1). A tag ID from 30 to 45 then changes it to group 0, 1, 2 or 3.
  • Starts the tag's strip offset at 0 inches. A recognized tag ID replaces it with the signed offset to the endpoint it estimates.
  • Sorts tags into four half-groups: 0 and 1 are the two red halves, 2 and 3 are the two blue halves.
  • Sets the matching flag (r4Seen, r5Seen, b4Seen or b5Seen) to true when a tag from that half is read. Both flags of a pair make a center.

Each tag begins unassigned at group -1 and offset 0. IDs 30-33 form group 0 and reconstruct R4; 34-37 form group 1 and reconstruct R5. Groups 2 and 3 similarly reconstruct B4 and B5 from IDs 38-41 and 42-45. One visible tag from each matching pair of groups is sufficient; two tags from only one group are not.

For example: IDs 30 and 37 can supply both red endpoints. IDs 30 and 31 supply only the R4 half, however many times they are read.

Think first

Can group 0 plus group 3 form a complete red or blue center?

Show Answer

No. The required pairs are 0 with 1, or 2 with 3.

16Convert tag identity into a signed known offset

Actual Blocks for this section
Blocks for Convert tag identity into a signed known offset
Blocks to noticeHover, focus or tap a block to see what it does.
  • Compares the tag's ID with 30 through 45 one by one to find out which red or blue tag it is.
  • Stores the half-group number for the matched tag: IDs 30-33 are group 0, 34-37 group 1, 38-41 group 2 and 42-45 group 3.
  • Stores the tag's signed offset in inches to the endpoint it estimates, such as +13 for ID 30 or -13 for ID 37.
  • Saves the tag's range in inches in its own named variable, such as R1Distance for ID 30, so telemetry can show which tags are visible.

IDs 30-37 are R1-R8; 38-45 are B1-B8. Within each four-tag sticker the centers sit at -6.5, -2.75, +2.75, +6.5 inches. To reconstruct endpoint 4, the first half uses offsets +13, +9.25, +3.75, 0; to reconstruct endpoint 5, the second half uses 0, -3.75, -9.25, -13. These are signed tag-to-endpoint corrections, not the tag's measured range. TeleOp additionally uses tag-to-sticker offsets +6.5, +2.75, -2.75, -6.5.

For example: R1 at ID 30 is 13 inches left of R4, so its endpoint correction is +13. R8 at ID 37 gets -13 to reconstruct R5.

Think first

For R6, ID 35, is the endpoint offset +3.75 or -3.75 inches?

Show Answer

It is -3.75 inches: move back along the strip from R6 to R5.

17Project the strip offset exactly as written

Actual Blocks for this section
Blocks for Project the strip offset exactly as written
Blocks to noticeHover, focus or tap a block to see what it does.
  • Converts the signed offset from inches to meters so it matches the camera pose units before it is added to the pose.
  • Finds the cosine of yaw in degrees. It is multiplied into the X correction, d*cos(yaw)*cos(pitch).
  • Finds the sine of yaw in degrees. It is multiplied into the Y correction, d*sin(yaw)*cos(pitch), exactly as the blocks are written.
  • Finds the cosine of pitch in degrees, which scales both the X and the Y corrections.
  • Finds the sine of pitch in degrees. It is used in the Z correction, where d*sin(pitch) is subtracted from z.
  • Stores the projected endpoint position for R4, R5, B4 or B5 by adding each correction to the tag's own x, y and z.

Let d be the signed inch offset divided by 39.3701. The source reconstructs X = x + d*cos(yaw)*cos(pitch), Y = y + d*sin(yaw)*cos(pitch), Z = z - d*sin(pitch). Notice that yaw contributes to X and Y in these actual Blocks, while pitch changes Z. That is not the usual simplified claim that yaw rotates an offset between X and Z. Treat pose-axis interpretation as a supervised verification task, not an already proven physical model.

For example: For d = 0.10 m, yaw = 90 degrees and pitch = 0, the written equations add about 0 to X, +0.10 to Y, and 0 to Z.

Math breakoutRotate a known AprilTag offsetΔX = d·cos(yaw)·cos(pitch) ΔY = d·sin(yaw)·cos(pitch)

Sine and cosine split one known strip distance into camera-axis pieces.

Think first

At yaw = 0 and pitch = 90 degrees, what is the signed Z correction for positive d?

Show Answer

Z decreases by d, because the source subtracts d*sin(pitch); X and Y corrections are zero.

18Average coordinates, then find range and bearing

Actual Blocks for this section
Blocks for Average coordinates, then find range and bearing
Blocks to noticeHover, focus or tap a block to see what it does.
  • True only when this scan found a tag from both red halves, so a red center can be built. Blue uses b4Seen AND b5Seen the same way.
  • Averages the R4 and R5 endpoint coordinates on each axis to find the midpoint of the red strip. Blue does the same with B4 and B5.
  • Takes the square root of X*X + Y*Y + Z*Z for the center to get its straight-line distance, then it is multiplied by 39.3701 for inches.
  • Finds the center's left/right angle in degrees from its X and Z. This reconstructed bearing, not a single tag's angle, becomes the steering angle.
  • Saves the red center's range in inches for the telemetry display. It stays not available if either red half is missing.

A complete red pair averages R4 and R5 coordinates; a complete blue pair averages B4 and B5. Each midpoint's 3D magnitude becomes its inch range. atan2 uses center X as the numerator-like Y socket and center Z as the X socket, giving atan2(center X, center Z) in degrees. This reconstructed bearing, not the raw visible tag's tx, guides centering. It is a geometric midpoint estimate, not full field GPS or multi-camera triangulation.

For example: Endpoints (-0.20, 0, 1.00) and (+0.40, 0, 1.00) m yield center (0.10, 0, 1.00), range about 39.57 inches, and tx about +5.71 degrees.

Math breakoutMidpoint and center bearingcenter = (A + B) ÷ 2 angle = atan2(X, Z)

Average two reconstructed endpoints, then calculate the signed turn toward their center.

Think first

Can you obtain the same midpoint by averaging the two endpoint ranges?

Show Answer

Not in general. Average the signed coordinates first, then compute the center's magnitude.

19Choose once, then retain the alliance

Actual Blocks for this section
Blocks for Choose once, then retain the alliance
Blocks to noticeHover, focus or tap a block to see what it does.
  • Runs the choose-a-center logic only during acquisition. After a choice is locked, only the selected alliance's center is updated.
  • Checks whether a center is strictly nearer than the best so far. Red is tested first, so an equal blue range does not replace it.
  • Records the chosen alliance: 0 for the red center, 1 for the blue center. These are not physical tag IDs.
  • Copies the chosen center's range in inches and horizontal angle in degrees into currentRange and currentTx for the centering and approach loops.
  • Marks that the chosen center is available in this scan. Motor decisions only use currentRange and currentTx when found is true.

Acquisition starts with selecting true, selectedId -1, and selectedRange 9999. Red is tested first; blue replaces it only when strictly nearer in the same scan, so a tie retains red. Once acquired, selecting becomes false: later scans update only the selected alliance's complete pair. Another nearer alliance cannot take over. currentRange is inches, currentTx is degrees, and found gates use of those values.

For example: Acquire red at 40 inches. A later scan with only a blue center at 20 inches leaves found false instead of switching targets.

Think first

With red and blue both at 40 inches in a selecting scan, which wins?

Show Answer

Red, selectedId 0. Blue's strict less-than test cannot replace an equal range.

Try it without a robot

Make the math make sense

Use a notebook or talk through your answer with a partner. You do not need a robot to predict what these blocks will do.

tag range (in) = sqrt(x*x + y*y + z*z) * 39.3701
Camera-space position is in meters. Include height y, and convert the 3D straight-line distance to inches.
d = offset (in) / 39.3701
Put a known strip offset in meters before adding it to the pose.
endpoint X = x + d*cos(yaw)*cos(pitch); Y = y + d*sin(yaw)*cos(pitch); Z = z - d*sin(pitch)
These are the actual source projections, using degree-based Blocks trig. Do not replace them with an assumed X/Z yaw formula. The physical pose-axis interpretation needs supervised verification.
center = (endpoint 4 + endpoint 5) / 2 on each axis
Average reconstructed endpoint coordinates, not tag ranges. One observation from each matching half is required.
center range = sqrt(X*X + Y*Y + Z*Z)*39.3701; center tx = atan2(X,Z)
Range includes all three axes. The Blocks atan2 sockets hold X-socket = center Z and Y-socket = center X, giving the signed horizontal angle in degrees.
centered check: found AND |currentTx| <= 2; continue while centered < 5 AND time < 6 s
The source counts loop checks, not verified distinct frames, and does not reset centered on a missing target.
range goal: found AND currentRange <= 24 in
This is camera-to-reconstructed-center straight-line range, not a wheel travel or bumper-clearance target.
displayed distance traveled = startRange - currentRange
The source subtracts ranges. Rotation, camera offset, target motion, and 3D geometry can make this different from actual chassis displacement.

1. Trace the timers and retained target

Write phase and power decisions for: no complete pair for 3 seconds; red acquired at 0.2 seconds; blue later becomes nearer; centered counts 1,2, missing, centered, centered, centered. Compare that sequence with a found +3-degree observation after count 2. Identify why the counter is not a proof of five fresh consecutive frames.

2. Choose exact approach outputs

On paper list FL/FR/BL/BR at range 30 inches with tx +3, +2, -2, and -3 degrees. Then trace a missing target, reacquisition at range 26, arrival at exactly 24, and an independent 8-second timeout case. Which cases set done?

3. Measure the right thing

Calculate a 3D tag range for x 0.30, y 0.40, z 0 m. For endpoints (-0.20,0,1) and (+0.40,0,1), find midpoint range and angle. Explain why startRange 40 minus currentRange 24 does not by itself prove 16 inches of robot travel or 24 inches of bumper clearance.

Math in motion

Closed-loop camera centering

measure → turn → measure again → stop inside ±2°

Each camera frame produces a new horizontal error. The robot turns in the error direction, measures again, and stops only after the center remains close enough to straight ahead. Requiring several centered frames filters camera flicker.

  1. Measure currentTx from the newest complete center calculation.
  2. Turn left or right with a small bounded motor command.
  3. Stop after the error is within 2 degrees for the required number of fresh frames.

Robot proportions use the official REV Starter Bot Onshape assembly bounds.

Math in motion

3D Pythagorean distance

range = √(X² + Y² + Z²)

X, Y, and Z are three right-angle legs measured from the camera. Squaring removes direction signs, adding combines all three dimensions, and the square root returns the direct distance.

  1. Square X, Y, and Z so left/right and up/down signs cannot cancel distance.
  2. Add the three squared lengths.
  3. Take the square root, then convert meters to inches with × 39.3701.

Uses the official BIOBUZZ AprilTag cluster geometry from the FIRST field CAD.

Math in motion

Rotate a known AprilTag offset

ΔX = d·cos(yaw)·cos(pitch) ΔY = d·sin(yaw)·cos(pitch)

The measured offset lies along the AprilTag strip, but that strip can be turned relative to the camera. Yaw and pitch rotate the known offset into X, Y, and Z components before those components are added to the visible tag position.

  1. Convert the known offset from inches to meters.
  2. Use cosine for the component aligned with an axis and sine for the perpendicular component.
  3. Add the rotated components to the visible tag coordinates to estimate a hidden point.

The white strip is official BIOBUZZ field CAD; arrows are instructional overlays.

Math in motion

Midpoint and center bearing

center = (A + B) ÷ 2 angle = atan2(X, Z)

A midpoint is found independently on every axis. Once the center has X, Y, and Z coordinates, atan2 compares sideways X with forward Z and preserves the correct left/right sign and quadrant.

  1. Average endpoint A and endpoint B on X, Y, and Z.
  2. Use the midpoint coordinates for center range.
  3. Use atan2(X, Z) for a safe signed horizontal angle, even when one coordinate is zero.

AprilTag strips come from the official BIOBUZZ field model.

Full-program context

Explore the full Blocks program

One source program, in one column. Calls connect any named helper routines; they are not separate programs. Click a numbered blue comment to return to its explanation.

Full commented Blocks program
100%

Ask your supervisor before importing or running these Blocks. Viewing the program does not control the robot.

Section in context

Full Blocks program

The highlighted Blocks belong to this section. You can select another blue comment.

Check your understanding

Your turn

Choose an answer, then check your thinking. You can change an answer and try again.

Your answers stay on this page and reset when you reload. No cookies, account, or saved answers.

0 / 7 correct · 0 / 7 answered

0
0
Question 1A complete red center is available at 0.2 seconds but blue is absent. Does acquisition keep searching for the full 3 seconds?

Question 2Red was acquired. Later only a complete blue center is visible. What happens during guidance?

Question 3centered is 2, then the selected center is missing for one loop. What does the source do?

Question 4found is true, range is 30 inches, and tx is exactly +2 degrees. What FL/FR/BL/BR values are written?

Question 5found is true and currentRange is exactly 24 inches during approach. What changes?

Question 6Which statement accurately compares autonomous and TeleOp setup?

Question 7The page is named Auto-Learn-AprilTagApproach and the source is enabled. What does that prove?

Reset clears every choice, explanation, and score.

Adult supervision · setup · safety

Supervisor notes

For supervisors: 90-minute teaching plan & robot setup

Before the robot is used

Safety: Treat this as source analysis, not a deployment request. Learn and enabled metadata are not competition or physical-run approval. Autonomous sends real powers, has no wall guard, no age/pipeline validity checks in scanTags, and no approach edge-angle limit. Its centered counter is not five verified consecutive fresh frames. Any independently authorized bench demonstration needs wheels clear, exclusion space, an operator, and a supervisor at STOP. Do not use a camera-range endpoint as a bumper-clearance guarantee.

Required hardware & dependencies

  • Four mecanum drive motors named front_left_drive, front_right_drive, back_left_drive, and back_right_drive; verify each configured name against its physical cable and wheel.
  • FTC Robot Controller, Driver Station, secure battery, and a notebook. Motor direction settings are specific to the source and mounting, not universal wiring instructions.
  • Limelight 3A named limelight with calibrated AprilTag pipeline 0; correct tag sizes, camera mounting, and expected ID 30-45 geometry.
  • Accurate target-layout reference and tape measure for a separate stationary range audit; encoder-capable drive motors for the source's RUN_USING_ENCODER configuration.

Source remains AprilTagAuto.blk. Required native Blocks/devices are Limelight 3A named limelight, four drive motors, and an AprilTag pipeline 0 with the expected ID 30-45 layout. No helper ZIP is supplied. An educational name and enabled flag are not authorization; independently review axes, frame age, centering logic, calibrated range, and wheel directions before physical use. This page does not deploy anything.

Robot setup checklist

  1. Inspect AprilTagAuto.blk and resolve native motor and Limelight Blocks without deploying. No helper installation or ZIP is claimed.
  2. Verify autonomous FL/BL REVERSE, FR/BR FORWARD, BRAKE, RUN_USING_ENCODER, zero INIT powers, 100 Hz poll request, and 50 ms telemetry transmission request.
  3. Review the literal endpoint equations against the real camera pose convention. Check the half-group target layout before accepting a reconstructed center.
  4. Document absent age/distinct-frame checks and the centered counter's loss behavior. Source timeouts limit duration but do not certify a safe route or stopping distance.

90-minute teaching sequence

  1. 0-15 min

    Compare direction profiles and identify each timer's phase.

    Look for: BR FORWARD in Auto; 3/6/8 seconds belong to different phases.

  2. 15-35 min

    Reconstruct endpoints, midpoint range, and bearing.

    Look for: Signed offsets in meters and literal X/Y yaw projection.

  3. 35-60 min

    Trace first usable selection and centered-counter branches, including loss.

    Look for: Locked alliance, zero on loss, retained counter, no frame deduplication.

  4. 60-90 min

    Calculate exact approach powers and classify outcomes; quiz and exit ticket.

    Look for: Strict +/-2 comparisons, actual FR bias, and completion distinct from timeout.

Observation notebook

Notebook: autonomous evidence, counters, commands, and stop reason
Phase / elapsed timeSelected alliance / foundRange / txcentered or doneDecision
Acquire / 0.2 sRed / true50 in / +3 degreesselectedId 0End acquisition; retain red
Center / within 6 sRed / falseOld values not usablecentered remains 2Four zero requests
Approach / within 8 sRed / true24 in / any reported txdone trueFour zero requests; range threshold reached
Approach / 8 sRed / true30 in / 0 degreesdone falseTimeout, not arrival

Mark freshness as unverified. Record range change separately from tape-measured chassis travel; a timeout or STOP is never relabeled successful completion.

Troubleshooting · stop before investigating

Acquisition stops without choosing a target.
Check for a matching pair of halves, pipeline contents, device mapping, and the 3-second maximum. Seeing many same-half tags is insufficient.
A nearer blue target does not replace acquired red.
That is the selecting=false policy. Only the chosen alliance can restore found during centering and approach.
Five centered checks arrive implausibly fast or survive a dropout.
The source counts loops without frame deduplication and omits loss reset. Record the limitation rather than claiming five fresh consecutive frames.
A robot direction would disagree with TeleOp.
Keep physical outputs disabled; compare BR FORWARD versus REVERSE and inspect mounting and encoder mode. Do not assume a shared hardware profile.
Display says distance traveled but independent tape disagrees.
The display is startRange-currentRange, not direct odometry. Check camera offset, target motion, height, and pose projection before interpreting it.

Exit ticket & assessment

  1. Name the three phase time limits.
  2. Explain the counter behavior on missing versus off-center targets.
  3. State what <= 24 measures and why an educational label is not approval to run.

Assessment: Require a correct phase trace, matching-half selection, counter-loss explanation, exact powers at +/-2 boundaries, and outcome classification. Students must recognize absent freshness/wall guards and the autonomous-specific direction profile.

Extension challenge: On paper design a comparison of camera range change, independent tape displacement, and verified fresh-frame counts. Describe improvements as proposals without editing the supplied Blocks or deploying.

Teacher key · discuss after students predict

Timer and counter trace

Acquisition exits on first selected center or at 3 seconds; center has 6 seconds; approach has 8. Counts 1,2,missing,3,4,5 can reach the gate because missing does not reset. A found +3 result resets to 0.

Approach outputs

At range 30: tx +3 gives 0.30/0.26/0.30/0.20; +2 and -2 give 0.25/0.31/0.25/0.25; -3 gives 0.20/0.36/0.20/0.30. Loss is zero; exactly 24 with found sets done.

Range interpretation

The 0.30/0.40/0 pose gives 0.50 m, about 19.685 inches. The midpoint practice gives about 39.57 inches and +5.71 degrees. A 16-inch range reduction is not independently verified robot travel.

Threshold guard

targetRange is assigned 24, so targetRange >= 10 always passes. Its else label about already being within 24 is not a measured current-range branch; the actual <=24 check is inside approach.