The Candy Vending Machine: a hopper of sweets, an auger that releases exactly one, a gate that accepts coins, and a Colour Sensor that watches the chute to confirm something actually came out.
Every model so far could be wrong. This one can be unfair — it can take a coin and give nothing back, and no amount of “the code ran without errors” makes that acceptable.
By the end of the lesson your machine will never take payment without delivering, and never deliver without payment — including when you interrupt it half-way through.
In the real world 5 min
Where you have seen it
A vending machine holds your money without spending it until the product has fallen. Many now have an infrared beam across the chute: if nothing breaks the beam, the machine hands the money back rather than keeping it.
A vending machine. Photo: Healthyvending / Wikimedia Commons (public domain).
A cash machine is stricter still. It counts the notes, then opens the shutter, and only then debits the account. If the shutter jams the notes are retracted and nothing is charged. The order of those steps is not an accident.
Why it is built that way
Because power cuts, jams and people pulling plugs are normal, not exceptional. A machine that is only correct when nothing goes wrong is not correct at all.
So real machines follow one rule: take the irreversible step last, and confirm the reversible ones first. Dispensing can be checked. Keeping money cannot be undone by a machine with no arms. Therefore dispense, confirm, then keep.
What would go wrong without it
Take the coin first and any jam turns into theft. Dispense first with no check and a customer who never inserted a coin gets a free sweet. Both are single-line differences in the program, and both destroy trust in the machine.
Do the undoable thing last, and only after you have proof the rest worked.
The main concept — a transaction 6 min
A transaction is two things that must both happen or neither. The machine takes payment and gives a sweet. One without the other is a failure even though every block ran perfectly.
The three states, and the dangerous one
State
Meaning
Safe to stop here?
Idle
No coin held, nothing owed.
Yes — nobody is out of pocket.
Holding
Coin received, sweet not yet delivered.
No. Stop here and the customer has paid for nothing.
Settled
Sweet delivered, coin kept.
Yes — both sides got what they were owed.
The whole job is to spend as little time as possible in Holding, and to have a way out of it that returns the coin. That is what a refund is: a planned exit from the dangerous middle state.
Delivery has to be proved, not assumed
“I turned the auger” is not the same as “a sweet came out”. The hopper empties; sweets jam; the auger sometimes turns past two at once. The Colour Sensor watching the chute is what turns an assumption into evidence.
// turn the auger, then WAIT for proof, with a deadline
[A v] run [clockwise v] for (1) [rotations v] at (40) % speed :: motors
reset timer :: control
set [delivered v] to (0) :: variables
repeat until <<(delivered) = (1)> or <(timer) > (2)>>
if <([3 v] reflected light intensity) < (25)> then
set [delivered v] to (1) :: variables
end
end
A sweet passing the sensor darkens it. No darkening within two seconds means no sweet — and the machine now owes a refund.
That deadline is Lesson 40’s idea of a timeout doing moral work: without it the machine waits for ever for a sweet that is never coming, holding the customer’s coin the whole time.
Money in the balance
Keep a running takings count, and increase it only in the settle step — never when the coin arrives. Then the number on the screen is always the money the machine is entitled to, and a refund costs nothing to account for because it was never counted.
ComponentData6 min
Variables
Why anybody needs one
Long before there were computers, people had exactly this problem. A shepherd counting sheep through a gate, a trader counting sacks of grain, a builder counting days — none of them can hold the number in their head while they get on with the work. So they scratched a mark on a wall, cut a notch in a stick, or wrote a number on a piece of paper. The number lived outside the person, in a place they had agreed on, and they could go back to it, read it, and change it.
Better still, once the number is written down somebody else can use it. Watch these two: one of them counts and writes, the other never sees a single animal and simply reads the wall.
Abby never remembers the numberBen never sees a henThe wall holds it for both
Abby has a gate and a wall. Before a single hen comes through she chalks 0 on the wall — that is where the number is going to live.A hen goes through. Abby rubs out the 0 and chalks 1. Another goes through, and she does it again.Three hens have been through, and the wall says 3. Abby is not remembering the number — she is reading her own wall each time and writing the next one.Ben has been at the market all morning. He has not seen one hen. He walks up, reads the wall, and knows the answer — without asking Abby anything.That is a variable. Not a number in somebody's head, but a place both of them agreed on: one writes to it, the other reads from it, and it keeps the number in between.Finished. Abby wrote, Ben read, and the wall is what joined them up.
the wall holds it
Notice what never happens: Ben never asks Abby. He does not need to — the number is not in her head, it is on the wall, and the wall is there for anyone who needs it.
Neither Abby nor Ben is holding the number — the wall is. And notice what never happens: Ben does not ask Abby. He does not need to, because the count is not in her head. It is in a place they both agreed on, which is what makes it useful to more than one of them.
That is all a variable is. The robot cannot hold a number in its head either, so you give it a wall of its own, write a name at the top so everyone knows which wall is which — score, count, degree_turn — and the program can read what is on it and write something new. One part of the program writes; another part reads. Exactly Abby and Ben.
The paper, and the two things you can do to it
Say we are counting rotations of a motor. Before we start we write 0 on the paper. Every time the motor completes a turn we cross out what is there and write one more: 0 becomes 1, then 2, then 3. That is change — it has to read the old number to work out the new one.
set is the other thing you can do, and it is completely different: rub the whole paper out and write the number you want. It does not care what was there. Press the buttons and watch what happens to the crossings-out.
score
0
The paper starts blank, so we write 0 on it. That is what a variable is: a place to keep a number while the robot works.
change leaves a trail — every value follows from the one before it. This is what counting is.
set wipes the sheet. Use it to start a count, never to continue one.
Press set score to 0 after counting up a few times and watch the whole history vanish. That is what happens to a count when a set block ends up in the wrong place — and it is the commonest variable bug there is.
Blocks reference
Block
What it does
set [count v] to (0)
Puts a value in, replacing whatever was there.
change [count v] by (1)
Adds to what is already there.
(count)
Reports the current value, for use in a comparison or on the display.
Set, or change?
set replaces; change adds. Counting things needs change. Starting a count needs set. Both programs below have both blocks — the only difference is whether the set block is inside the loop or above it.
set before the loop
when program starts
set count to 0
repeat 4
A run clockwise for 1rotations
change count by 1
set inside it
repeat 4
set count to 0
A run clockwise for 1rotations
change count by 1
Before the loop: counted 0Inside the loop: stuck at 0
Both programs count the turns of a motor. The left sets the count to zero before the loop; the right sets it inside.Turn 1. Both counters read 1, and so far the two programs agree.Turn 2. The left count is 2. The right was set back to zero at the top of the loop, so it is 1 again.Turn 3. The left reads 3. The right still reads 1.Turn 4. The motor turned four times on both robots — only one of them counted them.Finished. Four turns, and one of the two counts is fiction.
stopped
Both programs contain both blocks. Only the position of set [count] to 0 is different.
The count on the right is not broken; it is being told to start again on every pass. Each time round the loop it is wiped back to zero and then changed by one, so the honest answer is always 1 — while the motor cheerfully turns four times. A counter stuck at 1 almost always means a set block that has slipped inside the loop.
Anything oval is a number you can pick up
EV3 Classroom tells you what a block does by its shape, and once you have noticed that, a whole set of questions answers itself:
Oval — reports a number. The blue degrees counted, the timer, a distance, your own variable.
Pointed — reports true or false. These go in an if or a wait until, not in a variable.
Block-shaped — does something. These stack up; they do not fit inside anything.
So when a slot is oval, any oval fits it — and it does not matter in the least where that number came from. You can take the motor’s own A degrees counted and keep it in a variable you named degree_turn, then compare that with a number later. Pick an oval below and watch the same one drop into all three kinds of slot.
pick an oval
the same oval fits all three
set degree_turn to A degrees countedkeep it in a variable of your own
A degrees counted+10do arithmetic with it
A degrees counted>50compare it with a number
Every one of those slots is oval-shaped, and A degrees counted is an oval — so it drops in. Nothing about where the number came from matters.
This is what makes a variable more than a counter. A sensor reading is true only at the instant you read it; copying it into a variable freezes it, so the robot can compare where it is now against where it was when something happened:
when program starts :: events hat
[A v] reset degrees counted :: motors
set [degree_turn v] to ([A v] degrees counted :: sensors)
start moving [right: 30] :: movement
wait until <(([A v] degrees counted :: sensors) - (degree_turn)) > (400)>
stop moving :: movement
Read the condition aloud: how far the motor has gone now, minus where it was when we started, is more than 400. Both are ovals, so both can go into a subtraction, and the subtraction is an oval too — which is why it can go into a comparison. Ovals nest inside ovals as deep as you need.
Reset at the start, every time
A variable keeps its value after the program ends. Run the program again without setting it back and the second run begins where the first left off — the count starts at 14, the robot thinks it has already done the job. Every variable a program changes must be set to its starting value at the top.
Why it matters
A variable is the difference between a machine that repeats a fixed routine and one that responds to how things have gone — counting parts, tracking a score, remembering where it started.
ComponentSensing5 min
The Touch Sensor
The Touch Sensor is the simplest input the EV3 has: a button that is either pressed or not. That sounds trivial, but it is how a robot knows it has hit a wall, reached the end of a track, or been told to start by a person.
released
pressed
The red button out, and the same sensor with it pushed in. These two states are the entire output of this sensor — there is nothing in between.
Blocks reference
Block
What it does
wait until <[1 v] is pressed? :: sensors>
Holds the program here until somebody presses the sensor.
<[1 v] is pressed? :: sensors>
Reports true or false. Drop it into a condition to make a decision rather than a wait.
[1 v] when [bumped v] :: events hat
Starts a whole stack of its own. The dropdown chooses the moment: pressed, released or bumped.
Three different events
A button is not only “pressed”. One press is three things: the moment it goes down, the time it stays down, and the moment it comes back up. Watch what a single press does to three programs at once.
when program starts
forever
if 1 is pressed? then
change count by 1
versus two hat blocks
1 when pressed
1 when bumped
0is pressed? in a loop0when pressed0when bumped
In a loop: 0 answers from one pressBumped: exactly one
Nobody is touching the sensor. All three programs are watching it.A finger presses the button. Watch the red button go in — a couple of millimetres is the sensor's entire movement.The finger is still down. The loop checking «is pressed?» has already run hundreds of times, and every one of them counted.The finger lifts. Only now does «bumped» count, because bumped means pressed AND released.One press. Three completely different answers.Finished. The same press, counted three ways.
released
The middle counter is the one that surprises people. Nothing is wrong with it — a loop really does check that fast, and every check really is a separate answer.
Nothing there is broken. A loop really does get round hundreds of times a second, and each time it asks is pressed? the honest answer is still yes — so if that loop plays a sound or counts something, it does it hundreds of times from one finger. The two hat blocks each fire once, and they fire at different moments: pressed the instant the button goes down, bumped only when it comes back up.
The three options, and what each is for:
Pressed — the button is down right now. Good for “hold to run”.
Released — it is up again. Good for acting when somebody lets go.
Bumped — pressed and released. This is what you want for “click to start”, because it will not fire repeatedly while a finger stays down.
The classic bumper
when program starts :: events hat
set movement motors to [B v] and [C v] :: movement
start moving [straight: 0] :: movement
wait until <[1 v] is pressed? :: sensors>
stop moving :: movement
The robot drives until something presses the sensor. Note that the movement is started unmeasured on purpose — the sensor decides when to stop, not a distance.
Why it matters
Touch sensors are everywhere in machines you cannot see into: a lift knows the doors are shut, a printer knows the lid is closed, a washing machine will not spin until it is latched. They are safety devices as much as inputs.
ComponentSensing6 min
The Colour Sensor
The Colour Sensor looks down at a surface and can answer three quite different questions: what colour is this?, how bright is this? and how light is the room? Choosing the wrong one is the usual reason a line-following robot refuses to work.
front
side
The sensor has its own lamp beside its detector. That is why it must sit close to the surface and at a steady height — lifting it changes the reading even though the surface has not changed.
Blocks reference
Block
What it does
([3 v] color :: sensors)
Reports which colour it sees, from a short list — red, blue, green, black, white and a few more.
([3 v] reflected light intensity :: sensors)
Reports how bright the surface is, as a number from 0 (black) to 100 (white).
<[3 v] is color [red v]? :: sensors>
Reports true or false for one particular colour.
([3 v] ambient light intensity :: sensors)
Reports how much light is falling on the sensor, 0 to 100, with its own lamp switched off.
Which colour, exactly?
The sensor does not describe a colour — it picks one from a list of eight, and that list is the whole of what it can ever say:
Reports
Means
0
no colour — too far away, or too dark to call
1 · 2 · 3
black, blue, green
4 · 5 · 6
yellow, red, white
7
brown
Anything you put under it is forced into one of those eight. There is no orange and no purple: an orange brick comes back as red or as yellow, and often as red one moment and yellow the next as the robot creeps along. Light blue and grey are the other classic pair to avoid — grey is neither black nor white, so it flips between them.
This is why colour mode is a good fit for a task you control and a bad fit for one you do not. Sorting the LEGO bricks that come in the set works, because they are made in exactly these colours. Reading a printed sheet, a coloured tile from another set, or anything pastel is asking the sensor to answer a question it does not have a word for.
Two practical points follow from how it decides. It shines its own lamp and looks at how much red, green and blue comes back, so it must be close — about half a centimetre, and no more than a centimetre. Lift it and the answer decays to 0. And because it takes those three readings before it can answer, colour mode is the slowest thing this sensor does; a robot driving quickly can pass right over a small patch without ever reporting it.
When a colour must be recognised reliably, test it. Drive the robot slowly over the real surface with color shown on the screen and watch what it actually says — including what it says at the edges between two colours, which is where the wrong answers live.
Colour, or brightness?
Both questions are asked of the same surface at the same moment. Watch the two answers travel across a strip of colours and then over the edge of a black line.
when program starts
forever
write 3 color at line 1
write 3 reflected light intensity at line 3
colour: 2 possible answers herereflected light: every value from 88 down to 8
The sensor sits a few millimetres above the surface, with its own lamp shining down.It travels across the coloured patches. One read-out names what it sees; the other says how much light came back.Now the edge of a black line. The name only ever says white or black — but the number slides all the way down, and every value in between means something.Names for sorting. Numbers for following.Finished. Same sensor, same surface, two very different kinds of answer.
reflected light 88
Watch the two read-outs over the last third of the strip. One of them changes once. The other changes the whole way across.
Over the patches, both read-outs are useful. Over the edge of the line they part company: the colour name has only two answers to give and jumps between them, while the number slides smoothly from 88 down to 8. Every value in that slide tells you how far onto the line the sensor is — which is information the name simply does not carry.
Use colour when the answer really is a name — sorting red bricks from blue ones, stopping on a green square.
Use reflected light when the answer is a matter of degree — following the edge of a black line, where the useful readings are all the greys between black and white.
A line follower built on colour names only knows “black” or “not black”, so it can only lurch. Built on reflected light it can tell how far onto the line it has drifted, which is what makes smooth following possible.
The third mode: ambient light
The first two modes both switch the sensor’s own lamp on and measure what bounces back off the surface. Ambient light intensity does the opposite: the lamp goes off, and the sensor simply reports how much light is arriving from wherever — 0 in the dark, up to 100 in bright light.
Mode
Own lamp
Measures
Points
colour
on
which of eight colours the surface is
at the surface, very close
reflected light
on
how much of its own light comes back
at the surface, very close
ambient light
off
how bright the surroundings are
wherever you want to measure
That makes it the only one of the three that is not really about the floor. A number between 0 and 100 means very little on its own, so watch the same sensor sit through five different rooms — nothing underneath it changes at any point.
the sensor’s own lamp is off — it is measuring the room
Start in the dark — a hand over the lens, or the lights off. Almost no light reaches the sensor, and it reports 0.Curtains drawn with one small lamp on. Enough to see by, and the sensor climbs to about 12.An ordinary classroom with the lights on sits somewhere around 38 — the middle of the scale, not the top of it.Move it beside a bright window and the same sensor, in the same room, reads about 72.A torch pointed straight into it pushes the reading to nearly 100 — which is how a light can be used as a signal to a robot.Finished. Same sensor, same floor underneath it — the only thing that changed was the room.
ambient 0
Nothing under the sensor changed at any point in this run. Ambient light is the one mode that is not asking about the surface at all.
Those are the shape of the scale rather than exact figures, but the shape is the useful part: a lit room is nowhere near 100, and the top of the range is reserved for a light pointed straight at the sensor. Cover it with your hand and the number drops to near zero — which is the easiest way to check the sensor is doing what you think.
Point it at the ceiling and it tells you whether the room lights are on; point it forwards and a torch will spike the reading, which is a way of signalling to a robot without touching it.
Do not reach for it as a substitute for reflected light. Room light falling on a black line and on white paper is almost the same, so ambient mode can barely tell them apart — the reason reflected light works is precisely that the sensor brings its own light and measures how much of it survives.
It is also the mode most at the mercy of the room. A reading taken by a window in the morning will not match the same spot in the afternoon, so anything built on ambient light needs measuring on the day, in the place, with the lights as they will be.
Light and height matter
Even the two lamp-on modes are affected by room lighting — a reading taken by a sunny window differs from one taken in a corner. The sensor must also sit close to the surface and at a constant height, because lifting it changes the reading even though the surface has not changed.
ComponentControl4 min
The Timer
A wait pauses for a length of time. The timer is different: it runs in the background and can be read at any moment, so the robot can know how long something has taken while it is still happening.
Blocks reference
Block
What it does
(timer)
Reports the seconds since the timer was last reset.
reset timer
Sets it back to zero, so the next reading counts from here.
The timeout — a safety net
The most valuable use of a timer is escaping a wait that might never end. A robot told to drive until it sees a wall will drive for ever if the wall is not there. Combined with a timer, it can give up:
Repeat until the wall is close or five seconds have passed. That one change turns a program that can hang into one that always finishes. Both robots below are looking for a wall that is not there.
no way out
repeat until distance < 15
start moving straight: 0
with a timeout
reset timer
repeat until distance < 15 or timer> 5
start moving straight: 0
write GAVE UP at line 1
1.2stimer212cm · distance
Both robots are told to drive until something is within 15 cm. The room ahead is empty.Three seconds. No wall. Both are still driving — and the right-hand program is also watching its timer.The timer passes 5. The right-hand robot gives up, stops, and says so.The left robot is still going. Its condition can never become true, so that block will hold the program for ever.The right-hand program finished. The left one has not, and there is nothing to say why.
timer 1.2 s
The sensor is not faulty and the program is not wrong. There is simply no wall, and only one of these two programs has a way of noticing that.
The left-hand robot is not broken, and neither is its sensor. Its condition is simply one that will never come true, so the program sits on that block for ever — with nothing on the Brick to say so. The right-hand program asks the same question with an escape route bolted on, and finishes every time.
Why it matters
Real systems time themselves out constantly — a lift that cannot close its doors eventually gives up and beeps rather than trying for ever. A robot with no timeout simply stops responding, and there is nothing on screen to say why.
Dispense, prove, then keep. Refund is the planned way out of the middle.
▶The commit pointFrom Lesson 22 — before it you can still back out cleanly, after it you are obliged to finish. Here the obligation is owed to a person.Show meHide
ComponentData6 min
Variables
Why anybody needs one
Long before there were computers, people had exactly this problem. A shepherd counting sheep through a gate, a trader counting sacks of grain, a builder counting days — none of them can hold the number in their head while they get on with the work. So they scratched a mark on a wall, cut a notch in a stick, or wrote a number on a piece of paper. The number lived outside the person, in a place they had agreed on, and they could go back to it, read it, and change it.
Better still, once the number is written down somebody else can use it. Watch these two: one of them counts and writes, the other never sees a single animal and simply reads the wall.
Abby never remembers the numberBen never sees a henThe wall holds it for both
Abby has a gate and a wall. Before a single hen comes through she chalks 0 on the wall — that is where the number is going to live.A hen goes through. Abby rubs out the 0 and chalks 1. Another goes through, and she does it again.Three hens have been through, and the wall says 3. Abby is not remembering the number — she is reading her own wall each time and writing the next one.Ben has been at the market all morning. He has not seen one hen. He walks up, reads the wall, and knows the answer — without asking Abby anything.That is a variable. Not a number in somebody's head, but a place both of them agreed on: one writes to it, the other reads from it, and it keeps the number in between.Finished. Abby wrote, Ben read, and the wall is what joined them up.
the wall holds it
Notice what never happens: Ben never asks Abby. He does not need to — the number is not in her head, it is on the wall, and the wall is there for anyone who needs it.
Neither Abby nor Ben is holding the number — the wall is. And notice what never happens: Ben does not ask Abby. He does not need to, because the count is not in her head. It is in a place they both agreed on, which is what makes it useful to more than one of them.
That is all a variable is. The robot cannot hold a number in its head either, so you give it a wall of its own, write a name at the top so everyone knows which wall is which — score, count, degree_turn — and the program can read what is on it and write something new. One part of the program writes; another part reads. Exactly Abby and Ben.
The paper, and the two things you can do to it
Say we are counting rotations of a motor. Before we start we write 0 on the paper. Every time the motor completes a turn we cross out what is there and write one more: 0 becomes 1, then 2, then 3. That is change — it has to read the old number to work out the new one.
set is the other thing you can do, and it is completely different: rub the whole paper out and write the number you want. It does not care what was there. Press the buttons and watch what happens to the crossings-out.
score
0
The paper starts blank, so we write 0 on it. That is what a variable is: a place to keep a number while the robot works.
change leaves a trail — every value follows from the one before it. This is what counting is.
set wipes the sheet. Use it to start a count, never to continue one.
Press set score to 0 after counting up a few times and watch the whole history vanish. That is what happens to a count when a set block ends up in the wrong place — and it is the commonest variable bug there is.
Blocks reference
Block
What it does
set [count v] to (0)
Puts a value in, replacing whatever was there.
change [count v] by (1)
Adds to what is already there.
(count)
Reports the current value, for use in a comparison or on the display.
Set, or change?
set replaces; change adds. Counting things needs change. Starting a count needs set. Both programs below have both blocks — the only difference is whether the set block is inside the loop or above it.
set before the loop
when program starts
set count to 0
repeat 4
A run clockwise for 1rotations
change count by 1
set inside it
repeat 4
set count to 0
A run clockwise for 1rotations
change count by 1
Before the loop: counted 0Inside the loop: stuck at 0
Both programs count the turns of a motor. The left sets the count to zero before the loop; the right sets it inside.Turn 1. Both counters read 1, and so far the two programs agree.Turn 2. The left count is 2. The right was set back to zero at the top of the loop, so it is 1 again.Turn 3. The left reads 3. The right still reads 1.Turn 4. The motor turned four times on both robots — only one of them counted them.Finished. Four turns, and one of the two counts is fiction.
stopped
Both programs contain both blocks. Only the position of set [count] to 0 is different.
The count on the right is not broken; it is being told to start again on every pass. Each time round the loop it is wiped back to zero and then changed by one, so the honest answer is always 1 — while the motor cheerfully turns four times. A counter stuck at 1 almost always means a set block that has slipped inside the loop.
Anything oval is a number you can pick up
EV3 Classroom tells you what a block does by its shape, and once you have noticed that, a whole set of questions answers itself:
Oval — reports a number. The blue degrees counted, the timer, a distance, your own variable.
Pointed — reports true or false. These go in an if or a wait until, not in a variable.
Block-shaped — does something. These stack up; they do not fit inside anything.
So when a slot is oval, any oval fits it — and it does not matter in the least where that number came from. You can take the motor’s own A degrees counted and keep it in a variable you named degree_turn, then compare that with a number later. Pick an oval below and watch the same one drop into all three kinds of slot.
pick an oval
the same oval fits all three
set degree_turn to A degrees countedkeep it in a variable of your own
A degrees counted+10do arithmetic with it
A degrees counted>50compare it with a number
Every one of those slots is oval-shaped, and A degrees counted is an oval — so it drops in. Nothing about where the number came from matters.
This is what makes a variable more than a counter. A sensor reading is true only at the instant you read it; copying it into a variable freezes it, so the robot can compare where it is now against where it was when something happened:
when program starts :: events hat
[A v] reset degrees counted :: motors
set [degree_turn v] to ([A v] degrees counted :: sensors)
start moving [right: 30] :: movement
wait until <(([A v] degrees counted :: sensors) - (degree_turn)) > (400)>
stop moving :: movement
Read the condition aloud: how far the motor has gone now, minus where it was when we started, is more than 400. Both are ovals, so both can go into a subtraction, and the subtraction is an oval too — which is why it can go into a comparison. Ovals nest inside ovals as deep as you need.
Reset at the start, every time
A variable keeps its value after the program ends. Run the program again without setting it back and the second run begins where the first left off — the count starts at 14, the robot thinks it has already done the job. Every variable a program changes must be set to its starting value at the top.
Why it matters
A variable is the difference between a machine that repeats a fixed routine and one that responds to how things have gone — counting parts, tracking a score, remembering where it started.
Say this back before moving on: “If I pull the plug right now, is anybody out of pocket?”
What’s in this build 4 min
Drop a sweet down the chute by hand and watch the Colour Sensor. How far does the reading fall, and for how long? If you cannot see it move, the machine can never prove a delivery.
Part
What it is doing here
EV3 Intelligent Brick
The till. The takings on its screen are the machine’s claim about what it is owed, and that claim must survive being argued with.
Medium Motor — the auger
One rotation should release one sweet. Medium for the crisp, precise turn — a slow one releases two.
Large Motor — the coin gate
Two positions: keep drops the coin into the till, return tips it back out. The refund is mechanical, not a message on a screen.
Touch Sensor — coin arriving
Pressed by a coin landing in the cradle. It starts the transaction — and from that instant the machine owes something.
Colour Sensor — the chute
Watches for a sweet passing. This is the only part of the machine that knows whether it kept its side of the bargain.
The coin cradle must hold the coin, not swallow it. If the coin has already fallen into the till by the time the Touch Sensor fires, there is no refund possible and the rest of the lesson cannot be built.
Ports — and the rule 4 min
Sensors go in ports 1, 2, 3, 4. Motors go in ports A, B, C, D. They are not interchangeable, and nothing will tell you politely if you swap them.
Part
Port
Why this one
Auger (Medium)
A
The precise motor, on the front port.
Coin gate (Large)
D
The strong one — it moves the till mechanism.
Coin arriving (Touch)
1
Touch stays on 1 across the course.
Chute (Colour)
3
Colour stays on 3 across the course.
Check your own build now:
Auger in A, gate in D, coin in 1, chute in 3.
Set the gate to the return position and leave it there. A machine that starts up in the keep position could pocket a coin before the program is ready.
Load the hopper and turn the auger by hand until exactly one sweet drops per rotation.
Decide what a coin is — a 2×2 tile, a real coin, a washer — and use the same object all lesson.
Connect the Brick 4 min
Two routes, and either is fine. USB is the reliable one and the one to fall back on when a room’s Bluetooth is busy; Bluetooth leaves the robot free to move, which some models need.
▶How to connect the BrickUSB and Bluetooth, step by step, with a photograph of every screen. Open it if you have not done this before — or if pairing is not working.Show meHide
USB — the reliable one
Switch the Brick on with the dark grey centre button.
Cable into the Brick’s PC port — the small square socket beside the numbered ports, not one of the numbered ones.
Other end into the computer.
Bluetooth — name it first
Do these in order. Naming the Brick after you go looking for it in the list is how groups end up driving each other’s robots.
Name your Brick. On the Brick: Settings (the spanner) → Brick Name. Type something nobody else will pick, then press the tick. Every Brick is called EV3 until somebody changes it.
Turn Bluetooth on. Settings → Bluetooth. Tick Bluetooth and Visibility. Leave iPhone/iPad/iPod unticked.
Connect from EV3 Classroom. Click the Brick icon at the top of the programming area, find your Brick by name, and click Connect.
Say yes on the Brick. It asks “Connect?” with the computer’s name — choose the tick, then accept the passkey, which is already 1234.
Where to read it. The name sits in the bar across the very top of the screen, on every screen — so you can check which Brick you are holding at any moment without going into a menu. This one is EV3VE. A Brick nobody has renamed says EV3.Step 3, and the reason step 1 exists. Three Bricks in range — read the name before you click Connect. Pairing with the wrong one is not an error: it works perfectly, on somebody else’s robot.
Step 2.Bluetooth switches the radio on; Visibility is what lets the computer find you. With Visibility off your Brick works perfectly and simply never appears in the list.Step 4. Look at the Brick. It asks whether to accept and names the computer. Choose the tick.Then the passkey, already 1234. Press the tick again and you are connected.
The two failures, every class, every time. The Brick has gone to sleep while you were building — press the centre button to wake it. Or you have paired with the group at the next table, which is why the name matters.
The long version, including Port View and how to read the port tiles, is in the Brick & Bluetooth guide.
You will be pulling the plug on purpose today. One of the tests is stopping the program mid-transaction to see who ends up out of pocket, so a cable that has to be pulled out first will get in the way — use Bluetooth.
Confirm the connection 2 min
Check the Brick icon: connected, or not.
Two motor tiles — A and D.
Two sensor tiles — 1 and 3.
Read tile 3 with the chute empty, then drop a sweet through it five times. Write down the empty reading and the lowest reading during a drop. Your “delivered” threshold goes between them — and if a sweet sometimes passes without moving the number, fix the chute before writing any code.
Stuck? The long version, with a photograph of every screen, is in the Brick & Bluetooth guide.
Make it move 10 min
Build the naive version first. It works, and then somebody empties the hopper and it starts taking money for nothing.
Step 1 — the version that can rob you
when program starts :: events hat
forever
wait until <[1 v] is pressed? :: sensors>
[D v] run to position (90) [degrees v] at (50) % speed :: motors
change [takings v] by (1) :: variables
[A v] run [clockwise v] for (1) [rotations v] at (40) % speed :: motors
end
Coin kept first, sweet second, and no check that a sweet arrived. Empty the hopper and it keeps charging.
Step 2 — a transaction
when program starts :: events hat
set [takings v] to (0) :: variables
set [refunds v] to (0) :: variables
set [state v] to [IDLE] :: variables
[D v] run to position (0) [degrees v] at (40) % speed :: motors
[A v] reset degrees counted :: motors
write [INSERT COIN] at line (1) :: display
when program starts :: events hat
forever
// ---- 1. a coin arrives: we are now HOLDING and we owe something ----
wait until <[1 v] is pressed? :: sensors>
set [state v] to [HOLDING] :: variables
write [HOLDING] at line (1) :: display
set status light to [orange v] :: display
// ---- 2. try to deliver ----
[A v] run [clockwise v] for (1) [rotations v] at (40) % speed :: motors
reset timer :: control
set [delivered v] to (0) :: variables
repeat until <<(delivered) = (1)> or <(timer) > (2)>>
if <([3 v] reflected light intensity) < (25)> then
set [delivered v] to (1) :: variables
end
end
// ---- 3. settle, or refund. Never neither, never both ----
if <(delivered) = (1)> then
[D v] run to position (90) [degrees v] at (50) % speed :: motors
change [takings v] by (1) :: variables
set [state v] to [SETTLED] :: variables
write [ENJOY] at line (1) :: display
play sound [Communication / Thank you v] :: sound
else
[A v] run [counterclockwise v] for (1) [rotations v] at (40) % speed :: motors
[D v] run to position (-90) [degrees v] at (50) % speed :: motors
change [refunds v] by (1) :: variables
set [state v] to [REFUNDED] :: variables
write [SOLD OUT - REFUND] at line (1) :: display
play sound [Mechanical / Error v] :: sound
end
// ---- 4. back to a safe state ----
wait (2) seconds :: control
[D v] run to position (0) [degrees v] at (40) % speed :: motors
set [state v] to [IDLE] :: variables
set status light to [green v] :: display
write [INSERT COIN] at line (1) :: display
write (takings) at line (5) :: display
write (refunds) at line (7) :: display
wait until <not <[1 v] is pressed? :: sensors>>
end
Dispense, prove, then keep — and a mechanical refund when the proof does not arrive. The state on line 1 tells you at any instant whether it is safe to stop.
takings changes in one place only — inside the settle branch. That single rule is what makes the number trustworthy.
The auger reverses before the refund. A half-released sweet left in the mechanism will jam the next customer, so the machine undoes its own attempt.
The timeout is what makes the refund possible. Without it the machine waits for ever in HOLDING, which is the one state it must not linger in.
Line 1 always says which state it is in. That is not decoration — it is how you check the machine while it is running.
What success looks like: a coin buys a sweet and the takings rise. Empty the hopper, insert a coin, and the coin comes back out while the takings stay where they were.
If a refund still increments the takings, the counter is being changed before the branch — move it inside. If every transaction refunds, your chute threshold is above the empty reading, so a passing sweet never counts as proof.
Change it and test 8 min
One change at a time. Predict, then run, then look. The test that matters is not “does it work” but “who loses if I interrupt it now”.
Empty the hopper and insert a coin. Confirm the coin comes back and the takings do not move. This is the whole lesson in one test.
Move the coin-keeping step to the top, before the auger. Repeat the empty-hopper test. The machine has now taken money for nothing — say out loud which line did it.
Stop the program mid-dispense, while the state reads HOLDING. Where is the coin? Then do the same during SETTLED and compare.
Block the chute with a finger so the sweet never passes the sensor. The machine refunds a sweet it actually released — a real machine has this bug too, and it is why the beam sits below the flap, not above it.
Add a price of two coins. Count presses, and only start dispensing at two — then work out what the machine must do if the second coin never arrives.
Test a transaction by interrupting it. If nobody can be left out of pocket, it is right.
Where this goes 3 min
Your vending machine can take its time. Nothing is moving, so acting a second late costs nothing.
The next model has no such luxury. IP Man’s arms swing on a timetable, and by the time the sensor reports an arm arriving, the machine that must block it is already too late.
The answer is not a faster loop. It is acting early, by an amount you have measured — the first time in this course that a machine has to aim at where something will be rather than where it is.
Today the machine kept its side of a bargain. Next it has to beat the clock.
This is what you are building: the EV3 Candy Vending Machine.
Challenges & mission 27 min
Work through the challenges in order — each is harder than the last. The mission comes after all three, and it is meant to make you plan before you build.
Challenge 1
Empty the hopper and insert a coin.
The coin must come back and the takings must not move.
This is the whole lesson in one test, so run it five times and report the takings and refunds counts. If the takings moved even once, the machine stole from somebody.
Challenge 2
Build the version that robs you, on purpose.
Move the coin-keeping step above the auger, repeat the empty-hopper test, and record what happens.
Then put it back and write one sentence naming the single line that made the machine unfair. Being able to point at it matters more than fixing it.
Challenge 3
Interrupt it in each state.
Stop the program while the screen reads HOLDING, then again while it reads SETTLED, then again while IDLE.
For each one, say who is out of pocket. Then say how long the machine spends in HOLDING, and what you could do to make that shorter.
Mission
Sell to real customers.
Run the machine for at least ten transactions with people who are not in your group, and let it run out of stock at least once while they are using it.
Requirements:
1. Dispense, prove delivery, then keep payment — never any other order.
2. A mechanical refund that actually returns the coin, not a message saying it did.
3. A timeout on the delivery check, so the machine cannot sit in HOLDING for ever.
4. Takings changed in exactly one place, in the settle branch, and you can point at it.
5. The state visible on screen at all times.
6. The auger reverses before a refund, so the next customer does not inherit a jam.
At the end, count the sweets gone and check the takings match. Then count the refunds and check the till.
Write down any discrepancy and what caused it. A machine whose books do not balance is not almost right — it is the one failure a vending machine is not allowed to have.
Build it 15 min
Build the model before you read any further. Everything after this is about making it do something, and none of it will make much sense with nothing on the table in front of you.
Use the viewer's own controls to zoom and turn pages. Fullscreen makes it big enough to build from.
Check the finished build against the picture before you switch anything on. A motor mounted the wrong way round is far easier to spot now than it is to debug later, when it looks like a program fault.