Arduino Ladder · Bozoma Innovation Hub

Bozoma Innovation Hub  ·  Arduino Ladder  ·  Band 4

Night Guard

Buttons only ever say yes or no. Sensors give you a number. In this band you learn to read those numbers, and to find out the hard way that a number from a sensor means nothing at all until you decide what it means.

About 7 hours. Finish Band 3 first. You will need the serial monitor constantly.

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

Everything the board has read so far has been on or off. A button is pressed or it is not. There is no in between.

The world is not like that. Light is not on or off. It is dim, or bright, or somewhere between. Temperature is not hot or cold. To build anything that reacts to the real world, the board needs to read amounts, not just yes and no.

That is what this band gives you, along with the most important lesson in the whole course about working with real things:

A sensor does not tell you what something is. It tells you a number. What that number means is your job to work out, in the place where the thing will actually be used.

That job has a name, calibration, and it is Part 8 of this band. Skip it and your night light will work perfectly on your desk and be useless in the room you built it for.

What you need

  • Your board, USB cable and breadboard
  • One potentiometer, the round knob with three legs
  • One light sensor, a small round part with a wiggly line on top. It may be called an LDR or a photoresistor.
  • One resistor of 10 000 ohms. The stripes read brown, black, orange.
  • One LED and one 220 ohm resistor. A second LED, a second 220 ohm resistor, and a passive buzzer as well if you are doing the rain alarm or the room monitor Swap instead of the night guard: both of those use a green light and a red light, and the rain alarm beeps. The buzzer is not otherwise a Band 4 part; it arrives properly in Band 5.
  • Jumper wires

By the end you will be able to

  • Read a number from a sensor and say what range it can be in
  • Explain how a knob turns a turning motion into a voltage
  • Turn a number from one range into another with map
  • Measure the same thing in three real places and write down what you found
  • Say why 5 / 1023 gives you zero, and fix it
  • Build something that decides for itself, using a limit that a person can set
Part 1

Think first: the rope and the walk

15 min

Activity one: the rope

You need something long and bendy again: a shoelace, a phone charger cable, string, or the rope from Band 1 with its knot untied.

Tie one end to something fixed, about level with your waist. A door handle, a chair leg, a table leg. Wrap it twice round and knot it so it will not slide.

Hold the other end in one hand and step back until the rope is straight. Not stretched tight, just not sagging.

You should seeA straight line of rope between the fixed point and your hand, roughly level, about a metre or two long. If it droops in the middle, step back a little more.
If you have nothing to tie it toStand on one end with your foot and hold the other end up in your hand. That works just as well. Or lay it flat and straight along a table.

Now pinch the rope with your free hand. Thumb on one side, one finger on the other, loose enough that the rope can still slide through your fingers.

Slide your pinching hand slowly from one end to the other, taking about five seconds for the whole journey. The rope itself stays still. Only your hand moves.

You should seeThe length of rope on one side of your hand growing steadily longer, and the length on the other side growing steadily shorter, by exactly the same amount. It changes smoothly the whole way, never in jumps.
Answer these
  1. When your hand is right at the left-hand end, how much rope is on your left? How much on your right?
  2. When your hand is exactly in the middle, what fraction of the rope is on each side?
  3. As you slide from left to right, does the amount on your left change smoothly, or in jumps?

That is a potentiometer. The rope is a strip of material that resists electricity. The two ends are fixed. Your pinching hand is a contact that slides along it. Where your hand is decides how the total is split between the two sides.

Hold on to that. In Part 3 the two ends will be 5 volts and ground, and your hand will be the middle leg going to the board.

Activity two: the brightness walk

Take a pen and paper. Visit five different places, indoors and outdoors. For example: outside in the sun, outside in shade, by a window, in the middle of a room, and in a cupboard or under a cloth.

In each place, write down a number from 0 to 10 for how bright it feels, where:

  • 0 means you cannot see your own hand in front of your face.
  • 10 means it is so bright it hurts to look.

Write the two ends down at the top of your paper before you start, so you use the same scale in every place.

Then answer
  1. Is your "7" the same as your friend's "7"? How would you find out?
  2. If you did the same walk at eight in the evening instead, would your five numbers be the same?
  3. Somebody asks you to build a lamp that switches on "when it gets dark". What number would you tell it to use as the switching point, and how would you decide?

Keep this paper. In Part 8 you will do the exact same walk again, carrying the sensor, and compare your numbers with its numbers.

Question 3 has no right answer yet, and that is the point. Nobody can know the right switching number without going and measuring. Not you, not your facilitator, not the person who wrote the sensor.

Part 2

What the board gives you

15 min

There is a second row of pins on your board, along the bottom, marked A0 to A5. The A stands for analog, which just means "a smooth amount rather than on or off".

These pins do something the digital pins cannot. They measure the voltage on the pin and give you a number for it.

The instruction is analogRead, and it works like this:

int reading = analogRead(A0);

The number you get back is always between 0 and 1023.

  • 0 volts on the pin gives you 0
  • 5 volts on the pin gives you 1023
  • Anything in between gives you a number in between, in proportion

So 2.5 volts, exactly half, gives about 512.

Why 1023 and not 1000?

Band 2 met the same oddity with 255. It is the same reason.

The board splits the range into a fixed number of steps, and that number comes from how computers store things, not from anything convenient for humans. Here there are 1024 steps, counted from 0, so the last one is 1023.

Whenever you see a number like 255 or 1023, it came from the size of a box.

An important warningNever put more than 5 volts on any pin, and never join 5V straight to GND. Everything in this band stays inside the board's own 5 volt supply, so you are safe as long as you follow the wiring.
Words to know
analog
A smooth amount that can be anything in a range, rather than just on or off.
voltage
How hard the electricity is being pushed. Measured in volts.
analogRead
Measures the voltage on an analog pin and gives back a number from 0 to 1023.
calibration
Measuring, in the real place, what the sensor's numbers actually mean.

Do not confuse these two. analogWrite from Band 2 sends brightness out, and takes 0 to 255. analogRead here takes a measurement in, and gives 0 to 1023. Different jobs, different ranges, similar names. Write both in your glossary, side by side.

Part 3

The knob, and how it makes a voltage

15 min

A potentiometer is the rope from Part 1, built as a component. Take yours out and look at it. Three legs, and a shaft you can turn.

Inside there is a curved strip of resistive material. The two outer legs are joined to the two ends of that strip. The middle leg is joined to a contact that slides along it as you turn.

5V GND Pin A0 turning the knob moves this tap up or down 0 V 2.5 V 5 V 0 512 1023 what analogRead gives you
How a knob makes a voltage. The outer legs go to 5V and to ground, so the whole strip has 5 volts across it. The middle leg picks up whatever voltage is at the point where the contact is sitting, and the board turns that voltage into a number from 0 to 1023.

So when you turn the knob fully one way, the contact is right next to the 5 volt end, and the middle leg reads close to 5 volts, which is close to 1023. Turn it fully the other way and it sits next to ground, so close to 0 volts, which is 0. Anywhere between and you get a proportion.

This arrangement, where a voltage is split between two parts and you tap the middle, has a name: a voltage divider. Remember the name, because the light sensor in Part 7 is the same idea with one part replaced.

Words to know
potentiometer
A knob with three legs whose middle leg gives a voltage depending on the position of the knob. Often shortened to "pot".
voltage divider
Two resistances in a row across a supply, with a wire tapping the point between them.
Part 4

Read the code before you run it

6 min
b4_01_pot_read_given.ino
int knobPin = A0;

void setup() {
  Serial.begin(9600);
}

void loop() {
  int reading = analogRead(knobPin);
  Serial.println(reading);
  delay(200);
}
Write your answers down first
  1. What is the smallest number you expect to see? What is the largest?
  2. How many numbers will appear each second?
  3. There is no pinMode line for knobPin. Is that a mistake?
  4. Notice that the pin is written A0, with a capital A, and not just 0. Why do you think that is?
Answers to 3 and 4, once you have written your guesses

3. Not a mistake. Analog pins used for reading do not need pinMode. You can write it and it does no harm, but it is not required.

4. Because there is already a pin called 0. Digital pin 0 and analog pin A0 are two different pins on two different edges of the board, and the capital A is how you say which one you mean.

Here is the honest detail, because it will save you an argument one day. For analogRead alone, the board is forgiving, and analogRead(0) happens to reach the same pin as analogRead(A0). But for pinMode, digitalRead and digitalWrite, A0 means pin 14 and 0 means pin 0, and those really are two different pins. Write the capital A every time and you never have to remember which instructions forgive you and which do not.

Part 5

Build the knob and watch it

25 min
+ − − + j i h g f e d c b a 1 5 10 USB ARDUINO UNO knob knob f5 f5 f6 f6 f7 f7 j5 j5 j6 j6 j7 j7 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
Both of the knob's outside legs reach a rail. A divider with only one end connected divides nothing.
Two things before you startUSB unplugged. Also, take everything from Band 3 off, both ends: every part and every resistor out of the breadboard, and every jumper wire out of the Arduino header as well. When you have finished, nothing at all is in Arduino pins 2 to 10 and the board is bare.

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. Band 3's red light is on pin 9, and Part 6 of this band needs pin 9.

And for this whole band, use the rails along the top edge for everything, the ones nearest row j. On most boards the top rails and the bottom rails are not joined to each other, so mixing them means nothing works and nothing looks wrong. Every build in this band puts its parts in rows f to j, so the top rails are the short journey.

Power the rails. Wire from the + rail to the 5V pin. Wire from the − rail to a GND pin.

This is the first build where the breadboard needs 5 volts of its own. Until now everything was powered straight from a digital pin.

Check this twiceThe + rail must go to 5V and the − rail must go to GND. Joining them the wrong way round, or joining the two rails to each other, is the one mistake that can damage the board.

Push the potentiometer into the board so its three legs land in f5, f6 and f7. Turn it so the shaft points away from the board, out over the edge, so you can reach it to turn it once everything is wired.

Hold the plastic body, line all three legs up, and press straight down.

You should seeThe knob sitting flat and firm, not rocking, with the shaft free to turn.

It does not matter which way round the two outer legs go. Swapping them only reverses which way the numbers run as you turn. The middle leg is the one that matters, and it must be the middle one.

If the legs are too wide or too thick to fitGrip each leg close to the body with your fingers and bend only the tip, until the three tips are the same distance apart as three holes in a row. Bend at the tip, never at the body, because that is where they snap. Do not force it in.
If yours is a small square part with a slot on top instead of a shaftThat is a trimmer, and it does the same job. Turn it with a small screwdriver instead of your fingers. Everything else is the same.

Wire from j5 to the + rail. That is one end of the rope.

Wire from j7 to the − rail. That is the other end.

Wire from j6 to pin A0. That is your hand on the rope, going to the board.

Plug in, upload b4_01_pot_read_given.ino, and open the serial monitor.

You should seeNumbers scrolling past, five a second. Turn the knob slowly all the way one way and watch them fall towards 0. Turn it the other way and watch them climb towards 1023.
If the number never changesOne of the two outer wires is probably not connected. Check j5 and j7, and check the rails really do reach 5V and GND.
If the number jumps about wildly on its ownThe middle leg is probably not connected to A0. An analog pin with nothing on it floats, exactly like the button pin in Band 3.

Find the two ends. Turn the knob as far as it will go each way and write down the exact largest and smallest numbers you can reach.

Many knobs will not quite reach 0 or 1023. Yours might stop at 3 and 1020. That is normal and it is useful to know, because it means you should never write code that waits for exactly 1023.

Part 6

map: turning one range into another

25 min
+ − − + j i h g f e d c b a 1 5 10 15 20 25 USB ARDUINO UNO knob knob + + 220 220 f20 f20 f22 f22 f5 f5 f6 f6 f7 f7 h18 h18 j18 j18 j20 j20 j22 j22 j5 j5 j6 j6 j7 j7 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 knob has not moved. The light is new, and its pin wire is in row h because the resistor already owns j18.

Here is a problem you now have. Your knob gives you 0 to 1023. Brightness needs 0 to 255. They do not match.

You could do the arithmetic yourself. There is an instruction that does it for you:

int brightness = map(reading, 0, 1023, 0, 255);

Read it as a sentence: take reading, which lives on a scale from 0 to 1023, and give me the matching place on a scale from 0 to 255.

PartMeans
readingthe number you have
0, 1023the scale it came from: lowest, then highest
0, 255the scale you want: lowest, then highest

So 0 becomes 0, 1023 becomes 255, and 512 becomes about 127.

Unplug the USB, then add a light. LED long leg into f20, short leg into f22. Resistor from j20 to j18. Wire h18 to pin 9 (row h, because j18 now holds the resistor leg and a hole takes one leg only). Wire j22 to the − rail.

If the light never comes onTurn the LED round first, then check both legs are in different columns. This band puts everything in the top block, rows f to j, so the light's ground goes to the same − rail as the knob. If the knob still reads fine but the light is dead, it is the light, not the wiring to the board.

Upload b4_02_pot_dim_led.ino and keep the serial monitor open.

You should seeThe light brightening and dimming as you turn the knob, and two numbers on each line: the raw reading and the brightness it was turned into. Watch how 1023 becomes 255.

Now try it backwards. Change the line to this and upload again:

int brightness = map(reading, 0, 1023, 255, 0);
You should seeThe knob works the other way round. Turning it up makes the light dimmer.

Swapping the last two numbers flips the direction. That is a genuinely useful trick, and it is much easier than rewiring anything.

And try a small range. Change it to map(reading, 0, 1023, 60, 120); and upload.

You should seeThe light never goes fully off and never goes fully bright. The whole turn of the knob now only covers a narrow band of brightness.
What map does not do

It does not stop numbers going outside the range. If your reading is bigger than the number you promised, map will happily give you a result bigger than 255, and analogWrite will behave oddly.

There is a second instruction for that: constrain(value, 0, 255) forces anything below 0 up to 0 and anything above 255 down to 255. Wrapping one around the other is a common and sensible habit:

int brightness = constrain(map(reading, 0, 1023, 0, 255), 0, 255);
Part 7

The light sensor

30 min
+ − − + j i h g f e d c b a 1 5 10 15 20 25 USB ARDUINO UNO knob knob light sensor light sensor 10k 10k + + 220 220 f12 f12 f14 f14 f20 f20 f22 f22 f5 f5 f6 f6 f7 f7 h14 h14 h16 h16 h18 h18 j12 j12 j14 j14 j16 j16 j18 j18 j20 j20 j22 j22 j5 j5 j6 j6 j7 j7 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
Two dividers side by side. The knob's answer comes off its middle leg; the sensor's comes off the point between it and the 10k.

Take out the light sensor. It is a small round part, usually orange or brown on top, with a wiggly line across its face.

It is a resistor whose resistance changes with light:

  • Bright light makes it resist less.
  • Darkness makes it resist much more.

It has no direction, so it goes in either way round.

Here is the difficulty

The board cannot measure resistance. It can only measure voltage. So a sensor that changes its resistance is no use on its own.

The fix is the voltage divider from Part 3. Put the sensor at the top and a fixed resistor at the bottom, and tap the middle. Now, as the sensor's resistance changes, the voltage at the middle changes, and the board can read that.

This is one of the most useful ideas in all of electronics. Almost every simple sensor you will ever meet is wired exactly this way.

5V GND Pin A1 light sensor 10 kΩ resistor More light → sensor resists less → this point rises → bigger number
The light sensor wired as a voltage divider. Five volts goes through the sensor to a middle point, and a fixed 10 000 ohm resistor carries on from that point down to ground. Pin A1 reads the middle. More light lowers the sensor's resistance, which raises the voltage at the middle, which raises the number.
Before you startUSB unplugged.

Push the light sensor in so its two legs land in f12 and f14. Those holes are two columns apart, with column 13 empty between them.

Its legs come out much closer together than that, so spread them gently with your fingers first, holding the round body rather than the legs. It goes in either way round.

You should seeThe sensor standing up with its wiggly face pointing upwards or outwards, where light can reach it. Not lying flat against the board.

Wire from j12 to the + rail.

Put the 10 000 ohm resistor from j14 to j16. Its stripes read brown, black, orange. It is a different resistor from the 220 ohm ones. Check the stripes, do not guess.

If your kit has no 10 000 ohm resistorAnything from about 4 700 up to 47 000 ohms will work. The numbers you read will be different from somebody else's, which is exactly why this band makes you calibrate rather than trusting a number off a page.
If you use a 220 ohm resistor here by mistakeNothing will break, but the reading will barely move as the light changes, and you will think the sensor is faulty. Check the stripes.

Wire from h16 to the − rail. Row h, not row j: the resistor leg is in j16, and a hole takes one leg only. Same column, same connection.

Wire from h14 to pin A1. That is the middle point, between the sensor and the resistor.

Hole h14 is the same column as f14 and j14, so all three are the same connection. Any free hole in that column works.

Plug in, upload b4_03_light_read.ino, and open the serial monitor.

You should seeA number that changes as you change the light. Cup your hand over the sensor and watch it fall. Shine a phone torch on it and watch it climb.
If the number hardly moves at allCheck the resistor stripes. Then check the sensor is really in two different columns.
If the number goes the wrong way for youYou may have the sensor and resistor swapped over, which is not wrong, just upside down. Either swap them, or leave it and remember that for you a bigger number means darker. Write down which it is.

Write down four numbers: your reading with your hand fully covering the sensor, in the room normally, near a window, and with a torch on it.

The numbers will not sit stillThey scroll past five times a second and jitter by a few either way. That is normal. Hold the sensor still for five seconds, watch the range they wander between, and write down a number from the middle of that range. You are after "about 400", not an exact figure.
Part 8

Calibration: the most important part of this band

30 min

You now have a sensor giving numbers. Here is the question that decides whether your project works or not:

What number counts as "dark"?

Nobody can tell you. Not this page, not your facilitator, not the internet. It depends on your sensor, your resistor, the room, the time of day, and which way the sensor is pointing. Two people doing this band side by side will get different answers, and both will be right.

So go and find out.

Get your paper from Part 1, the one with your five places and your 0 to 10 guesses.

Take the board to each of those places with b4_03 running, and write the sensor's number next to your guess.

Two things that make this much easier

The sketch stays on the board when you unplug it. You proved that in Band 0. So you can unplug, walk somewhere, plug back into a laptop or a power bank there, and it is already running.

Point the sensor the same way every time. Straight up at the ceiling or the sky is easiest to repeat. If you point it at a window in one place and at the floor in the next, your five numbers are not comparable and the whole table is wasted.

If you cannot carry a laptop aboutBe careful here, because there is a trap. A power bank runs the board, but the serial monitor only shows numbers while the board is joined to a computer. So a power bank gets you a running board and no readings at all, and a photo taken before you leave shows the old room, not the new one.

Two ways round it, both fine:

The simple way. Do only the places you can reach with the laptop. Three real measurements beat five imagined ones, and the rest of the band works perfectly with three rows in the table.

The clever way. Make the board report without a screen, by blinking the light that is already soldered onto it. Open b4_03_light_read.ino and replace the whole of loop with this, then upload:

void loop() {
  int reading = analogRead(lightPin);
  int blinks = reading / 100;
  for (int i = 0; i < blinks; i = i + 1) {
    digitalWrite(13, HIGH);
    delay(200);
    digitalWrite(13, LOW);
    delay(300);
  }
  delay(2000);
}

Add pinMode(13, OUTPUT); to setup as well. Now a reading of 380 gives three blinks and 720 gives seven. Take the board and a power bank to the room, watch, count, come back.

That reading / 100 throws the remainder away, which is exactly the trap you meet in Part 9. Here it is doing precisely what you want, and it is worth remembering that the same behaviour can be a bug in one place and the whole point in another. It is rough, and rough is enough: you are looking for “about 400 in here and about 800 out there”, not exact numbers.

If carrying a laptop about is awkward, do it in whatever three places you can reach. Three real measurements beat five imagined ones.

Make a table like this and fill it in properly.

PlaceMy guess, 0 to 10Sensor numberTime of day
Outside in the sun   
Outside in shade   
By a window   
Middle of a room   
Under a cloth   

Now choose your number. Look at your table and pick the reading that sits between "light enough to see" and "dark enough to want a lamp". That is your switching point.

Write it down with a reason. Not just "400", but "400, because the middle of the room read 520 at six in the evening and 310 once the sun had gone."

From here on this page calls that number the threshold. It is just a shorter word for the switching point: the number the sensor has to cross before the device changes its mind.

Two things your table will show you

Your guesses and the sensor's numbers do not line up neatly. Your eyes adjust as you walk about. The sensor does not. A room that feels "about half as bright" as outside will usually read far less than half.

The time of day matters enormously. This is why the Make task in this band puts the switching point on a knob instead of writing it into the code. A number written into the code is a decision made once, by you, in one room, on one day. A knob lets the person using it decide, in their room, whenever they like.

That is a design idea, not an electronics one, and it is worth more than either.

Part 9

The division trap

20 min

Suppose you want to turn your reading into actual volts. The arithmetic is easy. 1023 stands for 5 volts, so:

volts = 5 / 1023 * reading

Upload b4_04_buggy_intdiv.ino, which contains exactly that line, and watch the serial monitor.

You will seeThe reading changing as you turn the knob, and the volts stuck at 0.00. Always. Whatever you do.

Nothing is broken. The arithmetic is correct. The problem is what kind of numbers the board thinks it is dealing with.

Whole numbers and decimals are different types

You have been using int since Band 0. An int holds a whole number only. It has no way to hold a fraction.

There is another type, float, which can hold decimals like 0.00489 or 3.5.

Here is the trap. When the board sees 5 / 1023, both of those are whole numbers, so it does whole-number division. The true answer is about 0.00489. There is nowhere to put the fraction, so it is thrown away, and the answer becomes 0.

Then it multiplies your reading by 0. And 0 times anything is 0.

Saying float volts does not help. By the time the answer is stored, the damage is already done.

The fix

Write at least one of the numbers with a decimal point. That tells the board to work in decimals from the start:

float volts = 5.0 / 1023.0 * reading;

Make that change and upload.

You should seeThe volts changing smoothly between about 0.00 and 5.00 as you turn the knob. Check it against your reading: halfway should be about 2.5.

Now try just one of them. Change it to 5.0 / 1023 and upload. It still works.

One decimal point anywhere in the division is enough. The board sees a decimal on one side and works in decimals for the whole thing.

Now try a different fix, with no decimals at all. Replace the line with these two:

int millivolts = 5000 * (long)reading / 1023;
Serial.println(millivolts);
You should seeNumbers from about 0 to 5000, changing smoothly as you turn the knob. Those are thousandths of a volt, so 2500 means 2.5 volts.

This works because of the order. Multiplying by 5000 first makes the number big, and only then does the division throw a fraction away. Losing a fraction out of 5000 hardly matters. Losing one out of 5 loses everything.

What the (long) is doing5000 times a reading of 1023 is over five million, which is too big for an ordinary int. Writing (long) in front tells the board to use a bigger box for the arithmetic. Leave it out and the answer wraps round and goes nonsense above a reading of about 6, which is almost straight away. Try it if you like, then put it back.

Both fixes are used in real code. Decimals are easier to read. Whole numbers are faster and use less memory, which matters on a small chip. What decides between them is whether the scale you choose is big enough to hold the detail you need.

Words to know
int
A name that holds a whole number. No fractions.
float
A name that can hold a number with a decimal point.
whole-number division
When both numbers are whole, the fraction in the answer is thrown away, not rounded.
Part 10

Build the night guard

30 min

Everything is already wired. The knob is on A0, the light sensor is on A1, the LED is on pin 9. You only need the sketch.

Upload b4_05_night_guard_worked.ino and open the serial monitor.

You should seeThree things on each line: the light reading, the threshold your knob is set to, and whether the lamp is on. Cover the sensor and the lamp comes on. Turn the knob and the point at which it comes on moves.
If the lamp never comes on, whatever you doLook at the two numbers before you touch the wiring. If the threshold is stuck near 0, the knob is not being read, so nothing can ever be below it. If the light reading never falls below the threshold even with your hand over the sensor, turn the knob up and try again. The serial monitor tells you which of the two is at fault, so read it before you rebuild anything.
If the lamp is on all the timeTurn the knob all the way down. If it goes off, nothing is wrong and your threshold was simply set very high. If it stays on, check the LED wiring from Part 6.

Read the sketch

void loop() {
  int light = analogRead(lightPin);
  int threshold = analogRead(knobPin);

  if (light < threshold) {
    digitalWrite(lampPin, HIGH);
  } else {
    digitalWrite(lampPin, LOW);
  }
  ...
}

That is the whole idea in four lines. Two sensors, one comparison, one decision.

Notice what the knob is really doing. It is not controlling the light. It is setting the number that counts as dark. The person using the device gets to make that decision, in their room, at their time of day, without touching any code.

Now find the flaw

Turn the knob very slowly until the lamp just starts to twitch, right on the point of coming on. Then take your hand off the knob completely, because your fingers will keep nudging it, and watch for thirty seconds.

If it just sits there steadyYour room is very still. Wave your hand slowly, a metre away from the sensor, so the light changes a little. Or nudge the knob a hair at a time until you find the exact point. The flicker is there; it only shows up when the reading sits right on the line.
You should seeThe lamp flickering on and off, or switching back and forth as tiny changes in the light push the reading over and back across the threshold.

This is a real problem and every device that compares against a limit has it. Fixing it is the Gold task in Part 12, and the fix has a name you can look up: hysteresis. It means using two limits instead of one, with a gap between them.

Finding a flaw in something that works is a good day's work. Most people never look for one.

Part 11

Look closer

25 min

a. Work it out by hand

Fill in this table without running anything. Assume the knob and sensor are wired as in this band.

Sensor readingKnob readingIs light < threshold?Lamp
800400nooff
200400  
400400  
399400  
2000  
10001023  
Check your table

200 and 400: yes, lamp on. 400 and 400: no, lamp off, because < means strictly less than and they are equal. 399 and 400: yes, lamp on, by one. 200 and 0: no, lamp off, because nothing is less than 0, so turning the knob all the way down switches the lamp off permanently. 1000 and 1023: yes, lamp on, so turning the knob all the way up leaves the lamp on almost all the time.

Those last two rows are worth noticing. The two ends of the knob are "never on" and "almost always on". That is a sensible design: the person can switch the whole thing off, or force it on, using the same control.

b. Break it on purpose

In b4_05, change if (light < threshold) to if (light > threshold). Predict what will happen before you upload.

Answer

It becomes a day lamp. It switches on when the room is bright and off when it is dark, which is exactly wrong for a night light and exactly right for something else, like a warning that a fridge door has been left open.

One character reverses the whole purpose of the device. Change it back.

c. Put the lines back in order

These lines have been shuffled:

analogWrite(lampPin, brightness);
int brightness = map(reading, 0, 1023, 0, 255);
int reading = analogRead(knobPin);

Put them in a working order and say why no other order works.

Answer

Read the knob, turn the reading into a brightness, then send the brightness out. No other order works because each line needs the name that the line before it created. You cannot map a reading you have not taken, and you cannot send a brightness you have not worked out.

d. Explain one line

In b4_05, the same comparison light < threshold appears twice: once to decide the lamp, and once again lower down to decide what to print. Why not just print inside the first if?

Answer

You could, and it would work. The reason it is written this way is that the printing block is deliberately separate: it always prints the same three things in the same order, so the output is easy to read and easy to compare between runs.

But you have spotted something real. The same test written twice means that if you ever change one and forget the other, the display will lie about what the lamp is doing. That is a genuine weakness, and the tidy fix uses a tool you meet in Band 5: work the answer out once, keep it in a name, and use that name in both places.

Full marks for anything that notices the duplication is a risk.

Part 12

Change it

30 min

Work on a copy of b4_05.

Bronze
Make the lamp fade as the light falls, instead of snapping on. The darker it gets, the brighter the lamp. You will need map and analogWrite, and you will need to think about which way round the map goes.
Silver
Print the reading in volts as well as as a number, using what you learned in Part 9. Then check it: at the halfway point on the knob, does it really say about 2.5?
Gold
Fix the flickering you found in Part 10. Use two limits instead of one: switch the lamp on when the light falls below the threshold, but do not switch it off again until the light rises above the threshold plus 50. Then find the smallest gap that stops the flicker, and write that number in your log.
A hint for Bronze

A low sensor reading means dark, and dark should mean bright lamp. So the two ranges run in opposite directions. Look again at the reversed map you tried in Part 6, step 3.

A hint for Gold, after you have tried it

You need the board to remember whether the lamp is currently on, because the rule now depends on that. A bool from Band 3 is exactly the tool.

If the lamp is off, switch on when light < threshold. If the lamp is already on, switch off only when light > threshold + gap. Two different tests, chosen by what the lamp is already doing.

Part 13

Make: something that watches and decides

100 min
What to build

A device that measures something about the world, compares it against a limit a person can set, and does something about it. Pick one, or bring your own:

  • A security light for a corridor or a doorway
  • A light that warns you when your room is too dark to read in
  • A plant monitor: has this plant had enough light today?
  • A cupboard alarm: a light comes on when the door is opened and light gets in
  • A study lamp that gets brighter as the room gets darker, so the total stays even
It is finished when all of these are true
  • The person using it can change the limit without touching any code
  • You have a calibration table with at least three real measurements, taken where the device will actually live
  • It does not flicker when the reading sits near the limit
  • The serial monitor shows enough for somebody else to work out what it is thinking
  • It still behaves sensibly when you take it into a completely different room

The test that matters most in this band

Set it up carefully where you built it, and check it works. Then carry it to a different room and switch it on without changing anything.

You do not need a laptop to do this. A phone charger or a power bank plugged into the same USB socket runs the board perfectly well, and plugging it in is switching it on. The sketch is already inside the board.

Write down what happened. Did it still make sense? Did the person have to reach for the knob straight away? Was the knob even in a place they could reach?

Almost every sensor project in the world fails this test the first time. Yours failing is normal and expected. What you write down about why is the actual work.

If you cannot move it to another roomTest it at two very different times of day instead, morning and after dark, without changing anything in between. That gives you the same lesson.

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, your calibration table, and one paragraph on what happened when you moved it. Then look at one other person's calibration table and ask them one question about how they chose their number.

If there is no other table to look atMeasure a second place properly and make a second table of your own, at a different time of day. Then write the question you would have asked somebody else, and answer it about your own two tables. The point is to notice that two honest measurements of the same thing disagree, and you can get that from your own work.
Part 14

Check yourself

15 min

Code you have not seen. Answer from reading only.

int sensorPin = A2;
int lampPin = 6;

void setup() {
  pinMode(lampPin, OUTPUT);
  Serial.begin(9600);
}

void loop() {
  int reading = analogRead(sensorPin);
  int level = map(reading, 0, 1023, 0, 100);

  float share = level / 100;

  analogWrite(lampPin, level);
  Serial.println(share);
  delay(100);
}
  1. What range of numbers can reading be in?
  2. What range can level be in?
  3. The lamp never gets close to full brightness. Why not?
  4. What will share print, for every reading except the very highest? Explain.
  5. Fix line by line: what is the smallest change that makes share work properly?
  6. The sketch has no wire connected to pin A2 at all. What will the serial monitor show, and what is that called?
Answers

1. 0 to 1023.

2. 0 to 100, because that is what the map was told to produce.

3. Because analogWrite wants 0 to 255, and level never goes above 100. So the lamp tops out at well under half brightness. The map should have gone to 255, not 100. Mixing up the two ranges is the classic Band 4 mistake, and this is it in the wild.

4. 0.00 every time, except when level is exactly 100, when it gives 1.00. Both level and 100 are whole numbers, so the division throws the fraction away. Writing float share does not save it, because the damage happens before the answer is stored.

5. Put a decimal point on the 100: float share = level / 100.0;. One character.

6. Numbers drifting and jumping about with no pattern, and changing if you wave your hand near the board. It is called a floating pin, exactly the same fault as the button in Band 3. An analog pin with nothing connected has no more idea what it is reading than a digital one does. This is the question that matters most in this band. If you answered "0", check what you saw in Band 3 Part 4.

Part 15

When something goes wrong

What you seeWhat it usually isWhat to do
The number never changesOne of the outer legs is not connectedCheck both ends of the divider reach the rails, and that the rails reach 5V and GND.
The number jumps about on its ownThe middle leg is not reaching the analog pinA floating analog pin, just like a floating button pin. Check that one wire.
The sensor barely changes with lightWrong fixed resistorYou need 10 000 ohms, striped brown black orange. A 220 ohm one gives almost no swing.
Bigger number when it gets darkerSensor and resistor are swappedNot wrong, just upside down. Swap them, or write down that for you a big number means dark.
Any calculation gives 0.00Whole-number divisionPut a decimal point on one of the numbers. See Part 9.
The lamp is very dim at fullYou mapped to 100 or 1023 instead of 255analogWrite wants 0 to 255. Check the last two numbers in your map.
The lamp flickers near the switching pointNothing is wrong. This is normalIt needs two limits with a gap. See Part 12, Gold.
A digitalWrite or pinMode acts on the wrong pinYou wrote 0 instead of A0For those instructions A0 is pin 14 and 0 is pin 0. (analogRead forgives you and treats them the same, which is why this only bites later.) Always write the capital A.
Everything was fine, now nothing worksThe rail wire to 5V or GND has come outThis build needs power on the breadboard. Check both rail wires first.
Still stuck after 30 minutes?

Photograph the board from above, and copy ten lines from your serial monitor. Post both, plus one sentence on what you expected. In this band the serial numbers are usually enough on their own for someone to tell you what is wrong.

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

Your board can measure the world now, not just be poked at. And you know the thing that separates a project that works on a desk from one that works in a room: the number a sensor gives you is not a fact about the world, it is a reading that has to be interpreted, in the place where it will be used.

You also met the division trap, which will catch you again one day. When a calculation gives you a stubborn zero, look at the types first.

Before you move on, make sure you have

  • Your working device, with a video
  • Your calibration table with at least three real measurements
  • Your paragraph on what happened when you moved it to another room
  • The number you found for Gold, if you did it
  • Both analogRead and analogWrite in your glossary, with their different ranges
  • Your build log for this band
  • Five or six correct answers in Part 14, including question 6

Next is Band 5: Simon Says. It is the hardest band so far and the most important one. You will write your own instructions for the first time, and you will find out why delay, which you have used in every single band, has been quietly holding you back the whole time.

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: the moment it decides, with the room actually changing.

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: your two threshold numbers and how you went and measured them.

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.