Cookie CodersFTC Team 39092

Autonomous · FTC Blocks + Scratch // Student lesson

Auto-Learn-NestedLoops
One flower. Four visits.

Code Lab / Auto-Learn-NestedLoops

Nest a sensor-controlled extraction loop inside a four-flower visit loop. Request extraction only while a fresh REV 2m distance reading suggests pollen remains, and stop when empty or when this flower's five-second budget expires. Use the Scratch puzzle to make the extraction and travel actually happen in a classroom simulation.

NestedLoopsStudy is disabled and read-only: it reads a real REV distance sensor but only reports intakeRequested. It does not move, extract pollen, or navigate to another flower. A range sensor cannot count hidden pollen or identify its colour. Sensor mounting and loaded/empty calibration determine whether this approach is usable.

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

Mission control

Read, predict, compare, explain.

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

How can one loop know when to leave a flower, while another loop remembers which flower comes next?

  • Nested loops
  • REV distance sensor
  • Per-flower deadlines
  • Perimeter routes

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

How can one loop know when to leave a flower, while another loop remembers which flower comes next?

By the end, you can…

  • Distinguish the outer four-visit loop from the inner one-flower extraction loop.
  • Refresh a REV distance reading, validate it, and distinguish pollen, empty and unknown.
  • Start one five-second budget per flower and stop the request on every exit.
  • Calculate perimeter travel in centimetres without driving through the HIVE frame.
  • Build and test a native Scratch nested-loop program rather than copy a timed intake sequence.

01Give a distance reading a calibrated meaning

Actual Blocks for this section
Blocks for Give a distance reading a calibrated meaning
Blocks to noticeHover, focus or tap a block to see what it does.
  • Fictional maximum near-pollen return in cm; calibrate actual mounting before hardware use.
  • Fictional 12..16 cm empty-backstop band; nearer gaps and farther returns remain unknown.
  • Wait for Driver Station START; no actuators are enabled.

Mount the REV sensor so pollen interrupts its beam and an empty flower exposes a known backstop. Test full, partly full and empty flowers at the same robot pose. The study's <=8 cm and 12..16 cm constants only explain the comparisons. They are not usable hardware calibration. Setup clears fault and intakeRequested and waits for START; no actuator writes exist.

For example: In a paper trace, 6 cm suggests pollen and 14 cm suggests the empty backstop. A real empty flower might return no valid range at all; that must remain unknown, not empty.

Think first

Does a 6 cm reading prove there are exactly four yellow pollen in the flower?

Show Answer

No. It is one range return. Colour, count, occlusion and remaining hidden pieces are not established by a distance sensor.

02Count four visits, not four sensor samples

Actual Blocks for this section
Blocks for Count four visits, not four sensor samples
Blocks to noticeHover, focus or tap a block to see what it does.
  • Inclusive outer visit counter: 1, 2, 3, 4.
  • Do not enter another visit after STOP or a sensor fault.

The outer loop counts visits inclusively: 1, 2, 3, 4. Its body contains a complete inner extraction loop. The classroom order is F3, F1, F4, F2, matching the existing Scratch map orientation. A timeout permits the next visit; a sensor fault skips later bodies. Driver Station STOP also prevents later bodies from running.

For example: Visit 1 can sample its sensor 50 times. That still counts as one flower visit, not 50 flowers. Four flowers total means the first flower and three others.

Think first

Should flower increase after every sensor reading?

Show Answer

No. Increase the visit index only after the inner loop exits, its request is stopped, and its result is recorded.

03Travel around known geometry before sampling

Actual Blocks for this section
Blocks for Travel around known geometry before sampling
Blocks to noticeHover, focus or tap a block to see what it does.
  • Report the planned visit; this is not a drive instruction.
  • Send the planned visit to the Driver Station.

The Blocks study reports a planned visit; it does not drive there. In Scratch, go to nested flower uses actual drive/turn commands on the existing autonomous map. The supplied outer loop scores preloads first and returns to the hive between flowers because the hopper holds only four. The route table is a separate collection-only geometry exercise starting at (150,-150) cm, not the scoring run's full distance. Coordinates are rounded robot service points, not flower centres; the field centre is (0,0), +x right, +y north.

For example: From F3 service (150,-59) to F1 service (59,150), go north 209 cm to (150,150), then west 91 cm: 300 cm total. A roughly 228 cm diagonal crosses the central frame region and is not the chosen route.

Think first

Does the centre-to-centre distance between two flowers equal the robot's drive command?

Show Answer

No. Use service poses, the current robot position, mounting offset and clear waypoints. A geometric shortest distance is not automatically a safe path.

04Start a fresh clock once per flower

Actual Blocks for this section
Blocks for Start a fresh clock once per flower
Blocks to noticeHover, focus or tap a block to see what it does.
  • Store the OpMode runtime once after arrival; subtract this later for elapsed seconds.
  • Clear the previous flower's empty flag before its first reading.

After arriving, store the current OpMode runtime in flowerStart and clear the previous flower's empty flag. Elapsed is getRuntime minus flowerStart. Do not reset the global runtime or update flowerStart inside the extraction loop. Starting after travel gives each flower its own budget rather than spending it on the drive.

For example: Arrive at 10.0 seconds: the cutoff is 15.0. Arrive at the next flower at 18.0: its cutoff is 23.0. The clocks do not share one five-second allowance.

Think first

What if flowerStart is set to the current time on every inner-loop iteration?

Show Answer

Elapsed stays near zero, so the timeout no longer bounds extraction.

05Continue only while every permission is true

Actual Blocks for this section
Blocks for Continue only while every permission is true
Blocks to noticeHover, focus or tap a block to see what it does.
  • Continue only while all permissions hold; any false part exits.
  • Clear the telemetry-only request before acquiring a new sensor reading.

A while loop continues only while all four conditions hold. Stopping uses the opposite rule: empty OR elapsed >= 5 OR fault OR STOP. Clear the request before the new sample. Even after sampling, recheck active and elapsed before setting it true. The 20 ms sleep yields between readings; this is a sampled software deadline, not a certified hard real-time stop.

For example: At elapsed 4.99 seconds with pollen, a request can be true. At exactly 5.00, it cannot. Empty on the first sample requests no extraction at all.

Think first

Would repeat until empty AND elapsed >= 5 stop promptly on an empty flower?

Show Answer

No. AND waits for both events. Scratch needs empty OR timeout (plus fault and STOP) so either event ends extraction.

06Read again and keep unknown separate from empty

Actual Blocks for this section
Blocks for Read again and keep unknown separate from empty
Blocks to noticeHover, focus or tap a block to see what it does.
  • Get a new range in centimetres from the named real REV sensor.
  • Reject nonpositive, non-finite and beyond-model readings using comparisons.
  • Interpret a calibrated near return, empty-backstop return, or unknown gap separately.
  • Yield for 20 milliseconds between cycles; this is not a hard real-time guarantee.

The body gets a new REV range every cycle. The study accepts only positive readings at most 200 cm: NaN, infinity, nonpositive and beyond-model readings fail the comparisons. With the teaching constants, <=8 suggests pollen, 12..16 inclusive suggests the empty backstop; (8,12) and >16 are unexplained. A far wall is not the calibrated empty backstop. Invalid or ambiguous means fault, not empty. A sensor-return envelope alone does not prove sensor health or freshness.

For example: Readings 6, 6, 14 cm give request true, true, false and an empty exit. Reading 10 cm or 0 cm instead produces a fault and aborts later visits. A frozen plausible 6 cm reading is limited by the timeout but not diagnosed as healthy.

Think first

If a disconnected sensor returns zero, should the robot proceed as though the flower is empty?

Show Answer

No. Zero is invalid. Clear the request, report the fault and stop later visits; do not silently turn missing evidence into empty.

07Stop, label the outcome, then move on

Actual Blocks for this section
Blocks for Stop, label the outcome, then move on
Blocks to noticeHover, focus or tap a block to see what it does.
  • Clear the request for empty, timeout, fault and STOP; never drive between flowers with extraction requested.
  • Report actual empty evidence rather than treating timeout as success.
  • Report this flower's elapsed time, not the entire route clock.

Every inner-loop exit clears the request, then reports empty and elapsed. A timeout can leave pollen behind. A fault requires investigation and suppresses later visit bodies. The read-only Blocks study is intentionally not a motor controller. In Scratch, finish nested flower stops the intake and extractor, labels EMPTY/TIMEOUT/FAULT/STOP and records one completed visit.

For example: In JAM mode, F4 retains four pollen and finishes with TIMEOUT after its own five seconds. The next flower can still be visited. In FAULT mode, F1 fails and later flowers remain unvisited.

Think first

Can four visits be completed without extracting every pollen?

Show Answer

Yes. A timeout is a completed attempt, not a successfully emptied flower. Keep visit count, remaining inventory and outcome separate.

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.

Your Scratch challenge: leave the inner loop correctly

Load the blank SB3 into the Scratch 3 editor with File → Load from your computer. No account required. Select YOUR NESTED LOOPS - EDIT MY BLOCK and replace the placeholder under extract this flower - STUDENT CHALLENGE. The outer four-visit loop, travel and scoring are supplied; your missing inner loop runs inside it.

Controls: green flag initializes; N resets and runs the untimed nested exercise; M changes NORMAL/JAM/FAULT while idle; X requests STOP and disables motion/extraction. Leave the original manual and A/P/Space controls idle during N. The Scratch red stop button halts the VM but is not evidence that your cleanup blocks ran. Use X to demonstrate program cleanup.

Known field lengths, planned robot travel

Top-down BIOBUZZ field with flower centres in centimetres: F1 (59, 173), F2 (-59, -173), F3 (173, -59), F4 (-173, 59). Origin (0, 0) is at field centre; positive X points right and positive Y points north.
Flower centres in the existing Scratch map's coordinate frame, rounded to centimetres. These are not the robot service points below: for example, F3 is at approximately (173, -59), while its planned robot service point is (150, -59).

The nominal BIOBUZZ field is 144 inches (365.76 cm) across, or six 24-inch (60.96 cm) tiles. These rounded service poses use the existing Scratch map orientation, with (0,0) at field centre, +x right, +y north. They are not surveyed flower centres or a calibrated hardware route.

Start at (150,-150) cm; follow perimeter waypoints around the central frame
VisitFlowerService (x,y) cmTravel from previous poseLength
1F3(150, -59)North 91 cm91 cm
2F1(59, 150)North 209 cm, west 91 cm300 cm
3F4(-150, 59)West 209 cm, south 91 cm300 cm
4F2(-59, -150)South 209 cm, east 91 cm300 cm

Collection-only paper route: 991 cm. This excludes scoring and returns. The actual Scratch run starts by scoring preloads and returns to the hive between flowers to respect the four-piece hopper, so its total is longer. The retained map has its own collision model, not official field collision CAD. Check real mounting offsets, robot swept volume, assembly tolerances and obstacles before hardware motion.

Teacher reference: separate worked Scratch solution

Make a prediction and try the blank puzzle first. The separate worked solution uses the same retained map and completes the inner loop in the challenge My Block.

Download worked Scratch solution

Map sources: current official BIOBUZZ manual and official field CAD. This puzzle adapts our existing autonomous Scratch map, preserving its art, finite inventory, hopper, scoring and physics. The added REV range is simulated: 6 cm when loaded, 14 cm when empty, invalid away from the selected flower. N is an untimed lesson, not a real REV sensor or a proven match strategy.

continue = active AND NOT fault AND NOT empty AND elapsed < 5
The FTC while condition; any false permission ends this flower's extraction.
Scratch stop = Empty OR Elapsed >= 5 OR Fault OR Stop
Use repeat until with OR, not AND. Read the sensor once before entering and again inside.
elapsed = current time - flowerStart
Capture flowerStart once after arriving at each flower. Do not reset it in the inner loop.
1 inch = 2.54 cm; 24-inch tile = 60.96 cm; 144-inch field = 365.76 cm
Nominal full-field dimensions. Survey actual assembly and clearances before hardware navigation.
91 + 300 + 300 + 300 = 991 cm
Collection-only paper route from (150,-150). The actual Scratch exercise includes preload scoring and hive returns between visits, so travels farther.

1. Build the Scratch puzzle

Load the blank SB3 using File > Load from your computer. Select YOUR NESTED LOOPS - EDIT MY BLOCK. Replace the Coach placeholder under define extract this flower - STUDENT CHALLENGE. The supplied RUN NESTED stack repeats four visits; put your inner repeat-until loop inside this called My Block. Set Nested start to timer once; turn the extractor servo on only if Nested stop = 0 and Active = 1; call read nested REV model. Repeat until Nested empty = 1 OR Nested elapsed >= 5 OR Nested fault = 1 OR Nested stop = 1 OR Active = 0. Inside: set intake motor 1, wait 0.02 seconds, read nested REV model again. Afterwards call finish nested flower. All Nested permission flags are numeric 0/1. Keep the original engine and travel/scoring helpers intact.

2. Prove three outcomes

Green flag initializes; N resets and runs the untimed nested exercise; M cycles NORMAL/JAM/FAULT while idle; X requests STOP and disables further motion/extraction. Aim acquires fresh tags and aligns in one call; no separate Focus is needed. Do not use manual driving or the original A/P/Space controls during N. Do not reset Scratch's shared timer: store timer in Nested start. NORMAL starts all four flowers full: expect Flower remaining [0,0,0,0], 16 flower pickups, four EMPTY results and an empty hopper after scoring. JAM stalls F4: expect [0,0,0,4] in F1/F2/F3/F4 order, 12 flower pickups and third result TIMEOUT. FAULT fails F1: expect [4,4,0,4], four pickups and results EMPTY, FAULT, unvisited, unvisited. N resets the original finite inventory on each run.

3. Trace the exact boundary

On paper test valid pollen at elapsed 4.99 and 5.00 seconds, an initially empty flower, zero range, 10 cm ambiguity and a stuck 6 cm reading. Record request, outcome and whether later visits are allowed. Explain why a five-second timeout does not prove empty.

4. Measure the map route

Draw the four service points and three corner waypoints in centimetres, with the field centre at (0,0). Label 91 and 209 cm legs. Convert 300 cm to inches (about 118.11). Compare the F3-to-F1 diagonal with the 300 cm perimeter route and explain the central obstruction.

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 / 8 correct · 0 / 8 answered

0
0
Question 1What does one outer-loop iteration represent?

Question 2Which Scratch repeat-until condition stops when either empty or out of time?

Question 3Where should Flower start be set?

Question 4Pollen is still detected at exactly 5.00 seconds. What is the request?

Question 5The REV sensor reads 0 cm. What should this study do?

Question 6With teaching thresholds 8 and 12 cm, what does 10 cm mean?

Question 7What is the chosen F3 service to F1 service travel?

Question 8What does the downloadable FTC Blocks study actually control?

Reset clears every choice, explanation, and score.

Adult supervision · setup · safety

Supervisor notes

For supervisors: 75-minute teaching plan & robot setup

Before the robot is used

Safety: Use paper and Scratch first. Keep NestedLoopsStudy disabled. It contains no motor or servo writes and does not drive between flowers. Any separately reviewed real sensor-only observation must be stationary, secured and adult-supervised. Never infer clear space or guaranteed empty inventory from a range reading. Unknown is not empty; zero power would not imply instantaneous mechanical stop.

Required hardware & dependencies

  • Scratch 3 editor (online or offline) and the blank BIOBUZZ-Nested-Loops-Puzzle.sb3. No Scratch account is necessary.
  • For a separately authorized read-only observation: REV 2m distance sensor configured pollen_distance, Control Hub/Driver Station and a stationary representative flower fixture.
  • Ruler, graph paper and loaded/partly loaded/empty target arrangements. Keep hands out of mechanisms and isolate actuator power.

Configure pollen_distance as a REV 2m distance sensor. The sample's <=8 cm pollen and 12..16 cm empty-backstop band are fictional teaching values, not measured settings. An invalid or ambiguous return stops the request and aborts later visits. No helper ZIP, motor or servo is required for this read-only study; do not connect its request to actuators without a separate reviewed implementation.

Robot setup checklist

  1. Download the blank puzzle, not the separate solution. Both puzzles start with the chassis facing north (Heading 0) and the launcher marker pointing into the starting hive's open face. This visual alignment does not replace Aim, which acquires fresh tags and aligns in one step. Edit only extract this flower - STUDENT CHALLENGE in YOUR NESTED LOOPS - EDIT MY BLOCK; trace the supplied outer repeat 4.
  2. Show Nested empty/valid/fault/stop/running as numeric 0/1. Explain the simulated 6 cm loaded / 14 cm empty model, valid only near the selected flower; it is not hardware evidence. Keep manual controls idle during N.
  3. Inspect the disabled native source and its no-actuator boundary. Survey sensor mounting, occlusion and an actual empty backstop before selecting any real thresholds.

75-minute teaching sequence

  1. 0-10 min

    Predict a loop within a loop

    Look for: One inner loop per visit, not one flower per sensor sample.

  2. 10-25 min

    Trace the native sensor, unknown and deadline decisions

    Look for: Fresh reading each cycle; exact five-second comparison; no invented sensor count.

  3. 25-50 min

    Build the blank Scratch puzzle

    Look for: OR stop condition, clock outside inner loop, intake off before travel.

  4. 50-65 min

    Run NORMAL, JAM, FAULT and X-stop cases

    Look for: Different outcome labels, remaining counts and cleanup.

  5. 65-75 min

    Explain 991 cm route and answer quiz

    Look for: Perimeter legs, consistent units and study-versus-hardware distinction.

Observation notebook

Record attempts, not just successful collections
CaseCompleted visitsFlower pickupsRemaining F1/F2/F3/F4Evidence
NORMAL4160, 0, 0, 0Four EMPTY results; actual finite pieces transferred and scored; hopper empty
JAM4120, 0, 0, 4F4 TIMEOUT around 5 s; next flower still attempted
FAULT244, 4, 0, 4F1 FAULT; last two remain unvisited; intake off
X / STOPDepends on stop momentNo further transfersRecord actual remainingIntake off; no new visits

This project retains the existing BIOBUZZ autonomous map, artwork, collisions, finite pollen, four-piece hopper and hive scoring. N is an untimed exercise with scoring between flowers, not a 30-second match strategy. The added REV range model and five-second transfer guard are teaching simulations; neither proves real sensor calibration nor repairs an incorrect student loop. Pickup counts exclude the four starting preloads.

Troubleshooting · stop before investigating

Empty flower waits five seconds
Read before the inner loop and use OR, not AND, in repeat until. Compare Nested empty to numeric 1.
JAM never exits
Move Nested start assignment outside the inner loop and refresh Nested elapsed through read nested REV model inside it.
No completed visits are recorded
Replace the placeholder in the challenge My Block and call finish nested flower after your inner loop; do not rebuild or delete the supplied outer stack.
Range changes but nothing moves on hardware
Intentional: this native study only reports requests and contains no actuator or route output.
Real empty target yields an invalid return
Do not label it empty. Investigate mounting/backstop and whether this sensor can reliably distinguish all partly loaded states.

Exit ticket & assessment

  1. Explain both loops.
  2. Write the OR stopping condition and locate the timer assignment.
  3. Give one timeout-versus-empty distinction and one range-sensor limitation.

Assessment: Require the NORMAL/JAM/FAULT observations and an X-stop demonstration, plus correct explanations of OR, per-flower timing and unknown readings. A finished route alone is insufficient.

Extension challenge: Trace an initially empty flower and a full hopper: empty should skip intake; a full hopper cannot accept another finite piece and must time out rather than imply empty. Investigate partially occluded pollen and prove when a distance-only classifier cannot establish empty; do not compensate with an arbitrary wider threshold.

Teacher key · discuss after students predict

Two clocks, two loops

The outer count tracks visits; a stored arrival time gives each inner loop a five-second budget. Travel is outside that budget.

Sensor evidence

Positive bounded readings still need calibrated interpretation. Invalid, ambiguous or hidden inventory cannot support an empty claim.

Route arithmetic

The first leg is 91 cm and each following visit is 209+91=300 cm: 991 total. Rounded Scratch coordinates are not surveyed robot poses.

Expected outcomes

NORMAL collects 16 flower pieces and empties the hopper through actual scoring. JAM collects 12 and leaves four at F4. FAULT collects four at F3 and aborts after F1. Four preloads are separate from flower pickups.