Two things at once
A program does not have to be one long column of blocks. Several stacks can run at the same time, each doing its own job — one driving, one watching a sensor, one keeping the display up to date.
How it is done
Give each stack its own hat block. Every stack beginning with when program starts starts at the same instant — not one after another — and from then on they run alongside each other.
Nor is it limited to two. Below, three stacks run together: a Medium Motor turning an attachment, the status light flashing, and the drive base rolling. Watch the arrows at the top — they all begin at once, and no stack waits for any other.
when program starts :: events hat [A v] start motor [clockwise v] :: motors when program starts :: events hat forever set status light to [green v] :: display wait (0.5) seconds set status light to [red v] :: display wait (0.5) seconds end when program starts :: events hat start moving [straight: 0] :: movement
Written down they have to go one under another, because a page is a column — but that is an accident of paper. On the Brick they sit side by side, and nothing in the first stack happens before anything in the third.
The rule: one owner per thing
Parallel stacks go wrong when two of them try to control the same thing. Use the switch below to take the wheels away from the third stack and point it at motor A, which the first stack is already driving.
the program starts — all of these begin here
stack 1 · Medium Motor
stack 2 · status light
stack 3 · drive base
Every stack is highlighted at the same moment on purpose — that is what running in parallel looks like. The switch above changes only what the third stack controls.
With one owner each, all three stacks are highlighted at the same instant and all three jobs get done. With two owners, motor A is handed contradictory orders hundreds of times a second and shivers instead of turning — and notice the second cost, which is easy to miss: the wheels now have nobody driving them. A stack that goes to fight over someone else’s motor has abandoned its own job. Nothing reports an error either way; as far as the Brick is concerned every stack is working perfectly. The same happens to a display line or a variable that two stacks both write to.
The discipline is simple: give each stack sole ownership of what it controls. One stack owns the motors, another owns the screen, another watches the sensors and tells the others what it found — which is what broadcasting is for.
More control tutorials
- Waiting — Pause for a length of time, or until a sensor says so.
- Repeating — Do something a set number of times, or over and over for ever.
- Making a decision — Do one thing or another, depending on what a sensor reports.
- Comparing and combining — Compare two numbers, and join two conditions with and / or.
- The Timer — Measure how long something has taken.