The Candy Vending Machine. A box called a hopper holds the sweets. A turning screw called an auger lets out one sweet at a time. A gate takes coins. A Colour Sensor watches the chute. It checks that a sweet really came out.
Every model so far could be wrong. This one can be unfair. It can take a coin and give nothing back. “The code ran with no errors” does not make that OK.
By the end of the lesson, your machine will never take a coin without giving a sweet. It will never give a sweet without a coin. That stays true even if you stop it halfway through.
In the real world 5 min
Where you have seen it
A vending machine holds on to your money until your snack has fallen. Many now have a beam of light across the chute. You cannot see it. If nothing passes through the beam, the machine gives your money back.
A vending machine. Photo: Healthyvending / Wikimedia Commons (public domain).
A cash machine at the bank is even more careful. It counts the notes. Then it opens the shutter. Only then does it take the money from your account. If the shutter gets stuck, it pulls the notes back in. You pay nothing. The order of those steps is planned on purpose.
Why it is built that way
That is because power cuts, jams and pulled plugs happen all the time. A machine that is only right when nothing goes wrong is not right at all.
So real machines follow one rule: do the step you cannot undo last. First check the steps you can undo. Giving out a sweet can be checked. But once a machine keeps a coin, it has no arms to hand it back. So: give the sweet, check it, then keep the coin.
What would go wrong without it
Take the coin first, and any jam means the machine steals. Give the sweet first with no check, and someone who never paid gets a free sweet. Each mistake is just one line in the program. Both make people stop trusting the machine.
Do the thing you cannot undo last. Do it only when you know the rest worked.
The main concept — a transaction 6 min
A transaction is two things that must both happen, or neither. The machine takes a coin and gives a sweet. One without the other is a failure, even if every block ran perfectly.
The three states, and the risky one
State
Meaning
Safe to stop here?
Idle
No coin held. Nothing owed.
Yes. Nobody has lost money.
Holding
Coin in, but no sweet given yet.
No. Stop here, and the person has paid for nothing.
Settled
Sweet given. Coin kept.
Yes. Both sides got what they should.
The job is to spend as little time as you can in Holding. You also need a way out of it that gives the coin back. That is a refund. It is a planned way out of the risky middle state.
Check that the sweet came out
“I turned the auger” is not the same as “a sweet came out”. The hopper runs out. Sweets get stuck. Sometimes the auger lets out two at once. The Colour Sensor on the chute turns a guess into proof.
// 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 going past makes the sensor reading darker. No dark reading within two seconds means no sweet. Now the machine owes a refund.
That time limit is called a timeout. You will use one again on the Ball Coaster in Lesson 46. Here it keeps the machine fair. Without it, the machine would wait for ever for a sweet that is never coming. And it would hold the person’s coin the whole time.
Counting the money
Keep a takings count of the money. Add to it only in the Settled step. Never add to it when the coin comes in. Then the number on the screen is always the money the machine has earned. A refund is easy, because that coin 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.
Give, check, then keep. A refund is the planned way out of the middle.
▶Variablestakings, refunds and state are all variables, like in Lesson 18. Open it if you are not sure yet.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, has anybody lost money?”
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 drop, and for how long? If you cannot see it move, the machine can never prove a sweet came out.
Part
What it is doing here
EV3 Intelligent Brick
The till, where the money is counted. The takings on its screen show what the machine says it has earned. That number must always be right.
Medium Motor — the auger
One rotation should let out one sweet. It is Medium for a quick, exact turn. A slow turn lets out two.
Large Motor — the coin gate
It has two positions. Keep drops the coin into the till. Return tips it back out. The refund really gives the coin back. It is not just a message on a screen.
Touch Sensor — coin arriving
A coin lands in the holder and presses it. That starts the transaction. From then on, the machine owes something.
Colour Sensor — the chute
Watches for a sweet going past. It is the only part that knows if the machine kept its side of the deal.
The coin holder must hold the coin, not swallow it. What if the coin has already fallen into the till when the Touch Sensor is pressed? Then no refund is possible. You cannot build the rest of the lesson.
Ports — and the rule 4 min
Sensors go in ports 1, 2, 3, 4. Motors go in ports A, B, C, D. You cannot swap them. If you do, nothing warns you. The robot just will not work.
Part
Port
Why this one
Auger (Medium)
A
The exact motor, on the front port.
Coin gate (Large)
D
The strong one. It moves the till parts.
Coin arriving (Touch)
1
Touch stays on 1 in the whole course.
Chute (Colour)
3
Colour stays on 3 in the whole 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. If the machine starts in the keep position, it could keep a coin before the program is ready.
Fill the hopper. Turn the auger by hand. Adjust it until just one sweet drops each rotation.
Choose what your coin is. It could be a 2×2 tile, a real coin, or a metal washer. Use the same thing 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 pull the plug on purpose today. In one test, you stop the program in the middle of a transaction. Then you see who lost money. A cable you must pull 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. Write down the lowest reading during a drop. Your “delivered” threshold is the number in between. Does a sweet sometimes pass without changing the number? Then fix the chute before you write any code.
One change at a time. Guess, then run, then look. The big test is not “does it work?” It is “who loses if I stop it now?”
Empty the hopper and put in a coin. Check that the coin comes back and the takings do not change. This is the whole lesson in one test.
Move the coin-keeping step to the top, before the auger. Do the empty-hopper test again. Now the machine takes money for nothing. Say out loud which line did it.
Stop the program while the sweet is coming out, when the state says HOLDING. Where is the coin? Then do the same during SETTLED. Compare them.
Block the chute with a finger, so the sweet never passes the sensor. The machine gives a refund for a sweet it really let out. Real machines have this bug too. That is why they put the beam right at the bottom of the drop.
Make the price two coins. Count presses. Only give a sweet at two. Then work out what the machine must do if the second coin never comes.
Test a transaction by stopping it in the middle. If nobody can lose money, it is right.
Where this goes 3 min
Your vending machine used a variable called state. It always knew which step it was on.
The next model is the Transmitting Gyro. It has one button and two jobs. Press once, and a plate lifts a spinning top. Press again, and the plate goes down.
The press is the same both times. So the machine has to remember which way the plate is. That is Lesson 43.
Today the machine kept its side of a deal. Next, one button learns to do two jobs.
This is what you are building: the EV3 Candy Vending Machine.
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.
Fullscreen it while you build — you can pause and scrub with the player's own controls.
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.
Make it move 10 min
Build the simple version first. It works. But then the hopper runs out, and it starts taking money for nothing.
Step 1 — the version that can take your money
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
The coin is kept first and the sweet comes second. Nothing checks that a sweet came out. Empty the hopper, and it still takes coins.
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
Give, check, then keep. If there is no proof, the coin really comes back. The state on line 1 tells you, at any moment, if it is safe to stop.
takings changes in one place only It changes inside the settle side and nowhere else. That one rule is why you can trust the number.
The auger turns back before the refund. A sweet left half-way out would jam the machine for the next person. So the machine undoes its own try.
The timeout makes the refund possible. Without it, the machine waits for ever in HOLDING. That is the one state it must not stay in.
Line 1 always says which state it is in. That is not just for show. It is how you check the machine while it runs.
What success looks like: a coin buys a sweet, and the takings go up. Empty the hopper and put in a coin. The coin comes back out. The takings stay the same.
Does a refund still add to the takings? Then the count is changed before the if. Move it inside. Does every coin get refunded? Then your chute threshold is above the empty reading. So a sweet going past never counts as proof.
Challenges 27 min
Work through them in order — each is harder than the last. The extra challenge comes after all three, and it is meant to make you plan before you build.
Challenge 1
Empty the hopper and put in a coin.
The coin must come back. The takings must not change. The takings are the money the machine keeps.
This test is the whole lesson. So run it five times. Report the takings count and the refunds count. If the takings changed even once, the machine stole from somebody.
Challenge 2
Build the version that cheats you, on purpose.
Move the coin-keeping step above the auger. Do the empty-hopper test again. Write down what happens.
Then put it back. Write one sentence naming the one line that made the machine unfair. Being able to point at it matters more than fixing it.
Challenge 3
Stop it in each state.
Stop the program while the screen says HOLDING. Do it again while it says SETTLED. Then do it again while it says IDLE.
For each one, say who has lost money. Then say how long the machine stays in HOLDING. Say what you could do to make that time shorter.
Extra challenge
Sell to real customers.
Run the machine for at least ten sales, with people who are not in your group. Let it run out of sweets at least once while they are using it.
It must do all of these:
1. Give out the sweet, check it came out, then keep the money. Never in any other order.
2. A refund that really gives the coin back with moving parts. A message saying it did is not enough.
3. A timeout on the check. A timeout is a time limit. Then the machine cannot stay in HOLDING for ever.
4. Takings changed in just one place, in the settle branch. You must be able to point at it.
5. The state shown on the screen all the time.
6. The auger turns backwards before a refund. Then the next customer does not get a jam.
At the end, count the sweets that have gone. Check the takings match. Then count the refunds and check the money box.
Write down anything that does not match, and what caused it. If a machine's money does not add up, it is not almost right. It is the one mistake a vending machine must never make.