ExpKit Getting Started Guide 1.5
ExpKit Getting Started Guide 1.5
Project Guide
By Jonathan Oxer
Getting Started 2
Parts Guide 3
Software Setup 7
Project 1: Controlling An LED 8
Project 2: Controlling 8 LEDs 12
Project 3: Reading Digital (On/Off) Input 17
Project 4: Reading Analog (Variable) Input 21
Project 5: Dimming LEDs Using PWM 25
Project 6: Making Things Move With Servos 29
Project 7: RGB LED Colour Control 32
Project 8: Drive More Outputs With A Shift Register 35
Project 9: Making Sounds 41
Project 10: Detecting Vibration And Knocks 43
Project 11: Light Input Controlling Sound Output 46
Recommended Tools For Advanced Projects 48
More Information And Getting Help 49
Reading Resistor Colour Codes 50
But those magic boxes aren’t really magic at all. They’re just carefully designed machines that do a
certain job, and you can learn how they work.
By starting with some basic projects and learning the principles of how various electronic parts work, you
can create your very own inventions and designs.
Most modern electronic devices are actually a combination of both hardware and software, and that’s
where Arduino comes in. Arduino boards are tiny computers that let you build your own hardware
projects, and then run small programs called “sketches” to make that hardware do different things.
This combination of hardware and software is what makes electronic devices seem so magical, and it’s
what makes them both flexible and powerful. The hardware provides the inputs and the outputs, while
the software controls how the device will behave.
This guide will help you get started with your first adventures in electronics, but there’s a whole world of
opportunities to explore if you want to take things further.
Most importantly, we hope you have fun and learn many interesting things along the way!
forum.freetronics.com
www.freetronics.com/expkit
www.freetronics.com/eleven
Solderless Breadboard
Under the holes in the breadboard are tiny sockets that make
connections to whatever you plug in, and also links them
together in rows across the breadboard. By plugging two or
more leads or jumper wires into the same row they will be
connected together inside the breadboard.
www.freetronics.com/breadboard
We’ve provided a big bundle of jumper wires that you can use
to connect your Arduino to your breadboard, and to make
connections between different parts of the breadboard.
LEDs can provide visual feedback from your projects. You can
use them to show status, or to show that your project has
detected a certain event or input, or for lighting effects or
displays. We’ve provided a selection of red and green LEDs,
and you can also buy blue, white, yellow, orange, and other
colours.
LEDs can easily be burned out if you let too much current flow
through them, so make sure you use a “current limiting
resistor” as explained in Project #1.
LEDs are “polarised”, which means they only work one way
around: one lead needs to be connected to positive, and the
other to negative. You can tell the leads apart because the
positive lead is longer. The LED also has a small flat spot on
the body next to the negative lead, which is handy if the leads
have been cut to the same length.
RGB LED
Most LEDs are just one colour, but RGB LEDs are special:
they combine three different LEDs (one each of red, green,
and blue - hence the name) into a single physical package.
If you turn on just the blue part, it will glow blue. Turn on the
red part, it will glow red. Turn on all three, and it will glow
white. By varying the relative intensity of each of the three
colours you can produce all the colours of the rainbow.
Unlike regular LEDs, RGB LEDs have four leads: one common
lead, plus one lead for each of the colour elements.
Servo Motor
Resistors
Diodes
That means it’s very important that you put them in place the
right way around, so diodes are marked with a tiny band near
one end so you can tell which end is which.
Transistors
www.freetronics.com/light
www.freetronics.com/sound
Windows users please note: The USB driver for the Eleven must be downloaded and used for first-time
installation of the Eleven's USB port. Full instructions are online at:
www.freetronics.com/usbdriver
3. With the Arduino IDE installed, we're ready to do the initial board and port setup. You won't need to do
this again unless the serial port number changes such as when using a different USB port on your
computer.
● In the Arduino IDE, select “Tools > Board > Arduino/Genuino Uno”.
● Before connecting your Eleven to the USB port, have a look at the list of ports in “Tools > Port”.
That's where your Eleven serial port is going to appear when you plug it in.
● Connect the Eleven to your computer USB port with a USB cable. After a short while if you look
at “Tools > Port” again you'll see a new port appear: that's the Eleven ready to be used. Select
that port now with “Tools > Port” so there is a tick mark next to it.
You're ready to go. The Arduino IDE now knows about your board and has a connection to it. Our Eleven
boards ship with the "Blink" sketch preloaded so you should immediately see the blue power LED
illuminate, and a red LED will begin flashing on and off at 1 second intervals.
2. Select “Sketch > Verify/Compile”. You've now “compiled” (prepared) the program ready to be sent to
the Arduino board.
3. Select “Sketch > Upload”. You'll see the red D13 LED flicker, then the green and yellow RX and TX
LEDs will flash while the upload is being done.
4. A few seconds later the RX and TX LEDs will go off, the board will reset, and the red D13 LED will
begin flashing on and off at 1 second intervals. Congratulations! You've now compiled and uploaded
your first sketch to the Eleven.
Parts required
1 x “Eleven” Arduino-compatible microcontroller board
1 x LED (either green or red, it doesn’t matter)
1 x 470 Ohm resistor (either yellow-violet-black-black-brown, or yellow-violet-brown-gold)
1 x Solderless breadboard
2 x Jumper wires
Bend the leads of the resistor around until it’s in a “U” shape like a big staple, then insert it so that one
resistor lead is in the same row as the “-” lead of the LED and the other resistor lead is in a sidebar of the
breadboard.
Next, use a jumper wire (preferably black as a matter of convention, but it doesn’t really matter) to
connect the same breadboard sidebar to one of the Arduino headers marked “GND”. GND is an
abbreviation for “ground”, which means 0 Volts. All other voltages in the circuit are measured relative to
GND.
Finally, use a second jumper wire to connect the breadboard row with the LED “+” lead in it to the
Arduino header marked “13”.
That means the Arduino now has the power to control whether any electricity flows through the LED. If
the Arduino digital output is in a “low” (0V) state, no electricity will flow through the LED. However, if the
digital output is in a “high” (5V) state, there is 5V applied across the LED and resistor together so the
LED will light up.
Software
Now that the Arduino has the ability to control the LED, we need to give it a program that will tell it what
to do. You may have already followed these steps when testing the software setup.
Open the Arduino IDE on your computer, and open the following menu:
The IDE will open a window containing a very simple program called “Blink”, which we can use to make
the LED blink on and off.
Plug your Arduino into your computer using a USB cable, and either select “Sketch > Upload” from the
menu or click the little round “Upload” button near the top left of the IDE window. It’s the one that looks
like an arrow pointing to the right. The upload menu and the upload button do exactly the same thing:
they’re just different ways to tell the Arduino IDE that you want it to upload the current sketch to the
Arduino board. It doesn’t matter which method you use.
After a few seconds the program will be prepared (“compiled”) and sent to the Arduino through the USB
cable, and your Arduino will then start flashing your LED on and off about once per second.
If the LED isn’t flashing, don’t worry. It’s easy to have one of the parts just a little bit out of place, so go
back over your circuit and compare it with the instructions above. In particular, make sure that the LED is
the right way around.
Blink starts with a section called “setup()”, which begins and ends with curly brackets. The curly brackets
are like the covers of a book: they define the boundaries, and all the pages of the book are inside them.
In this case the only thing inside setup() is a comment and a single operational line.
void setup() {
// initialize digital pin LED_BUILTIN as an output.
pinMode(LED_BUILTIN, OUTPUT);
}
The comment line starts with two slashes so that the computer knows it’s not part of the program.
Comments are ignored by the computer. They are used by programmers to write notes to explain what
the program is doing.
The line after the comment tells the Arduino to set the “pinMode” of the pin called “LED_BUILTIN” to be
an OUTPUT.
The digital pins on an Arduino can be used as either inputs or outputs, so it needs to know what you
want it to be. Sometimes you want a pin to be an input so that it can read from things like buttons, and
sometimes you want it to be an output so that it can control things like LEDs. In other projects we’ll use
some pins as inputs and some as outputs.
Many Arduino boards have an LED included right on the board so that you can make it flash. Different
types of boards have the LED on different pins, so this name is like a shortcut (or an alias) that will work
on all boards. In the case of the Eleven, the built-in LED is on pin 13, and we’ve also connected our
external LED to pin 13.
So when we set the pinMode on the pin called LED_BUILTIN, we’re actually setting it on pin 13. You
could just as easily put “13” into the program instead of typing “LED_BUILTIN”, but then you might need
to change it if you want to run the same program on a different type of Arduino.
The setup() section is only run once when the Arduino starts up, so it’s used for commands that you only
want it to do once. In this case setting the pin mode only needs to be done once when the program starts
Next we have another block of commands called “loop()”, and it also begins and ends with curly
brackets. The difference is that although setup() is only executed once when the Arduino starts up, the
loop() section is run over and over again. As soon as the Arduino gets to the end of the commands
inside loop(), it jumps right back to the start and does it all over again.
void loop() {
digitalWrite(LED_BUILTIN, H IGH);
delay(1000);
digitalWrite(LED_BUILTIN, L OW);
delay(1000);
}
Let’s step through it, just like the Arduino does when it’s running the program.
First is a command called “digitalWrite()”, which tells the pin referred to as “LED_BUILTIN” (pin 13 on the
Eleven) to go HIGH. Going HIGH will make the pin go to 5V, which will then make the LED connected to
that pin turn on.
Next is a “delay()” command, which tells the Arduino to stop doing anything until a certain period of time
has gone by. When it reaches this command it just sits and does nothing for a while, waiting for the time
to be up. The number in the brackets tells it how many milliseconds (thousandths of a second) it should
wait, so with the command “delay(1000)” it will wait for 1000 milliseconds (one second) before moving on
to the next command.
Next is another digitalWrite, but this time it sends the pin LOW (0V) so the LED will turn off.
Finally another delay(), so that the Arduino will wait another second before doing anything else.
Once the second delay has finished, the Arduino reaches the closing curly bracket that indicates the end
of the section so it scoots right back to the start of the “loop()” block to begin all over again.
The end result is a simple sequence of events: the Arduino turns on the LED, waits one second, turns off
the LED, waits one second, and then does it all again, forever.
Now that you’ve gone through the Blink program line by line, it should seem much easier to understand.
Read through it again from the top, and you’ll see that it’s simply a list of instructions for the Arduino to
follow. Each instruction tells it to do something, then it goes on to the next one.
Try altering the Blink sketch a bit to make it behave differently. For example, change both of the “1000”
delay values to 100 so that it blinks ten times as fast. Try different values in the two delays, and see what
effect it has on how the LED blinks.
Each time you make a change to the sketch, click the “Upload” button again near the top left so that the
new version is uploaded to your Arduino and you can see the result.
We’ll use a sketch that makes a light “scan” along a row of LEDs, much like the Kitt scanner in the show
“Knight Rider” or the red Cylon eye in Battlestar Galactica.
Parts required
1 x “Eleven” Arduino-compatible microcontroller board
8 x LEDs (either green or red, it doesn’t matter)
8 x 470 Ohm resistors (yellow-violet-black-black-brown, or yellow-violet-brown-gold)
1 x Solderless breadboard
9 x Jumper wires
Let’s start with the LEDs. Insert a total of eight LEDs in a row along the solderless breadboard, checking
that they all have the long (+) lead to the right.
Now insert a total of eight resistors, each one connecting between the short (-) pin of an LED and the
common GND bar on the side of the breadboard.
Finally, use jumper wires to link each of the LED + connections to one of the digital pins on the Arduino.
We used pin 13 for the first LED, so work backwards in sequence to connect the additional LEDs to pins
12, 11, 10, and so on.
Software
Open a new sketch in the Arduino IDE by going to “File > New”, then type in the following code or copy
and paste it from our site. You can find all the source code at www.freetronics.com/expkit:
int ledCount = 8;
int ledPins[] = { 6, 7, 8, 9, 10, 11, 12, 13 };
int ledDelay = 300;
void setup() {
for (int thisLed = 0; thisLed < ledCount; thisLed++) {
pinMode(ledPins[thisLed], OUTPUT);
}
}
void loop() {
for (int thisLed = 0; thisLed < ledCount-1; thisLed++) {
digitalWrite(ledPins[thisLed], HIGH);
delay(ledDelay);
digitalWrite(ledPins[thisLed], LOW);
}
for (int thisLed = ledCount-1; thisLed > 0; thisLed--) {
digitalWrite(ledPins[thisLed], HIGH);
delay(ledDelay);
digitalWrite(ledPins[thisLed], LOW);
}
}
The “ledCount” variable specifies how many LEDs are connected, so you can use this same sketch with
a different number of LEDs if you like. It starts with “int” to tell the Arduino that we want to store an
“integer” (whole number) with this name.
The “ledPins” variable is an “array”, which you can think of as being like a list: in this case it’s a list of the
pins that the LEDs are connected to. Later in the sketch we’ll read the list to turn different LEDs on and
off.
The “ledDelay” variable just sets the number of milliseconds to leave each LED on for. To make the
scanner run faster, make the number smaller. To slow it down, make the number bigger.
The setup() function is where things get interesting. It could alternatively have been written with a series
of eight nearly-identical lines, each one using pinMode() to set one of the LED pins to OUTPUT mode,
but that’s not a convenient way to write longer programs. Instead it uses a “for” loop, which runs
pinMode() eight times but with a different value each time.
The first argument passed to the “for” loop sets the name of the variable that will be used as the “loop
counter”. In this example the loop counter is a number called “thisLed”, and it’s given a starting value of
0.
The second argument sets the terminating condition so the “for” loop will know when it should stop
running. The loop will keep repeating itself until the condition fails, so in this case the loop will repeat until
the value of “thisLed” is equal to the value of “ledCount”. We’ve set ledCount to 8, so it will keep running
until thisLed is equal to 8.
The third and final argument is an action that the loop will perform every time it runs. The “++” operator is
a shorthand way of saying to take a variable and add 1 to it, so in this case the “thisLed” variable will get
bigger by 1 every time the loop executes.
When you put those three arguments together, you have a loop that will behave in a specific and
predictable way. It starts out with a variable with a value of 0, increases that value by 1 each time it runs,
and when the value reaches 8 it stops. It looks confusing, but it’s really just a very concise way of saying
“do this particular thing 8 times, slightly differently each time” without having to write each one out
individually.
The loop itself is interesting, but what’s happening inside it is also interesting. You’ll see it references
“ledPins[thisLed]”, which looks a bit confusing. You’ll remember that the variable “ledPins” is an array, or
list, containing a series of values. Referencing it this way allows us to look at specific positions in the list.
Imagine you have a restaurant menu with a list of dishes, and each one has a number next to it: you
don’t need to state the name of the dish, you can just say “I’ll have number 4, please” because the
position (or number) of the entry is an easy way to reference that item on the menu.
In arrays, the position in the list is called the “array index”, and it’s a number that specifies what position
in the array we want to examine. But unlike typical restaurant menus, array indices don’t start at 1: they
start at 0, so the first position in the array is referenced as index 0. The second position is index 1, and
So when the value of “thisLed” is 0, it’s the same as referencing “ledPins[0]”, which is position 0 (the first
item) on the list. The original code looks like this:
pinMode(ledPins[thisLed], OUTPUT);
The value for “thisLed” is 0 on the first pass through the loop, so to understand what’s going on we can
imagine the variable has been replaced by its value, like this:
pinMode(ledPins[0], OUTPUT);
But of course “ledPins[0]” is really just pointing to the first position in the list. Looking back at the
definition of the ledPins array, we can see that the first item on the list has a value of “6”. That means the
command that is really being executed on the first pass through the loop is this:
pinMode(6, OUTPUT);
Then on the next pass through the loop, the value of “thisLed” has increased to 1, so we’re referencing
“ledPins[1]”, which is the second item on the list. Then if you look at the second item on the list and
substitute it in, the end result is that what will really be executed on the second pass through the loop is
this:
pinMode(7, OUTPUT);
And so on.
Arrays can be a tricky concept, but they’re very powerful and can make your sketches much simpler by
allowing you to define lists of things and then step through the list, instead of specifying similar but
slightly different operations over and over again and taking many more lines to achieve the same end
result.
Next we get into the “loop()” part of the program, which will repeat forever. It might look cryptic at first
glance, but when you break it down into its major sections it’s fairly simple.
It’s really just two more “for” loops, that each operate just like the “for” loop we looked at a moment ago.
The first loop increments a counter to step forwards through the list using the “++” operator explained
previously. It begins at the start of the list of LEDs, and for each one it turns it on, then waits for a delay
period, then turns it off again before moving on to the next one.
Once the first loop finishes, the second loop begins. The second loop is almost the same, but it runs
backwards! It starts at the last position in the list of LEDs, and each time through it uses the “--” operator
to decrease the position value by 1. It’s like reading the restaurant menu backwards, starting at the last
item.
When it reaches the start of the list, the second loop finishes and the program jumps back to the start to
begin the first loop all over again.
Or you could consider other ways to structure this sketch. For example, think about how you could make
it scan from side to side but only use one “for” loop instead of two. At first glance that may seem
impossible, but by thinking about how the array is used as a list to step through the LEDs in sequence
it’s actually quite easy. For example, instead of having a simple list of pins and stepping through it first
one way and then the other, you could make a longer array that specifies the complete sequence for an
up-and-back scan, and just loop over it once, like this:
void setup() {
for (int thisLed = 0; thisLed < ledCount; thisLed++) {
pinMode(ledPins[thisLed], OUTPUT);
}
}
void loop() {
for (int thisLed = 0; thisLed < ledCount-1; thisLed++) {
digitalWrite(ledPins[thisLed], HIGH);
delay(ledDelay);
digitalWrite(ledPins[thisLed], LOW);
}
}
Yes, we’ve told the sketch that we have 14 LEDs when we really only have 8, but that doesn’t matter.
The 14 LED positions count up from 6 to 13 and then back down again, repeating some of the positions.
Of course this means that setup() will call pinMode() multiple times on the repeated pins, but that doesn’t
matter. No harm will be done, and the loop can then step through the list as if it’s a linear sequence when
in fact the list doubles back on itself.
Parts required
1 x “Eleven” Arduino-compatible microcontroller board
8 x LEDs (either green or red, doesn’t matter)
8 x 470 Ohm resistors (yellow-violet-black-black-brown, or yellow-violet-brown-gold)
1 x Momentary pushbutton
1 x 10K Ohm resistor (brown-black-black-red-brown, or brown-black-orange-gold)
1 x Solderless breadboard
11 x Jumper wires
Next, insert a pushbutton into the solderless breadboard as shown, paying attention to the difference in
spacing between the pins. If you look closely you’ll see that the pins are in two pairs, slightly further apart
in one direction than the other. Even though the button has a total of four pins, that’s only to make it
mechanically stronger when it’s mounted: it really only has two connections, which are doubled up so
that it can have four pins.
Internally, the pins are connected along the long sides of the button. If you orient it as shown in the
breadboard layout with the long sides spanning the central gap, and then connect one wire to the left of
the button and one wire to the right, it’ll work just fine.
Use a jumper lead to connect from one side of the button to the “D2” digital pin on the Arduino.
Use a 10K Ohm resistor to connect from that same side of the button to the “GND” (0V) rail on the
breadboard.
Use a jumper wire to connect from the other side of the button to the 5V header on the Arduino.
The button, 10K Ohm resistor, and associated jumper wires form a circuit that pulls Arduino digital pin D2
down to 0V through the resistor. This is called “biasing”, where a resistor is used to connect a digital pin
to a certain voltage (in this case 0V) so that it tries to be at that voltage. However, because the
connection goes through a resistor instead of directly through a simple piece of wire it’s not pulled “hard”
to that voltage, and it’s possible to override it and force it to a different voltage if you want to.
That’s done using the button, which is also connected to the digital input and has its other connection
going directly to 5V. The result is that when the button is not being pressed, digital pin D2 is pulled down
to 0V (“low”) through the resistor, but when the button is pressed it’s pulled up to 5V (“high”) through the
button.
The terms “high” and “low” are commonly used (often capitalised) to describe the “state” of parts of a
digital circuit, and you’ll see them used in many places in Arduino sketches. You’ll often see statements
like “pin 13 is in a LOW state” or “pin 7 goes HIGH” in discussions of digital circuits.
What this button circuit does is allow the sketch running on the Arduino to detect when the button is
being pressed, because it can measure the voltage of the digital pin connected to it. If it measures the
voltage of the pin and discovers it’s low, it knows the button isn’t being pressed. If the pin is high, it
knows the button is currently being pressed. In a moment we’ll take advantage of that to use the button
to change the behavior of the LEDs.
void setup() {
for (int thisLed = 0; thisLed < ledCount; thisLed++) {
pinMode(ledPins[thisLed], OUTPUT);
}
pinMode(buttonPin, INPUT);
}
void loop() {
for (int thisLed = 0; thisLed < ledCount-1; thisLed++) {
digitalWrite(ledPins[thisLed], HIGH);
delay(ledDelay);
while(digitalRead(buttonPin) == HIGH) {
delay(10);
}
digitalWrite(ledPins[thisLed], LOW);
}
}
Near the top of the sketch the “buttonPin” variable is set to the value 2, because the button is connected
to digital pin 2.
Inside setup(), the button pin is set to be an input so that the sketch can read from it and detect whether
it’s currently at a HIGH (5V) or LOW (0V) value. Remember that we have a 10K Ohm resistor biasing the
input low, so most of the time it will be at 0V and will read low. When the button is pressed the input will
be pulled up to 5V, and will read high.
Finally, inside the loop that scans along the LEDs, there is a new section of code:
while(digitalRead(buttonPin) == HIGH) {
delay(10);
}
This little section of code includes some very important programming concepts, including a while loop,
reading an input, and a comparison operator.
In this case, the condition that we’re testing inside the brackets looks like this:
digitalRead(buttonPin) == HIGH
Pay special attention to the double equals sign. No, it’s not a typo!
In programming, a single equals sign is used to specifically set one value to be equal to something else.
This is called an “assignment”. We’ve already seen this, like at the start of this program where the
variable called “ledCount” is set to a value of 14.
However, a double equals sign is like a question mark: it’s not setting the value, instead it’s checking
whether something is equal to something else. This is called a “comparison”. If the two sides of the
comparison are the same, then the comparison is true. If the two sides aren’t the same, the comparison
is false.
In this case, the comparison is checking whether the value of this command:
digitalRead(buttonPin)
is the same as the value “HIGH”. If it’s the same, the comparison is true and the loop will continue.
Otherwise, the comparison is false and the loop will finish.
In Arduino, the “digitalRead()” command is used to read from a digital input to see if it’s currently at a
high voltage or a low voltage. As long as the button is held down, the voltage at the pin will be high. The
condition will therefore be true so the loop will continue repeating itself.
In this case there’s nothing inside the loop except a delay of 10 milliseconds, so the loop will sit there
repeating the delay. The program can’t continue and the scanner will pause. Release the button and the
condition will be false, and the scanner will resume as before.
Further experiments
This project is controlled by a pushbutton that provides a simple “yes/no” value, but it’s not just buttons
and switches that behave this way. Many other devices have simple on/off outputs that you can read just
like a button, so with the skills you’ve learned so far you could replace the button with a variety of other
devices such as a security system motion detector, or a thermal switch, or a tilt switch.
Then the behaviour of the scanner could be controlled automatically by whatever sensor you have
connected, instead of manually by you.
In this project we’ll measure the level of light in the room, and show how to send that value to your PC so
you can read it on the screen and also use it to change how the sketch operates.
Parts required
1 x “Eleven” Arduino-compatible microcontroller board
1 x LED (either green or red, doesn’t matter)
1 x 470 Ohm resistor (yellow-violet-black-black-brown, or yellow-violet-brown-gold)
1 x “LIGHT” Light level sensor module
1 x Solderless breadboard
5 x Jumper wires
Connect a jumper wire from D11 through a 470 Ohm resistor, then the LED, then to GND, as shown in
the diagram.
The LIGHT module has three connections. They are designed to have a header or wires soldered
directly to them, so to make it easy for you to use the module in your breadboard we’ve pre-fitted header
pins. That way you can just plug them in and use jumpers to link them to your Arduino.
The three module pads need to be connected to three specific places on your Arduino:
● The “GND” connection on the left needs to link to GND on the Arduino.
● The “OUT” connection in the middle needs to link to Analog input A0 down near the bottom of the
Arduino.
● The “VCC” connection on the right needs to link to 5V on the Arduino.
The interesting part is the connections to the LIGHT module. The module needs GND and 5V
connections as a power supply so that it can operate, so that’s easy. Then, when it is powered up, it
reads the intensity of the light that is falling on it and changes the voltage on the OUT pin proportionally.
If the module is in complete darkness, it will output very close to 0V on the OUT pin. When the module is
in intense light, it will output very close to 5V on the OUT pin. When it’s in dim light, it will be somewhere
around the middle at about 2.5V, and so on.
So by measuring the voltage of the OUT pin in the range of 0V to 5V, we can tell how much light is falling
on the module.
Remember in the previous project we measured whether a button was being pressed or not, by reading
one of only two states: high and low. That was a digital value that was being read, because it could only
be in one of those two states. This is different, because the output from the LIGHT module could be 0V,
or 5V, but it could also be anywhere in between. We can’t read it as a digital input because it could be at
2.865V - what does that mean? Would we read it as high or low?
A signal that can have values anywhere across a range is called “analog” and the Arduino has a row of 6
inputs near the bottom right specifically designed for measuring analog signals.
Software
Open a new sketch in the Arduino IDE and type in the following code, or copy and paste it from our site:
void loop()
{
lightLevel = analogRead(A0);
Serial.print("Light level: ");
Serial.println(lightLevel, DEC);
digitalWrite(led, HIGH);
delay(lightLevel);
digitalWrite(led, LOW);
delay(lightLevel);
}
Upload it to your Arduino as usual using “File > Upload”, and then open the serial monitor. You can
open the serial monitor by going to “Tools > Serial Monitor”, or by clicking the little spy-glass icon in the
top right corner of the main program window. Once the serial monitor window opens, look in the bottom
right corner for a drop-down menu and select “38400 baud” from the list.
After a moment you should see a series of values being printed in the serial monitor while the LED blinks
on and off. Changing the light level will change the rate of the LED, and you will also see the values
change in the serial monitor. Try putting your hand over the light sensor and see if the flash rate of the
LED gets faster. Try shining a bright torch on it or putting it in direct sunlight and see if it gets slower.
The first is the use of the USB connection to send serial data back to your computer, so that you can
read it in the serial monitor. This is an extremely useful technique that you’ll use in many Arduino
projects.
Inside the setup() function, the Arduino is told to begin a serial connection to your computer at a rate of
38400 baud:
Serial.begin(38400);
Then later in the sketch, values are “printed” to the serial connection so that they can be displayed on
your computer in the serial monitor:
The first command prints text followed by a space, and then the second command prints the value of the
lightLevel reading as a decimal number. It also starts a new line ready for the next set of output, which is
why it says “println” (short for “print line”) instead of just “print”. That’s just to keep the output looking
neater on the screen.
Right now you’re probably thinking “Why is the maximum value 1023? And why is the middle reading
511? That doesn’t make any sense! Why couldn’t they make it read from 0 to 100, or 0 to 1000, or
something sensible like that?”.
It may not make sense when you first see it, but there’s a very good reason the values read from 0
through to 1023. The explanation is quite complicated, but it’s to do with the fact that the special circuitry
inside the analog inputs has to take a continuously-varying level and break it down into a series of
distinct steps, and figure out which step the voltage is closest to. There is a very detailed explanation of
the process in the book “Practical Arduino” by Jonathan Oxer and Hugh Blemings if you want to look into
the details. See www.practical-arduino.com for more information.
For now, just accept that 0 is the lowest reading, 1023 is the highest, and the rest of the range is spread
evenly between those limits.
After reading the light level from the module and obtaining a value between 0 and 1023, the sketch then
uses that value to decide how long to wait each time it turns the LED on and off. This makes the LED
flash at different rates depending on how bright the light is, because if the light level is low the delay will
be shorter and if the light level is high the delay will be longer.
Further experiments
This example makes the flashing get slower as the brightness increases. How could you reverse the
behavior, so that the flashing gets faster as brightness increases? One simple way is to read the value
from the sensor, then instead of using it directly you could subtract it from 1023:
delay(1023 - lightLevel);
A reading of 0 will then give a delay of 1023, and a reading of 1023 will give a delay of 0. Other
intermediate values will likewise be inverted.
Rather than simply altering the flash rate of a single LED, you could combine this project with project #3
to drive 8 LEDs and have the delay duration vary with the reading from the light sensor. Then the
scanning speed will get faster as the light gets dimmer.
What if you want to control the input manually, rather than based on light level? For that you can use the
variable resistor included in the Experimenters Kit. Connect one of the end connections to GND, the
other end connection to 5V, and the middle connection to the A0 analog input. You can adjust the
position of the variable resistor, and the voltage on the middle pin will vary proportionally.
Sometimes you don’t want things like LEDs to be either fully on or fully off. You want them to be half on,
or a quarter on. But that’s harder than it sounds, because to a computer, everything is “yes or no”, “high
or low”, “on or off” values: everything is black or white, computers don’t like grey! This is called “binary”
logic, where everything is either 0 or 1. The outputs from the Arduino are the same. They can be either
off or on, but not half on or half off.
The solution is a trick called “Pulse Width Modulation”, usually just called PWM. In this project we’ll use
PWM to control an LED so that it looks like it’s breathing: slowly pulsing on and off.
Parts Required
1 x “Eleven” Arduino-compatible microcontroller board
1 x LED (any colour)
1 x 470 Ohm resistor (yellow-violet-black-black-brown, or yellow-violet-brown-gold)
1 x Solderless breadboard
2 x Jumper wires
The interesting part is the magic inside the Arduino that does the PWM output.
PWM is a sneaky way to use a digital output and make it pretend to be partly on, even when it can’t be.
Like most magic, the trick is in the timing: if you have a digital output going to an LED, and you turn it on
and off very fast, the LED will be fully on for some of the time and fully off for some of the time. If you do
it fast enough, the human eye can’t see it flashing on and off. The human eye has a slow response time
which results in a phenomenon known as “persistence of vision” or the “flicker fusion threshold”. If you
make an LED flash on and off more than about 30 times per second you won’t be able to detect the
individual flashes. It will just look like the LED is dimmer than normal.
So if you want to make an LED look like it’s at about half normal brightness, it’s easy: just turn it on for a
set period of time, then turn it off for the same period of time, and so on. If it’s on about half the time
that’s what engineers call a “50% duty cycle”, and the result is that the LED will be about half as bright as
normal.
But what about other brightness levels? What if you want to make the LED look like it’s at ¼ brightness?
Easy, just change the relative times of the “on” and “off” periods. That’s why it’s called “pulse width
modulation” - it’s the width (duration) of the pulse that changes to give different output levels. To achieve
¼ output (or 25%) you just change the timing so that it’s turned on ¼ of the time, and turned off ¾ of the
time. For example, you could turn on the output for ten milliseconds, then turn it off for thirty milliseconds,
on for ten, off for thirty, and so on.
That sounds like a lot of work! You can use the “delay()” function that you’ve already seen to set up the
timing manually, but it can make your sketch quite complicated. Luckily the Arduino has a special feature
that makes it really easy to use PWM on certain outputs. If you look closely at the labels near the
headers on your Eleven, you’ll see that some of the pins have a tiny “PWM” label. You can use those
special outputs to control things like the brightness of LEDs using a very simple command in your sketch.
Inside the microcontroller is special circuitry attached to those pins that accepts a setting to tell it what
duty cycle to run at, and then it just keeps turning the pin on and off very fast to maintain that duty cycle.
Once your sketch has told the pin what duty cycle it should run at, the sketch can continue on doing
other things and the microcontroller will keep the pin running at that same duty cycle until it’s told
otherwise.
Software
Open a new sketch in the Arduino IDE and type in the following code, or copy and paste it from our site:
void setup() {
pinMode(led, OUTPUT);
}
void loop() {
while(brightness < 255)
{
analogWrite(led, brightness);
delay(delayTime);
brightness = brightness + 1;
}
while(brightness > 0)
{
analogWrite(led, brightness);
delay(delayTime);
brightness = brightness - 1;
}
}
In the first “while” loop, the program steps the brightness value up from 0 to 255. Each time it goes
around the while loop it increases the value by 1. Once the value reaches 255 the condition will fail and
the loop will end. Then it moves on and starts repeating the second loop, which steps the brightness
back down again from 255 all the way to 0. Then the second loop ends, and everything starts again.
The important part of this program is the lines that use “analogWrite()”, which tell the PWM-capable pin
called “led” to pulse rapidly on and off with a specific timing:
analogWrite(led, brightness);
When “brightness” has a value of 0, the pin called “led” (which we set to be pin 11 at the start of the
program) will be permanently off: a 0% duty cycle.
When it has a value of 255, the pin will be permanently on: a 100% duty cycle.
With a value of 127 (half way between 0 and 255) the pin will be on half the time and off half the time: a
50% duty cycle. By stepping the value up from 0 all the way to 255 the duty cycle of the pin will rise
slowly from not on at all at the beginning, to fully on at the end. This will cause the LED to start totally off
and gradually illuminate more until it’s totally on.
To the human eye the result is very simple, with a smooth transition from fully off to fully on in 256 steps.
Further experiments
Combining this project with the light sensor, you could make a night-light that varies the illumination level
depending on how bright the background light level is. Start with the sketch from the previous project,
and restructure it so that the loop isn’t delaying different amounts depending on the light level: instead, it
sends different values to analogWrite() to change the brightness of the LED.
Remember though that analogWrite() needs values between 0 and 255, while analogRead() gives values
between 0 and 1023. That means you need to proportionally scale back the reading from analogRead()
by dividing it by 4 before you can use it to set the LED brightness.
A sketch like this should do the job, and it will also send the readings to the serial console so you can
watch the values if you want to:
void setup() {
Serial.begin(38400);
pinMode(led, OUTPUT);
}
void loop() {
lightLevel = analogRead(A0);
ledLevel = lightLevel / 4;
Serial.print("Light level: ");
Serial.println(lightLevel, DEC);
analogWrite(led, ledLevel);
delay(100);
}
Controlling servo motors is easier than you may think, and it opens up all sorts of possibilities for projects
that let your Arduino control the physical world.
Parts required
1 x “Eleven” Arduino-compatible microcontroller board
1 x Servo motor
3 x jumper wires
Hardware assembly
Assembly for this project is very easy. Simply plug the three jumper wires into the connector on the
servo, and then plug the other ends into the appropriate locations on your Arduino. You don’t even need
a breadboard.
Servos generally have three connections: “+”, “-”, and “signal”. The trick is knowing which wire is which,
because different manufacturers often use their own colour codes and connection order. Luckily the big
servo manufacturers decided to all use the same connections to reduce confusion, which in turn has
forced many of the smaller servo manufacturers to follow their lead. You have to be careful though
because sometimes you’ll come across servos that use different connections, so you need to check the
manufacturer’s specifications just to be safe.
Use jumper wires to connect the servo to your Arduino as shown in the diagram.
The positive and negative supply connections simply provide power to the servo motor and its control
electronics.
The interesting part is the “signal” connection, which your Arduino uses to tell the servo what angle to
move to. Servos work on a PWM (pulse width modulation) signal, similar to the technique used in the last
project to dim LEDs. The servo reads the signal and converts it into an angular setting. Most servos can
turn approximately 180 degrees, including the servo included with your kit. However there are many
variations available with different sizes, rotational abilities and strength.
Software
Open a new sketch in the Arduino IDE and type in the following code, or copy and paste it from our site:
int delaytime=10;
int angle=0;
#include <Servo.h>
Servo myservo;
void setup()
{
myservo.attach(11);
}
void loop()
{
while (angle <=180)
{
myservo.write(angle);
delay(delaytime);
angle = angle + 1;
#include <Servo.h>
There are hundreds of libraries available for Arduino, each providing a special set of features for some
specific purpose. You can load libraries into your program and then make use of their features, which
saves you from having to do all the work and write the features yourself.
The servo library makes controlling the servo very easy. We can use its “write” function to send a specific
value to the servo, and then it will turn to that position. We’ve set the angle we want in the variable called
“angle”, so we can simply say:
myservo.write(angle);
It will accept any value between 0 and 180, since this is the rotational range of the servo.
You can see in the sketch how the servo will start at 0 degrees, then rotate around to 180 degrees and
then return to 0. The speed at which it moves through the steps can be altered by changing the value of
the variable “delaytime”. We’ve set it to 10 milliseconds, which means it will take 10 x 180 = 1800
milliseconds (just under 2 seconds) to fully sweep from one end to the other.
Further experiments
You could create a light level meter that uses the light sensor to measure the ambient light, which is then
used to set the position of the servo. You could attach a small arrow to the servo horn, and make a scale
behind it that shows the light level from fully dark through to fully bright.
Or read values sent to the sketch via USB from the Serial Monitor in the Arduino IDE, so that you can
type in a value and have the servo move to that position.
Parts required
1 x “Eleven” Arduino-compatible microcontroller board
1 x RGB LED (common-cathode type)
3 x 470 Ohm resistors (yellow-violet-black-black-brown, or yellow-violet-brown-gold)
1 x Solderless breadboard
4 x Breadboard jumper wires
By connecting power to the different pins, it’s possible to make the 3 different elements inside the RGB
LED light up. By adjusting the brightness of each of the three elements individually you can generate
whatever colour you like.
Turn on just the blue element, and you get blue. Light up the red and green elements together, and you
get yellow. Light up all three, and you get white, and so on.
If you look carefully at the four leads of the RGB LED you’ll see that one is longer than the others. That
lead is a common “cathode” (negative) lead that each of the three LED elements inside the RGB LED
shares with its siblings. The other three leads are the individual “anode” (positive) leads of the three
LEDs.
If you took three separate red, green, and blue LEDs and joined their negative leads together, you would
effectively have the same thing is what’s inside the RGB LED package.
Spread the LED legs apart just enough that all four can be inserted into adjacent rows of the solderless
breadboard as shown in the diagram, making sure to insert the long lead in the location shown by the
black jumper wire.
Place the three resistors into the breadboard, so that one end of each resistor is connected to a colour
pin of the LED and the other end is on a row of its own.
Use one of the jumper wires to connect from the common cathode (long) pin of the LED to the GND
connection on the Arduino.
Use the other three jumper wires to connect from the ends of the resistors to Arduino digital pins D9,
D10, and D11.
Software
Open a new sketch in the Arduino IDE and type in the following code, or copy and paste it from our site:
int redLedPin = 9;
int greenLedPin = 10;
int blueLedPin = 11;
void setup() {
pinMode(redLedPin, OUTPUT);
pinMode(greenLedPin, OUTPUT);
pinMode(blueLedPin, OUTPUT);
}
void loop() {
delay(500);
}
However, we’re not hard-coding values to send to analogWrite(): instead we call the “random()” function
to generate a random number between 0 and 255, and send that instead. By randomly setting each of
the three colour elements individually and pausing for half a second each time, the RGB LED will flicker
to a different random colour twice per second. Funky!
Further experiments
You could use a light sensor as a simple proximity sensor, assuming the light readings get dimmer as
you move your hand closer to it and cast more of a shadow, and use the value read from it to smoothly
go from “cold” blue when your hand is far away to “hot” red when it’s close.
You can even connect multiple shift registers together in a row called a “daisy chain”, giving you the
ability to control a huge number of outputs while still using just three pins on the Arduino.
Parts Required
1 x “Eleven” Arduino-compatible microcontroller board
1 x 74HC595 shift-register IC
8 x LEDs (any colour)
8 x 470 Ohm resistors (yellow-violet-black-black-brown, or yellow-violet-brown-gold)
1 x Solderless breadboard
18 x Breadboard jumper wires
Before you begin assembly there is one very important thing to remember about most ICs: they can be
damaged by invisible static electricity that builds up on your skin, clothes, and workbench. Simply
touching the IC in the wrong way can kill it forever. Some ICs aren’t susceptible to static electricity
damage, but many are, so the safest approach is to assume that all ICs are static-sensitive unless
specified otherwise.
Don’t worry, it’s not as bad as it sounds. If you follow some simple precautions you’ll be fine.
Professional electronics labs often have special work surfaces and anti-static wrist straps, but for
experiments on your kitchen table you don’t need to go that far. The important thing is to minimise
contact with the pins of the IC once it has been removed from its protective foam. Grasp the IC by the
ends of the package, and don’t touch the pins against anything that may have a static charge.
Once you’ve removed the 74HC595 from its protective foam you’ll notice something annoying: the pins
aren’t straight! IC pins are made to spread out slightly so that they can be inserted into circuit boards with
a special tool that squeezes the pins together, and then when the tool is released the pins spring back
out a bit to hold it firmly in place prior to soldering. That means you’ll need to bend the pins inwards a
little before you can fit the IC into a breadboard.
To bend the pins, hold the IC package side-on against a hard surface such as a wooden table top and
push down. They’ll be quite difficult to bend but you don’t want to bend them too far, so the trick is
pushing hard enough but not too hard! Try to bend both sides in just enough that they are parallel to
each other.
Next, check the orientation of the IC and then push it into the breadboard so that the two rows of pins are
on either side of the centre line like in the diagram above, and the dimple or dot near one end is at the
left. This will allow you to easily connect jumper wires to any pin of the IC.
The 74HC595 shift register has a few different features that we’re not going to use, so the first thing to do
is connect various pins to either GND or 5V to make the chip operate in the right mode.
With the chip oriented as shown to the right, you’ll notice that the bottom
left pin (pin 8) connects to GND and the top right pin (pin 16) connects to
VCC, or 5V. This is a loose standard used by most ICs that have two rows
of pins. Use jumper wires to connect those pins to the GND and 5V rails
on the breadboard.
There are two more pins we need to set to specific levels: RESET and
OE, or Output Enable. Use another jumper wire to connect RESET (pin
10) to 5V, and OE (pin 13) to GND.
Now we’re ready to connect up all the LEDs to the outputs of the chip. The outputs are the “Q” pins
labelled A through H. Each output connects to the + (anode) side of an LED, which is the longer pin. The
- (cathode) side of each LED then connects to a 470 Ohm resistor (yellow-violet-black-black-brown, or
yellow-violet-brown-gold) which then connects to GND.
Once it’s all connected you’ll notice there is one remaining pin on the shift register that doesn’t have
anything connected to it: the “OUT” pin. That’s OK, it’s meant to remain unconnected for this project.
Software
Open a new sketch in the Arduino IDE and type in the following code, or copy and paste it from our site:
int dataPin = 2;
int latchPin = 3;
int clockPin = 4;
void setup() {
pinMode(dataPin, OUTPUT);
pinMode(latchPin, OUTPUT);
pinMode(clockPin, OUTPUT);
}
void loop() {
for (int currentValue = 0; currentValue < 256; currentValue++) {
// Disable the latch while we clock in data
digitalWrite(latchPin, LOW);
delay(200);
}
}
The brief version is that the 8 outputs of the shift register represent the individual “bit” values of a single
“byte” of data. A “byte” is a value that consists in binary form of 8 bits, with each bit having double the
place value of the previous bit when read from right to left.
Totally confused? OK, let’s break it down and work through it slowly.
The position of the 5 is important. In decimal, each time you move one position to the left you increase
the place value by 10x.
In just the same way, the binary number “10” (which is not the same as ten in decimal!) has a different
value to the binary number “1”, because the place-value of the digits increases as you move to the left.
With binary, each time you move one position to the left you increase the place value by just 2x.
That’s because decimal digits can have any of 10 values, from 0 to 9, so each place value increases by
10x as you move to the left. Binary digits, or bits, can have one of only two values: either 0 or 1, off or on,
low or high, so each place value only increases by 2x as you move to the left.
Have a look at this table, starting from the right hand side (the lowest value position) and see how the
place value increases for both decimal and binary as you move towards the left.
Position 8 7 6 5 4 3 2 1
Since a byte has eight bits, and each bit can have a maximum value of 1, the biggest possible number
that can fit inside one byte is the binary number “11111111”. This is equivalent to a decimal value of 255:
128 + 64 + 32 + 16 + 8 + 4 + 2 + 1. One byte can therefore be any number between 0 and 255 decimal.
Now stop for a second and look at that binary number again. That’s eight bits, all in a row, and every bit
can have the value of either 0 or 1. Now imagine that each one of those bits is wired up to one of the
eight outputs (A through H) of the shift register, so if that particular bit is set to 1 then the matching output
is on, and if that particular bit is set to 0 then the matching output is off.
Got it? Well, that’s exactly how a shift register works! The eight outputs are just physical representations
of the value of each of the eight bits inside a byte. And by sending a different value for the byte, we can
manipulate which outputs are turned on and which are turned off.
Remember that the bits are counted from the right in increasing place value (just like decimal numbers)
so to turn specific outputs on, you just work out the bits to represent those outputs.
Want to turn on outputs A, C, and E, and leave all the others off? Easy, just map it out like this,
remembering that digits to the left have higher place value so we’ll label it starting with “A” on the right
and working to the left like we would with a decimal number:
H G F E D C B A
0 0 0 1 0 1 0 1
You can use this same technique to figure out how to turn on any combination of outputs, and then map
it down to a single value in either decimal or binary to achieve that end result.
Now with those principles in mind, look at the sketch again and it may make a bit more sense.
First it sets up the connections to the shift register input, and to the CLOCK and LATCH pins.
Then, in the main loop, it uses a “for” loop to repeat over an incrementing number. The “for” loop starts
with a variable called “currentValue” which begins with a value of 0, and keeps repeating as long as the
value is less than 256. Each time it repeats, the value increases by 1, so it will go through with a value of
0, then a value of 1, then a value of 2, then a value of 3, and so on until the value reaches 255. On the
next cycle through the value will reach 256, which hits the limit that has been set and causes the
program to finish the “for” loop.
After the “for” loop has finished there are no more commands, so the main loop then just goes back to
the start, and begins all over again from scratch with a starting value of 0. That just repeats forever, so
what the sketch does is count from 0 to 255, then go back and do it again.
But the interesting bit is what the sketch does with that value each time it runs through the “for” loop.
Inside the “for” loop are three commands: first a command to change the state of the LATCH pin, then a
command to send the current value to the register using the DATA pin, then a command to change the
state of LATCH back again.
Those three commands, in that sequence, will cause the Arduino to take the value of the “currentValue”
variable and send it to the shift register to set the state of all the outputs.
Using the "shiftOut" command we can send a byte of data (value from 0 to 255) to the shift register,
setting the state of each output appropriately. For example, sending a value of "0" decimal will set all the
outputs LOW. Sending a value of "255" decimal will set all of the outputs HIGH. Sending a value of 1, 2,
4, 8, 16, 32, 64, or 128 decimal will set only output A, B, C, D, E, F, G, or H HIGH respectively.
Further Experiments
If you want to manipulate individual outputs from within your program without affecting the state of other
outputs, the most convenient method is to store the current value of the shift register as a 1-byte variable
and apply bitwise operators to it. The Arduino website has a good introduction to bitwise operators at
http://www.arduino.cc/playground/Code/BitMath.
Sometimes eight outputs aren’t enough! You can connect multiple shift registers together in a row (called
a “daisy chain”) so that you can pass values down the chain to each of the modules individually. That
way you can control 16, 24, 32, or even more separate outputs with the same three outputs from your
Arduino.
To daisy-chain multiple shift registers, begin with the simple example above. Then connect a second
shift register so that the VCC, GND, RESET, OE, CLOCK, and LATCH connections are all linked to the
same place as the first shift register. Finally, run a jumper wire from the OUT connection of the first shift
Once you have two shift registers daisy-chained together, setting their outputs is just as easy as
addressing a single register except that you have to send two bytes of data instead of one. The first byte
sent will pass down the chain to the final shift register, and the second byte sent will then go to the first
shift register: think of it as pushing messages down a pipe. The first one you push in will go towards the
end, and the second message will go in right behind it.
Using three or more shift registers follows the exact same principle: simply daisy-chain more together
linking the OUT connection of each into the DATA connection of the next in the chain, and send as many
bytes of data as you have shift registers in the chain.
Parts Required
1 x “Eleven” Arduino-compatible microcontroller board
1 x “SOUND” sound and piezo module
1 x Solderless breadboard
2 x Breadboard jumper wires
Hardware assembly
Connecting your module is very easy, because it is not polarised so it can be connected either way
around. Use one of the jumper wires to connect a pin of the module to the GND on the Arduino, and the
second jumper wire to connect the other module pin to Arduino digital pin D8.
int piezo = 8;
int duration = 250;
int notes[] =
{261, 293, 329, 349, 392, 440, 493, 523, 587, 659, 698, 783, 880};
// frequencies for musical notes - from middle C, D, E, F, G, A, B, C, D, E, F, G, A
void setup()
{
pinMode(piezo, OUTPUT);
}
void loop()
{
for (int i = 0; i < 13; i++)
{
tone(piezo, notes[i], duration);
delay(duration);
}
for (int i = 11; i > 0; --i)
{
tone(piezo, notes[i], duration);
delay(duration);
}
}
In the sketch we have defined the pin for the module as 8, and also filled the array “notes” with
frequencies for the main musical notes from middle C. You can find out more note frequencies from the
website http://bit.ly/notefrequency.
After connecting the hardware and uploading the sketch, the tones will be played repeatedly in an
ascending then descending order.
Further experiments
Just about any project can benefit from sound output, to be used as a warning, an alarm tone, to play a
song for a game, or as a pleasant notifier.
Parts required
1 x “Eleven” Arduino-compatible microcontroller board
1 x “SOUND” sound and piezo module
1 x Solderless breadboard
2 x Breadboard jumper wires
Software
Open a new sketch in the Arduino IDE and type in the following code, or copy and paste it from our site:
int knock = 0;
void setup()
{
Serial.begin(38400);
}
void loop()
{
knock = analogRead(0);
Serial.println(knock);
}
The numbers displayed are a representation of the level of vibration or shock felt by the piezo. If you tap
the module using various strengths, you can see the numbers increase then decrease. The example
here shows the effect of tapping the module with a finger.
Further experiments
The ability to detect vibrations and knocks opens up many possibilities, including alarm and movement
sensors, making your own “knock lock” that activates after receiving a knock of a certain strength or
pattern, or just as another form of input.
Using the values returned from the sketch, you can now use your Arduino and the module to make
decisions based on the strength of knock received by the module.
We demonstrate this using the following sketch. When a knock is received, the onboard LED will light for
half a second. In the sketch we consider a “knock” to occur when the value from the analogue input is
greater than 10.
Open a new sketch in the Arduino IDE and type in the following code, or copy and paste it from our site:
int knock = 0;
void loop()
{
knock = analogRead(0);
if (knock > 10)
{
digitalWrite(13, HIGH);
delay(500);
digitalWrite(13, LOW);
}
}
Parts required
1 x “Eleven” Arduino-compatible microcontroller board
1 x “SOUND” sound and piezo module
1 x “LIGHT” light sensor module
1 x Solderless breadboard
5 x Breadboard jumper wires
Software
Open a new sketch in the Arduino IDE and type in the following code, or copy and paste it from our site:
int lightLevel;
int piezo = 8;
int duration = 300;
void setup()
{
pinMode(piezo, OUTPUT);
}
void loop()
{
lightLevel = analogRead(A0);
tone(piezo, lightLevel, duration);
delay(duration);
}
After assembling the hardware and uploading the sketch, move your hand over the light sensor. You
should be able to hear the frequency or pitch of the sound change with the amount of light falling onto
the sensor.
Further experiments
As the light levels measured by the sensor are converted to numbers your Arduino can work with, the
possibilities are almost endless. Create a nightlight, light-activated burglar alarm, or perhaps a “cricket”
that only squeaks when the lights are off.
Sidecutters
Sidecutters are the number one tool of any electronics
hobbyist: you can use them to cut wire, strip insulation, trim
component leads, and many other uses.
Multimeter
A multimeter is a general purpose test instrument for measuring all
sorts of electrical properties, including the three fundamentals:
voltage, current, and resistance. Many advanced multimeters can
also measure capacitance, diode voltage drop, transistor gain, and
other properties, but usually the critical feature is simply measuring
voltage. All those other features are nice to have but even a $10
bargain-bin special from your local electronics store will be better
than nothing when you’re just getting started.
Multimeters have two leads: black (negative) and red (positive) that
can be connected to your circuit in different ways depending on what
you are measuring. The most common way to use a multimeter for
hobby projects is to connect the negative test probe to a “ground” (0V) point somewhere on the circuit,
and then use the positive probe to measure the voltage at other locations in the circuit.
Freetronics Blog
Regular stories about amazing things people have built using Arduino. Great for a dose of inspiration:
www.freetronics.com/blog/news
Freetronics Forums
Discuss your projects or ask for help on the Freetronics Forum. It’s filled with helpful hackers and
Freetronics staff, so no matter what your electronics problem is you’re likely to find someone here to help
figure it out:
forum.freetronics.com
In the example, the 5-band resistor has the first band brown (1), second band black (0), third band black
(0), 4th band is red (x100 multiplier), so the resistor value is 10,000 Ohms: usually written as 10k.
The easiest way to understand the multiplier is to look at what number that colour represents (red is 2)
and just add that many zeros after the other digits.