Arduino Ladder · Bozoma Innovation Hub

Bozoma Innovation Hub  ·  Arduino Ladder  ·  Band 2

Mood Lamp

Until now your lights have been fully on or fully off. This band gives you everything in between, gives you colour, and gives you the first tool that lets a program repeat itself without you typing the repetition out by hand.

About 6 hours. Finish Band 1 first. You will need to be comfortable wiring an LED without looking it up.

Choose your build

Swap means build it instead of the one on this page: it teaches the same things and leaves you just as ready for the next band. Everything else on this page still applies, including the Check yourself questions. Practice is short, comes after the core, and gives you no sketch: the job, the check, and the code is yours. Bench is not a build at all: it is an instrument or an idea, done once, and everything after it is easier for having done it.

Sketches for this band

Click one to save it, or get every sketch at once from the downloads page. Each file opens with a plain-English header telling you what it does and how to wire it.

Start here

What this band is for

Three new things happen here, and each one opens a door.

  • Brightness. You will make a light fade smoothly instead of snapping on and off. You will also find out that the board is lying to you about how it does that, and prove it with your own hand.
  • Colour. One LED that can be any colour you name, and the reason why mixing coloured light works differently from mixing paint.
  • Repeating. In Band 0 you copied and pasted the same four lines over and over to get three flashes. Here you learn the tool that does that for you, and going from three to ten costs you one character.

What you need

  • Your board, USB cable and breadboard
  • One ordinary LED and one RGB LED. The RGB one has four legs instead of two.
  • Four resistors of 220 ohms. Three are used at once in Part 7; the fourth is a spare.
  • Jumper wires
  • A torch, or your phone light
  • Something to make a diffuser from: a ping pong ball, a plastic sachet-water bottle, or white paper
Part 1

The torch test, before any code

10 min

Ten minutes with a torch will teach you the main idea of this band better than any explanation.

You need a small light: a torch, or the camera light on a phone. A big room lamp will not work, because you cannot cover it with a hand.

Set it up so your hands are free. Stand the phone against a book, or prop the torch on a table, pointing at a plain pale wall about an arm's length away. Make the room as dim as you can.

You should seeA bright circle on the wall that stays still without you holding anything.

Now pass your flat hand across the front of the light, about 5 cm from it, so the circle on the wall goes dark and light again. Watch the wall, never your hand.

Once a second. Count out loud: "one and, two and". Cover on the number, uncover on the "and".

You should seeThe wall clearly flashing on and off. Nobody could mistake it for a steady light.

Twice a second. Count twice as fast.

You should seeStill clearly flashing, just quicker.

Now as fast as your hand will physically go, for about ten seconds.

You should seeThe flashing starting to smear together. It stops looking like separate flashes, and the wall looks dimmer than when the light is uncovered.
You will not get all the way there, and that is the pointYour hand manages maybe five or six covers a second. To make flashing look like a completely steady dim light you need somewhere near fifty a second, and no hand can do that.

So you see it heading that way and never arriving. Hold on to that feeling. The board does this hundreds of times a second, which is far past the speed where your eye gives up and simply reports "dimmer".
Write these down
  1. At your fastest, did the wall still look like separate flashes, or had it started to smear into one? Describe what you actually saw.
  2. Covering once a second means the light is off for half of every second. Is the wall as bright as when you never cover it? Roughly how bright would you say it looks?
  3. If your hand could somehow go a hundred times faster, what do you think the wall would look like?

That change-over point, where fast flashing stops looking like flashing and starts looking like dimness, is the whole trick behind this band.

The board cannot make a dim light. Its pins have only two settings: fully on at 5 volts, or fully off at 0 volts. There is nothing in between. What it can do is switch between them faster than your eye can follow, and let your eye do the averaging for it.

Part 2

How the board fakes dimming

15 min

The instruction for this is analogWrite. You give it a pin and a number from 0 to 255.

  • analogWrite(9, 0); means fully off
  • analogWrite(9, 255); means fully on
  • analogWrite(9, 128); means about half brightness
  • analogWrite(9, 64); means about a quarter brightness

But the pin is never actually at half a voltage. Here is what it is really doing.

5V 0V time analogWrite(64) on 1/4 of the time analogWrite(128) on 1/2 of the time analogWrite(191) on 3/4 of the time
What the pin is actually doing. In every case it is either fully on at 5 volts or fully off at 0 volts. The number you give analogWrite decides what share of each tiny slice of time it spends switched on. On an Uno this repeats several hundred times every second, far too fast to see.

Look at the three lines in the picture. None of them ever sits at a middle height. They are all jumping between the top and the bottom. What changes is how much of the time is spent at the top.

This has a name: PWM. You do not need to remember what the letters stand for. What you need to remember is the idea: fast switching that your eye reads as dimness.

Why 255 and not 100?

It would be easier if the range went 0 to 100, like a percentage. It does not, and the reason is worth knowing.

Computers store numbers in fixed-size boxes. The smallest useful box holds 256 different values, which is 0 up to 255. So the board offers you the whole box rather than throwing part of it away.

You will meet 255 again and again in this course, and by Band 4 you will meet 1023, which is a bigger box. When you see numbers like that, it is a sign that they came from the size of a box rather than from anything in the real world.

Only some pins can do this

This is the single most common trap in this band, so read it twice.

On an Arduino Uno, only pins 3, 5, 6, 9, 10 and 11 can do PWM.

Look at your board now. Next to those six pin numbers, and only those, there is a small squiggle printed: ~. That mark is how the board tells you which pins can dim.

Find all six squiggles on your own board before you carry on. Write the six numbers in your glossary.

What happens if you use the wrong pinNothing complains. analogWrite on any other pin is perfectly legal code, so there is no error message. The board simply treats anything below 128 as fully off, and anything from 128 upwards as fully on. Your fade turns into a snap. You will meet this on purpose in Part 8.
Words to know
analogWrite
Sets a pin to a brightness from 0 to 255 by switching it on and off very fast.
PWM
The name for that fast switching. Only some pins can do it.
~
The squiggle printed next to the six pins on an Uno that can do PWM.
diffuser
Something white or cloudy placed over a light to spread it out, so you see a soft glow instead of a hard bright dot.
Part 3

Read the code before you run it

10 min
b2_01_fade_given.ino
int lampPin = 9;

void setup() {
  pinMode(lampPin, OUTPUT);
}

void loop() {
  for (int level = 0; level <= 255; level = level + 4) {
    analogWrite(lampPin, level);
    delay(20);
  }
  for (int level = 255; level >= 0; level = level - 4) {
    analogWrite(lampPin, level);
    delay(20);
  }
}

There is one completely new thing here: the word for. Part 4 explains it fully. Before you read that explanation, make your guesses, even though you do not understand it yet. Guessing first is what makes the explanation stick.

Write your guesses down
  1. In one sentence, what do you think the light does?
  2. How many times do you think the two lines inside the first for happen? Show how you worked it out.
  3. How long do you think one complete round takes? Show your arithmetic.
  4. What is the largest number you think level ever holds?
Part 4

The for loop, explained slowly

25 min

A for loop is a way of saying: do this block of lines over and over, counting as you go, and stop when the count reaches a certain point.

Here is the first line on its own:

for (int level = 0; level <= 255; level = level + 4) {

Inside the round brackets there are three separate parts, separated by two semicolons. Each one does a different job. Look at them one at a time.

PartWhat it isWhen it happens
int level = 0The start. Make a name called level and put 0 in it.Once, before anything else. Never again.
level <= 255The test. Is level less than or equal to 255?Before every round. If the answer is yes, do the block. If no, stop and move on.
level = level + 4The step. Add 4 to level.After every round, just before the test happens again.

The order things happen in

Read this list slowly. It is the whole machine.

  1. level is created and set to 0.
  2. Test: is 0 less than or equal to 255? Yes. So run the block.
  3. Block runs: analogWrite(lampPin, 0) then delay(20).
  4. Step: level becomes 4.
  5. Test: is 4 less than or equal to 255? Yes. Run the block again.
  6. Block runs with level now 4. Then step makes it 8. Test passes. And so on.
  7. Eventually level becomes 256. Test: is 256 less than or equal to 255? No. So the block does not run, and the loop is finished.
The one line that confuses everybody

level = level + 4 looks like nonsense. In maths, nothing can equal itself plus four.

But = here does not mean "equals". It means: work out whatever is on the right, then put that answer into the name on the left.

So read it as: take the value in level, add 4 to it, and store the answer back in level. If level held 8, it now holds 12.

This is one of the biggest differences between code and maths. Once you have it, a great deal of code stops looking strange.

Now answer the guesses properly

How many rounds? level takes the values 0, 4, 8, 12, and so on up to 252. That is 64 different values. So the block runs 64 times.

Working it out: the last value is 252, the step is 4, so 252 divided by 4 is 63, plus one more for the very first round at 0, giving 64.

How long is one round of loop? There are two for loops, one going up and one coming down. 64 rounds each is 128 rounds altogether. Each round waits 20 milliseconds. 128 times 20 is 2560 milliseconds, which is about two and a half seconds.

What is the largest number level ever holds? It is 256, and that surprises most people. On the last round that actually runs, level holds 252. Then the step adds 4, making it 256, and only then does the test fail. So the biggest number it ever holds is one that never reaches the pin. The same thing happens in the second loop coming down, where it ends up holding −1.

Why <= and not <? <= means "less than or equal to". With < the loop would stop before ever reaching the top value. Using <= means 255 itself is allowed. This one character makes a real difference and there is a question about it at the end.

Words to know
for loop
A way of repeating a block of lines a set number of times, counting as it goes.
round
One pass through the block. Sometimes called an iteration.
=
Put the value on the right into the name on the left. Not the same as "equals".
<=
Less than or equal to.
>=
Greater than or equal to.
Part 5

Build it and prove the trick

40 min
+ − − + j i h g f e d c b a 1 5 10 USB ARDUINO UNO + + 220 220 f5 f5 f6 f6 h3 h3 j3 j3 j5 j5 j6 j6 SCL SCL SDA SDA AREF AREF GND GND 13 13 12 12 11 11 10 10 9 9 8 8 7 7 6 6 5 5 4 4 3 3 2 2 1 1 0 0 IOR IOR RST RST 3V3 3V3 5V 5V GND GND GND GND VIN VIN A0 A0 A1 A1 A2 A2 A3 A3 A4 A4 A5 A5
Band 1's circuit exactly, on pin 9 instead of pin 8. Pin 9 has a ~ beside it and pin 8 does not.

The circuit is exactly the same as Band 1, but on pin 9 instead of pin 8, because pin 9 can do PWM and pin 8 cannot.

Before you startUSB unplugged.

Put the LED in. Long leg into f5, short leg into f6.

Resistor from j5 to j3.

Wire from h3 to pin 9. Not j3: the resistor leg is in that hole already, and a hole takes one leg only. h3 is in the same column, so it reaches the resistor just the same. Check your board and make sure pin 9 has a ~ next to it.

Wire from j6 to the − rail, and another wire from the − rail to a GND pin.

Your breadboard has two − rails, one along each long edge. In this band, “the − rail” always means the one along the top edge, nearest row j. Pick it now and use only that one all band.

Plug in and upload b2_01_fade_given.ino.

You should seeThe light grows slowly brighter, then slowly dimmer, then repeats. One complete round takes about two and a half seconds.
If it snaps on and off instead of fadingYou are on a pin without a ~. Check which pin your wire is really in.
If nothing lights at allGo back to Band 1, Part 11 and work down that checklist: LED the wrong way round, both legs in the same column, bare legs touching, something crossing the middle channel, and whether the − rail really reaches GND. It is the same circuit as Band 1, so it fails in the same five ways. Part 12 of this band covers the faults that are new here.

Time it. Use a phone stopwatch. Start it the moment the light goes fully dark. Count ten more times that it goes fully dark, then stop. Divide your total by ten, and compare that with the 2560 milliseconds you calculated.

They should agree closely. If they do not, one of the two is wrong, and working out which is the exercise.

Now prove the board is faking it

Three changes. Do them in order and watch carefully each time.

Make the steps big and slow. Change both 4s to 60, and both delay(20)s to delay(400). Upload.

You should seeThe light arrives in about five obvious jumps instead of a smooth fade. You can count them out loud. Those jumps were always there. That is what the fade is made of.

Put it back. Change them back to 4 and 20. Upload.

You should seeA smooth fade again. There are now 64 steps in each direction and you cannot see a single one. Nothing changed except how fast they go by.

Now the important one. First click File then Save As and save a copy under a new name, such as handwave. You need b2_01 again in Part 8 and Part 9, so do not change the original.

In your copy, delete everything inside loop and put this one line in instead:

void loop() {
  analogWrite(lampPin, 60);
}

Upload it. The light now sits at one steady, dim setting and stays there.

Make the room as dark as you can. Switch the room light off, not just down, and draw the curtains if it is daytime.

Now hold your hand about 10 cm from the LED with your fingers spread, and sweep it side to side as fast as you can, at least three full sweeps a second. Watch your fingers, not the light.

If you only see a smooth blurThree things to try, in order: get the room darker, sweep faster, and bring your hand closer to the LED. If it still blurs, take off any diffuser, because a diffuser spreads the light and hides the effect completely.
You should seeYour fingers appear as a row of separate lit copies, like a series of frozen snapshots, instead of a smooth blur.
What you just saw, and why it matters

If the LED were genuinely dim and steady, your moving hand would be a smooth blur, the way it is in ordinary light. It is not. You see separate copies.

That is because the light is not dim at all. It is fully on and fully off, hundreds of times a second, and your moving hand is catching it at different positions during each flash. Your hand has just measured something too fast to see.

Write one sentence describing what you saw. Keep it. You will be asked for it when you claim this band.

Part 6

Colour works differently than you think

15 min

Another short activity before any code.

There are two ways to do this. The screen way needs nothing but a phone, so start there. The torch way is more fun if you can manage it.

The screen way, on your own, with one device

Open any drawing or painting app on a phone or computer and find its colour picker. Look for one with three sliders marked R, G and B, or a box where you can type three numbers.

Set red to 255, green to 0, blue to 0. That is pure red light.

Now add green. Set red 255, green 255, blue 0.

You should seeYellow. Not a muddy brown. Bright yellow.

Try the other pairs and write each down: red and blue (255, 0, 255), green and blue (0, 255, 255), all three (255, 255, 255).

The torch way, if you can get two lights

You need two lights you can colour: a torch with a red sweet wrapper taped over the front and another with a green one, or two phones each showing a full screen of one pure colour.

Make the room dark. This will not work in daylight.

Prop both lights on a table pointing at a white wall, about a hand's width apart, roughly an arm's length from the wall.

You should seeTwo coloured circles on the wall, side by side, not touching.

Slide one light slowly towards the other until the two circles half overlap. Look at the middle part, where both colours land on the same piece of wall.

Either way, write down the colour you get for each pair.

  • Red and green together
  • Red and blue together
  • Green and blue together
  • All three together
What you should have got, and why it feels wrong

Red and green make yellow. Red and blue make pink or magenta. Green and blue make light blue or cyan. All three together make white.

Nearly everybody finds red and green making yellow surprising, because we all learned colour from paint and crayons. Mixing red and green paint gives you a muddy brown.

Here is the difference. Paint takes colour away. A white wall is already reflecting all colours; red paint absorbs everything except red. Add another paint and you absorb even more, so mixing paints always heads towards dark.

Light adds. You start with darkness and put light into it. Every colour you add makes it brighter, so mixing light always heads towards white.

Screens and LEDs make light. So the rules that apply to them are the adding rules, and that is why every colour on a computer is described by three numbers: how much red, how much green, how much blue.

That is exactly what you are about to control. An RGB LED takes three numbers, each from 0 to 255, and mixes that much red, green and blue light.

ColourRedGreenBlue
Red25500
Green02550
Blue00255
Yellow2552550
Orange2551200
Pink255105180
White255255255
Off000

To find the three numbers for any other colour, search the web for the colour name followed by "RGB value". You will get three numbers in that order.

Part 7

Wire the RGB LED

35 min
+ − − + j i h g f e d c b a 1 5 10 15 USB ARDUINO UNO RGB LED red / long / green / blue RGB LED red / long / green / blue 220 220 220 220 220 220 f5 f5 f6 f6 f7 f7 f8 f8 h10 h10 h12 h12 h2 h2 j10 j10 j12 j12 j2 j2 j5 j5 j6 j6 j7 j7 j8 j8 SCL SCL SDA SDA AREF AREF GND GND 13 13 12 12 11 11 10 10 9 9 8 8 7 7 6 6 5 5 4 4 3 3 2 2 1 1 0 0 IOR IOR RST RST 3V3 3V3 5V 5V GND GND GND GND VIN VIN A0 A0 A1 A1 A2 A2 A3 A3 A4 A4 A5 A5
The common-cathode kind: the long shared leg goes to the − rail. Three resistors, one per colour, because each colour is its own light.

An RGB LED looks like one light but it is really three lights inside one plastic case: a red one, a green one and a blue one, sitting right next to each other so their light mixes.

That is why it has four legs. Three of them are the three lights. The fourth is the shared return path that all three use.

Because it is three lights, it needs three resistors. Not one. This is the second most common mistake in this band.

one package, three lights inside f5 f6 f7 f8 the LONG leg is the shared one 220 Ω Pin 9 red 220 Ω Pin 10 green 220 Ω Pin 11 blue the − rail GND one wire
An RGB LED is three separate light circuits sharing one return path. Each colour gets its own pin and its own resistor. The single longest leg goes to the minus rail, and one wire takes the rail back to GND.

Finding the legs

Hold the LED with the four legs pointing down. One leg is clearly longer than the other three. That is the shared one, and it goes to ground.

Now hold it so the four legs point down and the rounded back of the dome faces you, not the flat side. Turn it so that the long leg is second from the left. There will be one short leg to its left and two short legs to its right. (Which face you look from matters. Turn it round and the order reverses, so fix on the rounded back and stay there.) With it that way round, reading left to right:

PositionWhich legGoes to
1st, far leftredits own resistor, then pin 9
2nd, the long oneshared groundstraight to the − rail, no resistor
3rdgreenits own resistor, then pin 10
4th, far rightblueits own resistor, then pin 11
If you cannot tell which end is whichIt does not matter yet. Wire it up, run the test sketch, and see which colour appears when. If they come out in a different order, just swap the wires until red is on pin 9. Nothing is damaged by getting this wrong, as long as each leg has its resistor.
Before you start: clear the board, completelyUnplug the USB. Then take out everything that is still on it, not just Part 5's light: Part 5's plain LED, its resistor and both its wires, and Band 1's three lights, their three resistors and their four wires if the tower is still standing.

The RGB LED needs holes that Band 1's yellow and green lights are sitting in: j8 and j10 both hold a Band 1 resistor leg, and the RGB build puts a resistor in each of them. Arduino pins 7, 8 and 9 must all end up empty too.

Both ends of every wire. Pulling a wire out of the breadboard and leaving its other end in the Arduino is the fault that catches everybody, because a leftover wire in an Arduino pin is invisible when you are looking at the breadboard. One Arduino pin takes one wire, so a wire you forgot will stop you dead later in the band and you will look for it on the board, where it is not.

Pull each part out by its body, straight up, as in Band 1 Part 3. You want a bare breadboard and a bare row of Arduino pins.

Straighten the four legs first. RGB LEDs arrive with their legs splayed out at angles. Hold the plastic body and gently bend each leg until all four point straight down, side by side, about as far apart as four holes in a row.

You should seeFour parallel legs, like the teeth of a comb.

Push the LED into the board so its four legs land in f5, f6, f7 and f8, with the long leg in f6.

Hold the plastic dome, line all four legs up over the holes from directly above, and press straight down. Never push it in at an angle.

So: red leg in f5, long leg in f6, green leg in f7, blue leg in f8.

You should seeThe LED standing upright, all four legs fully in, not wobbling when you nudge it.

Ground first. Wire from j6 to the − rail. Then a wire from the − rail to a GND pin.

Red. Resistor from j5 to j2. Wire from h2 to pin 9.

Green. Resistor from j7 to j10. Wire from h10 to pin 10.

Blue. Resistor from j8 to j12. Wire from h12 to pin 11.

Each pin wire goes in row h, not row j, because the resistor leg already has the j hole. Same column, same connection.

Check: three resistors, three wires to pins 9, 10 and 11, one wire from the long leg to the rail, one wire from the rail to GND. Eight connections in all. Then plug in.

Upload b2_02_rgb_colours.ino.

You should seeRed for a second, then green, then blue, then orange, then white, then off, then it starts again.
If the colours come out in the wrong orderYour legs are not in the order this page assumed. Swap the wires at the pin end until red appears when the sketch says red. Nothing is broken.
If everything is bright when the sketch says off, and dark when it says white
+ − − + j i h g f e d c b a 1 5 10 15 USB ARDUINO UNO RGB LED red / long / green / blue RGB LED red / long / green / blue 220 220 220 220 220 220 f5 f5 f6 f6 f7 f7 f8 f8 h10 h10 h12 h12 h2 h2 j10 j10 j12 j12 j2 j2 j5 j5 j6 j6 j7 j7 j8 j8 SCL SCL SDA SDA AREF AREF GND GND 13 13 12 12 11 11 10 10 9 9 8 8 7 7 6 6 5 5 4 4 3 3 2 2 1 1 0 0 IOR IOR RST RST 3V3 3V3 5V 5V GND GND GND GND VIN VIN A0 A0 A1 A1 A2 A2 A3 A3 A4 A4 A5 A5
The common-anode kind. The shared leg moves to the + rail, the outer strip on the same top edge, and one new wire runs from that rail to 5V. The three resistors and the three pin wires do not move.
Unplug the USB cable first. You have the other kind of RGB LED, where the shared leg goes to 5V instead of ground. Move the wire that goes from j6 to the − rail so it goes to the + rail — the outer strip along the same top edge, the one marked with a red line and a +, not the inner one you have used all band instead. Then run one new wire from that same + rail to the 5V pin. Leave everything else where it is.

Then check it by eye before the USB goes back in. This is the only step in the whole band that puts five volts onto the breadboard, and the one mistake that can damage the board is joining 5V to GND. So look: no wire runs from the + rail to a GND pin, and no wire runs from the − rail to 5V. If both of those are true, plug in. Everything then works, but your numbers are backwards: 0 is bright and 255 is off. Note that in your log, because it affects every sketch in this band.

Read the sketch you just ran

b2_02_rgb_colours.ino
int redPin = 9;
int greenPin = 10;
int bluePin = 11;

void showColour(int r, int g, int b) {
  analogWrite(redPin, r);
  analogWrite(greenPin, g);
  analogWrite(bluePin, b);
}

void setup() {
  pinMode(redPin, OUTPUT);
  pinMode(greenPin, OUTPUT);
  pinMode(bluePin, OUTPUT);
}

void loop() {
  showColour(255, 0, 0);
  delay(1000);

  showColour(0, 255, 0);
  delay(1000);

  showColour(0, 0, 255);
  delay(1000);

  showColour(255, 120, 0);
  delay(1000);

  showColour(255, 255, 255);
  delay(1000);

  showColour(0, 0, 0);
  delay(1000);
}

There is something new in the middle: a group called showColour.

It looks like setup and loop, because it is the same kind of thing: a named group of instructions. But this one is not built into the Arduino. Somebody wrote it. It is called a function.

The difference from setup and loop is that this group does not run on its own. It runs only when something asks for it by name. Look at loop: every line there that says showColour(...) is asking for it.

And it takes three numbers with it. Look at the top line of the group:

void showColour(int r, int g, int b) {

The three things in the brackets are empty boxes waiting to be filled. When loop says showColour(255, 120, 0), then inside the group r holds 255, g holds 120, and b holds 0. The three analogWrite lines then use those.

You are reading this one, not writing it

Writing your own functions is Band 5. Here you only need to be able to read one and say what it does. That is deliberate: reading working code before writing your own is easier and teaches just as much.

But do notice what it buys. Without it, every colour change would be three lines of analogWrite. With it, each change is one line that says what it means. And if you ever needed to change how colours are set, you would change it in one place instead of everywhere.

The worked example

Now upload b2_03_colour_story_worked.ino. Watch it all the way through before you read it. It is a sunrise: night, first red light, orange, full daylight, then back to night.

Then open it and find the group called fadeTo. This is the part that matters:

b2_03_colour_story_worked.ino
void fadeTo(int r1, int g1, int b1, int r2, int g2, int b2) {
  for (int step = 0; step <= 100; step = step + 1) {
    int r = r1 + (r2 - r1) * step / 100;
    int g = g1 + (g2 - g1) * step / 100;
    int b = b1 + (b2 - b1) * step / 100;
    showColour(r, g, b);
    delay(stepDelay);
  }
}

One name in there comes from further up the file. Near the top of b2_03_colour_story_worked.ino is the line int stepDelay = 25;. That is the pause between the hundred small steps, and it is the one number you change to make a fade slower or faster. Find it now, so you know where it is when Part 11 asks you to change it.

It takes six numbers: the colour you are starting from, and the colour you are going to. Then it walks from one to the other in a hundred small steps, showing each one, so the change looks smooth instead of jumping.

The arithmetic inside says: start where you are, and add the part of the difference you have travelled so far. When step is 0 you get exactly the first colour. When step is 100 you get exactly the second. In between you get a mixture.

You do not need to be able to write this yet. You do need to be able to say what it does, because your Make task uses it.

Part 8

Look closer

25 min

a. Run the loop by hand

Take the first for loop of b2_01. Copy this table and fill it in for the first four rounds and the last one.

Roundlevel at the startIs it 255 or less?Number sent to the pinlevel after the step
10yes04
2    
3    
4    
last    
Check your table

Round 2: starts at 4, yes, sends 4, becomes 8. Round 3: starts at 8, yes, sends 8, becomes 12. Round 4: starts at 12, yes, sends 12, becomes 16.

Last round: starts at 252, yes, sends 252, becomes 256. Then the test asks whether 256 is 255 or less. It is not, so the loop ends without running the block again.

Now write down in your own words what each of the three parts inside for( ; ; ) is for. If you cannot, read Part 4 again.

b. Find the one wrong character

Your board still has the RGB LED on it from Part 7, and that is fine. The wire going to pin 9 is the red channel, and red is the light this exercise uses. Leave the green and blue wires alone.

Unplug the USB cable, then move one wire. Take the wire that goes to pin 9 and put it into pin 7 instead. Plug the USB back in afterwards. Leave everything else exactly as it is.

Now open b2_04_buggy_nonpwm.ino and upload it. It compiles. It uploads. The LED is wired correctly and it does light up. But it will not fade. It snaps from off to on, somewhere in the middle.

One character in the sketch is wrong. Find it by reading, then say why moving that wire is what made the fault show up.

Answer

The sketch uses pin 7, and you have just put your wire into pin 7, so the light really is on pin 7. Pin 7 has no ~ next to it, so it cannot do PWM.

analogWrite on a pin like that is perfectly legal code, so nothing complains. The board simply treats anything below 128 as fully off and anything from 128 upwards as fully on. So instead of 64 brightness levels you get two.

To put it right you must change two things, not one. Move your wire back to pin 9, and change the 7 in the sketch to a 9. Change only one of them and the light will not come on at all, because the code and the wire will be pointing at different pins.

That is worth sitting with. The code and the board have to agree. Neither one can tell you when they do not.

If you have not already found all six squiggles on your board, do it now.

c. Put the lines back in order

The five lines inside fadeTo's loop have been shuffled:

delay(stepDelay);
int g = g1 + (g2 - g1) * step / 100;
showColour(r, g, b);
int b = b1 + (b2 - b1) * step / 100;
int r = r1 + (r2 - r1) * step / 100;

Put them back in a working order. Then say why the order matters, in one sentence.

Answer

The three lines that work out r, g and b must all come before showColour(r, g, b), because you cannot show three values before you have worked them out. The three of them can be in any order among themselves. delay goes last.

The general rule: a name has to be given a value before anything can use it.

d. Why is your white not white?

In b2_02, the line showColour(255, 255, 255) is supposed to give white. Look at yours carefully. It is probably slightly pink, or slightly blue, or slightly green.

Why would equal numbers not give equal light?

Answer

The three tiny lights inside the package are not equally good at making light. Red is usually the strongest. They all have the same 220 ohm resistor, so equal numbers do not produce equal brightness.

The fix is not to argue with it. The fix is to find, by eye, the three numbers that look white on your particular LED, and write them down. Try lowering the red a little, say 200 instead of 255, and see if it improves.

That process has a name: calibration. It is the idea that the numbers in your code are instructions, not measurements, and that real parts differ from one another. It is the whole subject of Band 4, arriving one band early.

Part 9

Change it

30 min

Work on a copy of b2_01.

Your plain LED came off the board in Part 7 and it does not go back. b2_01 uses pin 9, which is now the red channel of the RGB LED, so what you will watch fade in this part is a red light coming out of the RGB one. That is expected. Nothing is broken.

Bronze
Make the fade take exactly twice as long, without changing any delay. Count the rounds before and after to prove it worked. Then say what the two different ways of slowing it down are, and what each one costs you.
Silver
Make it breathe: hold at full brightness for one second at the top of each round, and stay fully off for two seconds at the bottom.
Gold
Rewrite b2_01 so that both the step size and the delay are names at the top of the sketch. Then retune the whole thing to a slow, smooth two second breath by editing only those two lines. After that, go back to your Band 0 Gold answer and rewrite it using a for loop. Compare the number of lines.
A hint for Bronze

The number of rounds is decided by the step size. Right now the step is 4 and there are 64 rounds.

Halve the step to 2 and you get 128 rounds, which is exactly twice as many, so it takes exactly twice as long.

The point of Bronze

Halving the step from 4 to 2 takes you from 64 rounds to 128, so the fade takes twice as long and gets finer.

Doubling the delay from 20 to 40 also makes it take twice as long, but you still only have 64 rounds, so it gets chunkier instead.

Same result, opposite cost. Noticing that two different controls reach the same outcome by different routes, and choosing between them on purpose, is most of what engineering judgement actually is.

Part 10

Make: a lamp that tells a story

120 min
What to build

A lamp with a diffuser over it that plays a colour story lasting between 45 and 90 seconds, then repeats. Choose something you have actually watched happen:

  • Sunrise over the lagoon
  • Harmattan haze getting thicker through the day
  • A storm coming in
  • The light in a room you know well, at a particular hour
It is finished when all of these are true
  • It uses at least four colours, and each one has its name written next to it in a comment
  • Every change is a fade. There are no sudden jumps anywhere in the story
  • It has a diffuser, made from something that was going to be thrown away
  • All the colour numbers sit at the top of the sketch, so the story can be retuned without hunting through it
  • Somebody who has not been told what it is can describe what it reminds them of

How to go about it

Watch the real thing, or remember it properly. Write down the four or five colours in order, in words: dark blue, then deep red, then orange, then pale yellow.

Turn each word into three numbers. Use the table in Part 6, or search the web for the colour name and "RGB value".

Start from b2_03. Use Save As to make your own copy. Change the colours in the fadeTo lines to yours.

Get the timing right. The whole story must last between 45 and 90 seconds. Change stepDelay to make each fade longer or shorter, and use delay between fades to hold on a colour.

Make the diffuser. A diffuser is just something white or cloudy over the light, so you see a soft glow instead of one hard bright dot. Pick whichever of these you can actually get hold of.

Paper tube. Easiest, and needs nothing special.

  • Cut a strip of white paper about 8 cm tall and 15 cm long.
  • Wrap it twice around a pen to make a tube, slide the pen out, and tape the seam.
  • Cut a small circle of the same paper and tape it on top like a lid.
  • Stand the tube over the LED. It does not have to touch it.

Ping pong ball. Best glow, but needs care.

  • Mark a spot on the ball. Push the point of a skewer or a compass into it and twist slowly to open a round hole about 6 mm across. Do not cut it cold with scissors, because the plastic splits.
  • Hold the LED body steady with one hand and lower the ball on with the other. Push down hard and you will lever the legs out of the board.

Sachet water bottle, or any thin white plastic.

  • Cut the bottom 6 cm off a bottle to make a small cup, and turn it upside down over the LED.
  • Cloudy or frosted plastic works much better than clear.
You should seeThe whole diffuser glowing evenly in the LED's colour, instead of one small bright point. Judge it in a dim room.
If it is still one bright dotThe diffuser is too clear or too close. Use thicker paper, add a second layer, or raise it a centimetre off the LED.
If the diffuser feels warmTouch it with the back of a finger after a minute. It should feel like room temperature. If it is warm, unplug and check your resistors, because a correctly wired LED at these currents stays cool.

Look at it in a dark room and adjust. Colours that look right on a screen often look wrong through a diffuser.

Test it on two people

Show it to two people separately. Ask each the same question: what does this remind you of?

Write down both answers word for word. If neither is close to what you intended, you have learned something more useful than a working lamp. Write down what you would change.

If you cannot find two people todayRecord a video and send it to two people on your phone, and ask each of them the same question. Any two people will do: family, neighbours, friends from school. They do not need to know anything about electronics. If you truly cannot reach anyone, leave the lamp for a day, watch it again with fresh eyes, and write down what you think a stranger would say. Say in your log which one you did.

Show your work

If you are doing this course aloneThere may be nobody to post to and nobody else’s work to look at. That is fine, and it does not let you off this part. Do it this way instead: save the photos and the video into a folder named for this band, write the same notes into your build log, and then be your own second reader. Come back to your own sketch the next day, read it cold, and write down the one thing you would do differently now. That is the whole value of looking at somebody else’s work, and you can get most of it from your own.

Post a video of the whole story, all 45 to 90 seconds of it, not a short clip. Include both testers' answers. Then look at one other person's sketch and tell them one place where their colour numbers would be easier to change.

If there is no other sketch to look atPut your own away for a day, then open it cold and read it as though somebody else wrote it. Find one place where the colour numbers would be hard to change, and write down what you would do instead. You will spot more than you expect, because by then you will have forgotten what you meant.
Part 11

Check yourself

15 min

Code you have not seen. Answer from reading only.

int pin = 6;

void setup() {
  pinMode(pin, OUTPUT);
}

void loop() {
  for (int v = 0; v < 200; v = v + 40) {
    analogWrite(pin, v);
    delay(250);
  }
}
  1. List every value that v takes.
  2. How long does one full pass through loop take?
  3. Does the LED ever reach full brightness? Explain.
  4. What does a person watching see at the moment loop starts again?
  5. Change two numbers so the fade looks smooth instead of stepped, while one full pass still takes about the same time.
  6. Would this sketch behave the same way on pin 7? Say exactly what would happen.
Answers

1. 0, 40, 80, 120, 160. Five values. If you said 200 as well, look again: the test is <, not <=, so 200 is not allowed. That one character is the difference.

2. Five rounds, each waiting 250 milliseconds, so 1250 milliseconds, which is one and a quarter seconds.

3. No. The biggest number ever sent is 160 out of a possible 255, so it only reaches about two thirds of full brightness.

4. A sudden jump from 160 straight back to 0. There is no fading down, only fading up, so the cycle has a hard edge in it.

5. Any pair where the number of rounds multiplied by the delay still comes to about 1250. For example step 5 with delay 31, which gives 40 rounds. Or step 10 with delay 62, which gives 20 rounds. What is being checked is whether you understand that the two numbers trade against each other.

6. No. Pin 7 cannot do PWM, so anything below 128 comes out fully off and anything from 128 up comes out fully on. Working through the values from question 1: it stays dark at 0, 40, 80 and 120, and lights only at 160. One brief flash per pass, not a fade. This is the question that matters most in this band. If you said it lights at 120, check 120 against 128 again.

Part 12

When something goes wrong

What you seeWhat it usually isWhat to do
No fade, just on and offanalogWrite on a pin with no ~Check two things and make them agree: which pin your wire is really in, and which pin number the sketch says. Both must be 3, 5, 6, 9, 10 or 11. Look at the board itself, not at what you think you did.
0 gives bright, 255 gives darkYou have the other kind of RGB LED, where the shared leg goes to 5VQuick test: if showColour(0,0,0) gives white, that is what you have. Unplug the USB. Take the wire running from j6 to the − rail and move that end to the + rail — the outer strip along the same top edge, the one marked with a red line and a +, not the inner one you have used all band. Then run one new wire from that same + rail to the 5V pin. Leave everything else exactly as it is: all three resistors and all three pin wires stay put. Then check it by eye before the USB goes back in. This is the only step in the whole band that puts five volts onto the breadboard, and the one mistake that can damage the board is joining 5V to GND. So look: no wire runs from the + rail to a GND pin, and no wire runs from the − rail to 5V. If both of those are true, plug in. Your numbers are then backwards, so 0 is bright and 255 is off.
Brightness drifts as the colour changesOne resistor on the shared leg instead of three on the colour legsThree separate resistors, one for each colour leg, none on the shared leg.
One colour never appearsThat leg is in the wrong column, or its resistor is looseTest each colour on its own with showColour(255,0,0), then (0,255,0), then (0,0,255), before you assume the code is wrong.
White looks pink or blueNothing. This is completely normalAdjust the numbers by eye and write down what worked. See Part 8d.
The LED is hot, or looks brown insideA missing or disconnected resistorUnplug now. That LED may already be damaged. Replace it and check the whole circuit before powering up again.
Fade is smooth but very fast or very slowStep size and delay are fighting each otherChange one at a time and watch. Never change both at once, or you cannot tell which one did what.
Still stuck after 30 minutes?

Photograph the breadboard from directly above in good light. Post the photo, your sketch, and one sentence saying what you expected and what happened instead. Do not rebuild it first.

If there is nobody to send it toWrite the three things down anyway, in your build log: what you expected, what happened, and what you have already tried. Putting a problem into words solves a surprising number of them on its own. Then work down the checklist above one more time, slowly. If it is still stuck, leave it until tomorrow and come back fresh. Do not sit and stare at it.
Done

What you know now

You can control brightness, and you know that the board is faking it, because you proved it with your own hand. You can mix any colour from three numbers. And you can write a loop that repeats itself, which means the length of your code no longer grows every time you want to do something more.

Before you move on, make sure you have

  • Your finished lamp with its diffuser, and a video of the whole story
  • Both testers' answers, word for word
  • Your sentence about what you saw when you waved your hand
  • Your completed table from Part 8a
  • The six PWM pin numbers written down
  • Your build log for this band
  • Five or six correct answers in Part 11, including question 6

Next is Band 3: Combination Lock. So far the board has only ever talked. Next it starts listening, and you find out that a button is far stranger than it looks.

Ship it

One video under sixty seconds, and one post of five lines. The video is the same one this band already asks you for as evidence, so this is not extra work. It is the same work, done once, somewhere a person can see it.

Point the camera at: your colour story with the diffuser on, not a clip of it.

The four shots: three seconds of the thing sitting still, fifteen of you doing something to it, fifteen of it responding all the way to the end, and ten of the honest bit, which is your measurement or the wire that was wrong the first time.

The line worth writing in the post: that the board cannot really dim a light, and what it does instead.

Show your work has the five-line template, a worked example, and the three checks to make before anything goes public. Tag it #BozomaBuilds so all nine of yours sit together.