All Exp - of Arduino
All Exp - of Arduino
Scientific Research
الجامعةالمستنصرية
Al-Mustansiriyah University
Faculty of Engineering كلية الهندسة
Computer Engineering Department قسم هندسة الحاسوب
Microcomputer Lab.
Prepared By
Prof. Dr. Dhafer Rafaa Zaghar
Assist. Lec. Ayam Mohsen Abbass
2016
2017
Al-Mustansiriyah University Third Class
Faculty of engineering
Computer engineering Department Microcomputer Lab.
1. Object: The objective of this experiment is to learn the main principles for using
arduino.
2. Theory:
What is Arduino?
Arduino is an open-source prototyping platform based on easy-to-use hardware
and software. Arduino boards are able to read inputs - light on a sensor, a finger on
a buttonand turn it into an output - activating a motor, turning on an LED,
publishing something online.
Why Arduino?
Arduino has been used in thousands of different projects and applications. The
Arduino software is easy-to-use for beginners, yet flexible enough for advanced
users. It runs on Mac, Windows, and Linux. Teachers and students use it to build
low cost scientific instruments, to prove chemistry and physics principles, or to get
started with programming and robotics.
Arduino also simplifies the process of working with microcontrollers, but it offers
some advantage for teachers, students, and interested amateurs over other systems:
1. Inexpensive: Arduino boards are relatively inexpensive compared to other
microcontroller platforms.
2. Cross-platform: TheArduino Software (IDE) runs on Windows, Macintosh
OSX, and Linux operating systems. Most microcontroller systems are limited
to Windows.
1
Al-Mustansiriyah University Third Class
Faculty of engineering
Computer engineering Department Microcomputer Lab.
2
Al-Mustansiriyah University Third Class
Faculty of engineering
Computer engineering Department Microcomputer Lab.
The magic behind this family is the fact we can use the same
IntegratedDevelopment Environment (IDE) on our computers with any of those
boards. Fig.1shows some notable Arduino family members.
3
Al-Mustansiriyah University Third Class
Faculty of engineering
Computer engineering Department Microcomputer Lab.
In some cases. Some projects don’t necessarily need a computer, and itwould be
overkill to use a whole computer just to power the Arduino.Also, the USB port
only delivers 5 volts, and sometimes you need more.In these situations, the best
solution usually is an AC adapter.
Figure 3. AC adapter
4
Al-Mustansiriyah University Third Class
Faculty of engineering
Computer engineering Department Microcomputer Lab.
The IDE provides a graphical interface in which you can write your code, debug it,
compile it, and upload it, basically.
Open:Presents a menu of all the sketches in your sketchbook. Clicking one will
open it within the current window overwriting its content.
5
Al-Mustansiriyah University Third Class
Faculty of engineering
Computer engineering Department Microcomputer Lab.
6
Al-Mustansiriyah University Third Class
Faculty of engineering
Computer engineering Department Microcomputer Lab.
PageSetup
It shows the Page Setup window for printing.
Print
Sends the current sketch to the printer according to the settings defined in Page
Setup.
Preferences
Opens the Preferences window where some settings of the IDE may be
customized, as the language of the IDE interface.
Quit
Closes all IDE windows. The same sketches open when Quit was chosen will be
automatically reopened the next time you start the IDE.
Edit
Undo/Redo
Goes back of one or more steps you did while editing; when you go back, you
may go forward with Redo.
Cut
Removes the selected text from the editor and places it into the clipboard.
Copy
Duplicates the selected text in the editor and places it into the clipboard.
Copy forForum
Copies the code of your sketch to the clipboard in a form suitable for posting to
the forum, complete with syntax coloring.
Copy asHTML
Copies the code of your sketch to the clipboard as HTML, suitable for
embedding in web pages.
7
Al-Mustansiriyah University Third Class
Faculty of engineering
Computer engineering Department Microcomputer Lab.
Paste
Puts the contents of the clipboard at the cursor position, in the editor.
SelectAll
Selects and highlights the whole content of the editor.
Comment/Uncomment
Puts or removes the // comment marker at the beginning of each selected line.
Increase/DecreaseIndent
Adds or subtracts a space at the beginning of each selected line, moving the text
one space on the right or eliminating a space at the beginning.
Find
Opens the Find and Replace window where you can specify text to search inside
the current sketch according to several options.
FindNext
Highlights the next occurrence - if any - of the string specified as the search item
in the Find window, relative to the cursor position.
Find Previous
Highlights the previous occurrence - if any - of the string specified as the search
item in the Find window relative to the cursor position.
Sketch
Verify/Compile
Checks your sketch for errors compiling it; it will report memory usage for code
and variables in the console area.
8
Al-Mustansiriyah University Third Class
Faculty of engineering
Computer engineering Department Microcomputer Lab.
Upload
Compiles and loads the binary file onto the configured board through the
configured Port.
Upload Using Programmer
This will overwrite the bootloader on the board; you will need to use Tools >
Burn Boot loader to restore it and be able to Upload to USB serial port again.
However, it allows you to use the full capacity of the Flash memory for your
sketch. Please note that this command will NOT burn the fuses. To do so a Tools
-> Burn Boot loader command must be executed.
Export Compiled Binary
Saves a .hex file that may be kept as archive or sent to the board using other
tools.
Show Sketch Folder
Opens the current sketch folder.
Include Library
Adds a library to your sketch by inserting #include statements at the start of your
code.
Add File...
Adds a source file to the sketch (it will be copied from its current location). The
new file appears in a new tab in the sketch window. Files can be removed from
the sketch using the tab menu accessible clicking on the small triangle icon
below the serial monitor one on the right side of the toolbar.
9
Al-Mustansiriyah University Third Class
Faculty of engineering
Computer engineering Department Microcomputer Lab.
Tools
Auto Format
This formats your code nicely: i.e. indents it so that opening and closing curly
braces line up, and that the statements inside curly braces are indented more.
Archive Sketch
Archives a copy of the current sketch in .zip format. The archive is placed in the
same directory as the sketch.
Fix Encoding & Reload
Fixes possible discrepancies between the editor char map encoding and other
operating systems char maps.
Serial Monitor
Opens the serial monitor window and initiates the exchange of data with any
connected board on the currently selected Port. This usually resets the board, if the
board supports Reset over serial port opening.
Board
Select the board that you're using.
Port
This menu contains all the serial devices (real or virtual) on your machine. It
should automatically refresh every time you open the top-level tools menu.
Programmer
For selecting a hardware programmer when programming a board or chip and
not using the onboard USB-serial connection. Normally you won't need this, but
if you're burning a boot loader to a new microcontroller, you will use this.
10
Al-Mustansiriyah University Third Class
Faculty of engineering
Computer engineering Department Microcomputer Lab.
3. Procedure:
1. Installing Arduino (Windows): The Arduino software that you will use to
program your Arduino is available for Windows, Mac and Linux. The installation
process is different for all three platforms and unfortunately there is a certain
amount of manual work to install the software.
Get the latest version from the download page. You can choose between the
Installer (.exe) and the Zip packages. We suggest you use the first one that installs
directly everything you need to use the Arduino Software (IDE), including the
drivers. With the Zip package you need to install the drivers manually. The Zip file
is also useful if you want to create a portable.
When the download finishes, proceed with the installation and please allow the
driver installation process when you get a warning from the operating system.
11
Al-Mustansiriyah University Third Class
Faculty of engineering
Computer engineering Department Microcomputer Lab.
Choose the installation directory (we suggest to keep the default one)
The process will extract and install all the required files to execute properly the
Arduino Software (IDE).
12
Al-Mustansiriyah University Third Class
Faculty of engineering
Computer engineering Department Microcomputer Lab.
Before we launch the Arduino software, you are going to install the USB drivers.
Plug one end of your USB cable into the Arduino and the other into a USB socket
on your computer. The power light on the LED will light up and you may get a
'Found New Hardware' message from Windows. Ignore this message and cancel
any attempts that Windows makes to try and install drivers automatically for you.
13
Al-Mustansiriyah University Third Class
Faculty of engineering
Computer engineering Department Microcomputer Lab.
Also on the 'Tools' menu, you will find the 'Serial Port' option. Select this option.
14
Al-Mustansiriyah University Third Class
Faculty of engineering
Computer engineering Department Microcomputer Lab.
4. Discussion:
1. Is all types of arduino are suitable for any application? Explain this?
2. Reinstall the arduino IDE and use another serial port in your computer?
15
Al-Mustansiriyah University Third Class
Faculty of engineering
Computer engineering Department Microcomputer Lab.
Learn how program Arduino to make the Arduino's built-in LED blink.
2. Requirements:
Arduino/Uno.
Usb /Arduino cable.
3. Theory: The Arduino has rows of connectors along both sides that are used to
connect to electronic devices and plug-in 'shields' that allow the Arduino to do
more. However, the Arduino also has a single LED that you can control from your
sketches. This LED is built onto the Arduino board and is often referred to as the
'L' LED as this is how it is labeled on the board. The position of this LED is circled
in red on the Fig.1of the Arduino Uno below.
1
Al-Mustansiriyah University Third Class
Faculty of engineering
Computer engineering Department Microcomputer Lab.
4. Procedure:
Loading the 'Blink' Example:
You may find that your Arduino board's 'L' LED already blinks when you connect
it to a USB plug. This is because Arduino boards are generally shipped with the
'Blink' sketch preinstalled. In this experiment, we will reprogram the Arduino with
our own Blink sketch and then change the rate at which it blinks.
In experiement1, you setup your Arduino IDE and made sure that you could find
the right serial port for it to connect to your Arduino board. The Arduino IDE
includes a large collection of example sketches that you can load up and use. This
includes an example sketch for making the 'L' LED blink.
Load the 'Blink' sketch that you will find in the IDE's menu system under File →
Examples → 01.Basics.
2
Al-Mustansiriyah University Third Class
Faculty of engineering
Computer engineering Department Microcomputer Lab.
When the sketch window opens, enlarge it so that you can see the whole of the
sketch in the window.
3
Al-Mustansiriyah University Third Class
Faculty of engineering
Computer engineering Department Microcomputer Lab.
You have saved your copy of 'Blink' in your sketchbook. This means that if you
ever want to find it again, you can just open it using the File → Sketchbook menu
option.
4
Al-Mustansiriyah University Third Class
Faculty of engineering
Computer engineering Department Microcomputer Lab.
Click on the 'Upload' button. The second button from the left on the toolbar.
If you watch the status area of the IDE, you will see a progress bar and a series of
messages. At first it will say 'Compiling Sketch..'. This converts the sketch into a
format suitable for uploading to the board.
5
Al-Mustansiriyah University Third Class
Faculty of engineering
Computer engineering Department Microcomputer Lab.
Next, the status will change to 'Uploading'. At this point, the LEDs on the Arduino
should start to flicker as the sketch is transferred.
The other message tells us that the sketch is using 1,084 bytes of the 32,256 bytes
available. After the 'Compiling Sketch...’ stage you could get the following error
message:
The clue is at the top here, it probably means that your board is not connected at
all, or the drivers have not been installed (if necessary) or that the wrong serial port
6
Al-Mustansiriyah University Third Class
Faculty of engineering
Computer engineering Department Microcomputer Lab.
is selected. If you get this, go back to exp.1 and check your installation. Once the
upload has completed, the board should restart and start blinking.
How 'Blink' Works: Here is the code for the Blink sketch.
The first thing to note is that quite a lot of this sketch is what is called 'comments'.
Comments are not actual program instructions, they are just comments about how
the program works. They are there for out benefit, so that there is some explanation
to accompany the sketch. Everything between /* and */ at the top of the sketch is a
block comment, that explains what the sketch is for. There are also single line
comments that start with // and everything up until the end of the line counts as
being a comment. The first actual line of code is:
7
Al-Mustansiriyah University Third Class
Faculty of engineering
Computer engineering Department Microcomputer Lab.
As the comment above explains, this is giving a name to the pin that the LED is
attached to. This is 13 on most Arduinos, including the Uno.
Next, we have the 'setup' function. Again, as the comment says, this is run when
the reset button is pressed. It is also run whenever the board resets for any reason,
such as power first being applied to it, or after a sketch has been uploaded.
Every Arduino sketch must have a 'setup' function, and the part of it where you
might want to add instructions of your own is between the { and the }. In this case,
there is just one command there, which, as the comment states tells the Arduino
board that we are going to use the LED pin as an output. It is also mandatory for a
sketch to have a 'loop' function. Unlike the 'setup' function that only runs once,
after a reset, the 'loop' function will, after it has finished running its commands,
immediately start again.
Inside the loop function, the commands first of all turn the LED pin on (HIGH),
then 'delay' for 1000 milliseconds (1 second), then turn the LED pin off and pause
for another second.
8
Al-Mustansiriyah University Third Class
Faculty of engineering
Computer engineering Department Microcomputer Lab.
5. Discussion:
1. Make your LED blink going to faster. As you might have guessed, the key to
this lies in changing the parameter in () for the 'delay' command.
This delay period is in milliseconds, and so if you want the LED to blink twice as
fast, change the value of 1000 to 500. This would then pause for half a second each
delay rather than a whole second. Upload the sketch again and you should see the
LED start to flash more quickly?
2. Try changing the delay again to make the blinking even faster using 100 as the
parameter to 'delay'?
9
Al-Mustansiriyah University Third Class
Faculty of engineering
Computer engineering Department Microcomputer Lab.
Learn how to change the brightness of an LED by using different values of resistor.
2. Requirements:
1
Al-Mustansiriyah University Third Class
Faculty of engineering
Computer engineering Department Microcomputer Lab.
3. Theory:
LEDs make great indicator lights. They use very little electricity and they pretty
much last forever. In this Exp. We will use perhaps the most common of all
LEDs a 5mm red LED. 5Mm refers to the diameter of the LED and as well as
5mm, other common sizes are 3mm and the large fun 10mm LEDs.
We cannot directly connect an LED to a battery or voltage source. Firstly,
because the LED has a positive and a negative lead and will not light if they are
the wrong way around and secondly, an LED must be used with a resistor to
limit or 'choke' the amount of current flowing through the LED - otherwise the
LED could burn out!
If we do not use a resistor with an LED, then it may well be destroyed almost
immediately, as too much current will flow through the LED, heating it and
destroying the 'junction' where the light is produced.
2
Al-Mustansiriyah University Third Class
Faculty of engineering
Computer engineering Department Microcomputer Lab.
There are two ways to tell which is the positive lead of the LED and which the
negative. Firstly, the positive lead is longer. Secondly, where the negative lead
enters the body of the LED, there is a flat edge to the case of the LED.
If we happen to have an LED that has a flat side next to the longer lead, we
should assume that the longer lead is positive.
Resistors: As the name suggests, resistors resist the flow of electricity and the
higher the value of the resistor, the more it resists and the less electrical current
will flow through it. We are going to use this to control how much electricity
flows through the LED and therefore how brightly it shines.
But first, a bit more about resistors. The unit of resistance is called the Ohm,
which is usually shortened to Ω the Greek letter Omega. Because an Ohm is a
low value of resistance (it doesn't resist much at all), we also give the values of
resistors in kΩ (1000 Ω) and MΩ (1000, 000 Ω). These are called kilo-ohms
and mega-ohms.
In this Exp. we are going to use four different values of resistor, 270Ω, 470Ω,
2.2kΩ and 10kΩ. These resistors all look the same, except that they have
different colored stripes on them. These stripes tell us the value of the resistor.
The resistor color code works like this, for resistors like this with three colored
stripes and then a gold stripe at one end. Each color has a number, as follows:
Black 0
Brown 1
Red 2
Orange 3
3
Al-Mustansiriyah University Third Class
Faculty of engineering
Computer engineering Department Microcomputer Lab.
Yellow 4
Green 5
Blue 6
Purple 7
Gray 8
White 9
The first two striped are the first two digits of the value, so red, purple means 2,
7. The next stripe is the number of zeros that need to come after the first two
digits, so if the third stripe is brown, as it is in the photograph above, then there
will be one zero and so the resistor is 270Ω. A resistor with stripes brown, black,
orange is 10 and three zeros so 10,000 Ω in other words 10 kΩ. Unlike LEDs,
resistors do not have a positive and negative lead. They can be connected either
way around.
4. Procedure:
Breadboard Layout:
Connect up your strip board as shown below, using the 270Ω resistor.
4
Al-Mustansiriyah University Third Class
Faculty of engineering
Computer engineering Department Microcomputer Lab.
The Arduino is a convenient source of 5 Volts that we will use to provide power
to the LED and resistor. We do not need to do anything with your Arduino,
except plug it into a USB cable.
With the 270 Ω resistor in place, the LED should be quite bright. If you swap out
the 270 Ω resistor for the 470 Ω resistor, then the LED will appear a little dimmer.
With the 2.2kΩ resistor in place the LED should be quite faint. Finally, with the 10
kΩ resistor in place, the LED will be just about visible. Pull the red jumper lead
out of the breadboard and touch it into the hole and remove it, so that it acts like a
switch. We should just be able to notice the difference. Turning out the lights
might help even more.
5
Al-Mustansiriyah University Third Class
Faculty of engineering
Computer engineering Department Microcomputer Lab.
Note, we will probably want to put the 270Ω resistor back in place. So, it does not
matter which side of the LED we put the resistor, as long as it is there somewhere.
6
Al-Mustansiriyah University Third Class
Faculty of engineering
Computer engineering Department Microcomputer Lab.
Now load the 'Blink' example sketch from Exp.1. We will notice that both the
built-in 'L' LED and the external LED should now blink. Let’s try using a different
pin of the Arduino – say D7. Move the red jumper lead from pin D13 to pin D7
and modify the following line near the top of the sketch:
5. Discussion:
Let’s try using a different pin of the Arduino – say D7. Move the red jumper lead
from pin D13 to pin D7 and modify the following line near the top of the sketch:
So that it reads:
7
Al-Mustansiriyah University Third Class
Faculty of engineering
Computer engineering Department Microcomputer Lab.
Upload the modified sketch to our Arduino board and the LED should still be
blinking, but this time using pin D7?
8
Al-Mustansiriyah University Third Class
Faculty of engineering
Computer engineering Department Microcomputer Lab.
(RGB LEDs)
1. Object:
Learn how to use a RGB (Red Green Blue) LED with an Arduino. We will use the
analog Write function of Arduino to control the color of the LED.
2. Requirements:
1
Al-Mustansiriyah University Third Class
Faculty of engineering
Computer engineering Department Microcomputer Lab.
3. Theory:
At first glance, RGB (Red, Green, and Blue) LEDs look just like regular LEDs,
however, inside the usual LED package, there are actually three LEDs, one red,
one green and yes, one blue. By controlling the brightness of each of the individual
LEDs you can mix pretty much any color you want. We mix colors just like you
would mix audio with a 'mixing board' or paint on a palette – by adjusting the
brightness of each of the three LEDs. The hard way to do this would be to use
different value resistors (or variable resistors) as we played with in Exp. 2. That's a
lot of work! Fortunately for us, the Arduino has an analog Write function that you
can use with pins marked with a ~ to output a variable amount of power to the
appropriate LEDs.
2
Al-Mustansiriyah University Third Class
Faculty of engineering
Computer engineering Department Microcomputer Lab.
PWM:
Pulse Width Modulation (or PWM) is a technique for controlling power. We also
use it here to control the brightness of each of the LEDs.
The diagram below shows the signal from one of the PWM pins on the Arduino.
Roughly every 1/500 of a second, the PWM output will produce a pulse. The
length of this pulse is controlled by the 'analogWrite' function. So 'analogWrite(0)'
will not produce any pulse at all and 'analogWrite(255)' will produce a pulse that
lasts all the way until the next pulse is due, so that the output is actually on all the
time.
If we specify a value in the analogWrite that is somewhere in between 0 and 255
then we will produce a pulse. If the output pulse is only high for 5% of the time
then whatever we are driving will only receive 5% of full power.
If however the output is at 5V for 90% of the time then the load will get 90% of the
power delivered to it. We cannot see the LEDs turning on and off at that speed, so
to us, it just looks like the brightness is changing.
3
Al-Mustansiriyah University Third Class
Faculty of engineering
Computer engineering Department Microcomputer Lab.
4. Procedure:
Breadboard Layout: The RGB LED has four leads. There is one lead going to
the positive connection of each of the single LEDs within the package and a
single lead that is connected to all three negative sides of the LEDs.
The common negative connection of the LED package is the second pin from
the flat side of the LED package. It is also the longest of the four leads. This
lead will be connected to ground. Each LED inside the package requires its own
270Ω resistor to prevent too much current flowing through it. The three positive
leads of the LEDs (one red, one green and one blue) are connected to Arduino
output pins using these resistors.
If you are using a common ANODE LED instead of common CATHODE,
connect the long pin to +5 instead off ground.
4
Al-Mustansiriyah University Third Class
Faculty of engineering
Computer engineering Department Microcomputer Lab.
Colors: The reason that you can mix any color you like by varying the quantities
of red, green and blue light is that your eye has three types of light receptor in it
(red, green and blue). Your eye and brain process the amounts of red, green and
blue and convert it into a color of the spectrum. In a way, by using the three LEDs
we are playing a trick on the eye. This same idea is used in TVs, where the LCD
has red, green and blue color dots next to each other making up each pixel.
5
Al-Mustansiriyah University Third Class
Faculty of engineering
Computer engineering Department Microcomputer Lab.
If we set the brightness of all three LEDs to be the same, then the overall color of
the light will be white. If we turn off the blue LED, so that just the red and green
LEDs are the same brightness, then the light will appear yellow. We can control
the brightness of each of the red, green and blue parts of the LED separately,
making it possible to mix any color we like. Black is not so much a color as an
absense of light. So the closest we can come to black with our LED is to turn off
all three colors.
Arduino Sketch:
The following test sketch will cycle through the colors red, green, blue, yellow,
purple, and aqua. These colors being some of the standard Internet colors.
6
Al-Mustansiriyah University Third Class
Faculty of engineering
Computer engineering Department Microcomputer Lab.
Try the sketch out and then we will dissect it in some detail......
The sketch starts by specifying which pins are going to be used for each of the
colors:
7
Al-Mustansiriyah University Third Class
Faculty of engineering
Computer engineering Department Microcomputer Lab.
The next step is to write the 'setup' function. As we have learnt in earlier lessons,
the setup function runs just once after the Arduino has reset. In this case, all it has
to do is define the three pins we are using as being outputs.
Before we take a look at the 'loop' function, let’s look at the last function in the
sketch.
This function takes three arguments, one for the brightness of the red, green and
blue LEDs. In each case the number will be in the range 0 to 255, where 0 means
off and 255 means maximum brightness. The function then calls 'analog Write' to
set the brightness of each LED. If we look at the 'loop' function we can see that we
are setting the amount of red, green and blue light that we want to display and then
pausing for a second before moving on to the next color.
8
Al-Mustansiriyah University Third Class
Faculty of engineering
Computer engineering Department Microcomputer Lab.
Try adding a few colors of your own to the sketch and watch the effect on our
LED.
If we are using a Common Anode RGB LED, then we need to change the analog
write values so that the color is subtracted from 255,, Uncomment the line #define
COMMON__ANODE in the sketch!!
Using Internet Colors:
If we have done any Internet programming, we will probably be aware that colors
are often represented as a 'hex' number. For example the color red has the number
#FF0000. We can find the numbers associated with a particular color using tables
like these:
http://www.devguru.com/features/colors (http://adafru.it/aZ6)
The six digits of the number are actually three pairs of numbers; the first pair being
the red component of the color, the next two digits the green part and the final pair
the blue part. Red is #FF0000, because its maximum red (FF is 255 in hex) and it
has no green or blue part. It would be pretty useful to be able to dial up one of
these color numbers so that it is displayed on the RGB LED. Let's try and make the
color indigo (#4B0082).
9
Al-Mustansiriyah University Third Class
Faculty of engineering
Computer engineering Department Microcomputer Lab.
The red, green and blue parts of indigo are (in hex) 4B, 00 and 82 respectively.
We can plug those into the 'setColor' function like this:
We have used hex numbers for the three parts of the color by putting '0x' in front
of them. Try adding a few colors of our own to the 'loop' function. Don't forget to
add a delay after each one.
5. Discussion:
1. Try changing the delays to speed up or slow down the color changing?
2. There are lots of things we can do with RGB LEDs. Check out some of the
projects on the Internet using RGB LEDs and we will find multi-color persistence
of vision devices, as well as all sorts of lighting effects, mention to these
examples?
10
Al-Mustansiriyah University Third Class
Faculty of engineering
Computer engineering Department Microcomputer Lab.
Learn how to use eight large red LEDs with an Arduino without needing to give up
8 output pins.
2. Requirements:
Qty
1
Al-Mustansiriyah University Third Class
Faculty of engineering
Computer engineering Department Microcomputer Lab.
Half-size Breadboard 1
2
Al-Mustansiriyah University Third Class
Faculty of engineering
Computer engineering Department Microcomputer Lab.
Arduino Uno R3 1
3
Al-Mustansiriyah University Third Class
Faculty of engineering
Computer engineering Department Microcomputer Lab.
3. Theory:
The 74HC595 Shift Register:
Before we go through the code, let's have a quick look at what the chip is doing, so
that we can understand what the code has to do. The chip is of a type called a shift
register.
The shift register holds what can be thought of as eight memory locations, each of
which can be a 1 or a 0.
To set each of these values on or off, we feed in the data using the 'Data' and
'Clock' pins of the chip. The clock pin needs to receive eight pulses, at the time of
4
Al-Mustansiriyah University Third Class
Faculty of engineering
Computer engineering Department Microcomputer Lab.
each pulse, if the data pin is high, then a 1 gets pushed into the shift register,
otherwise a 0. When all eight pulses have been received, then enabling the 'Latch'
pin copies those eight values to the latch register. This is necessary, otherwise the
wrong LEDs would flicker as the data was being loaded into the shift register.
The chip also has an OE (output enable) pin, this is used to enable or disable the
outputs all at once. You could attach this to a PWM capable Arduino pin and use
'analogWrite' to control the brightness of the LEDs. This pin is active low, so we
tie it to GND.
4. Procedure: As we have eight LEDs and eight resistors to connect up, there are
actually quite a few connections to be made.
5
Al-Mustansiriyah University Third Class
Faculty of engineering
Computer engineering Department Microcomputer Lab.
It is probably easiest to put the 74HC595 chip in first, as pretty much everything
else connects to it. Put it so that the little U-shaped notch is towards the top of the
breadboard.
Pin 1 of the chip is to the left of this notch.
Digital 4 from the arduino goes to pin #14 of the shift register
Digital 5 from the arduino goes to pin #12 of the shift register
Digital 6 from the arduino goes to pin #11 of the shift register
All but one of the outputs from the '595 are on the left hand side of the chip, hence,
for ease of connection that is where the LEDs are too.
After the chip, put the resistors in place. You need to be careful that none of the
leads of the resistors are touching each other. You should check this again, before
you connect the power to your Arduino. If you find it difficult to arrange the
resistors without their leads touching, then it helps to shorten the leads so that they
are lying closer to the surface of the breadboard. Next, place the LEDs on the
breadboard. The longer positive LED leads must all be towards the chip,
whichever side of the breadboard they are on. It now just remains to attach the
jumper leads as shown above. Do not forget the one that goes from pin 8 of the IC
to the GND column of the breadboard. Load up the sketch listed a bit later and try
it out. Each LED should light in turn until all the LEDs are on, and then they all go
off and the cycle repeats.
6
Al-Mustansiriyah University Third Class
Faculty of engineering
Computer engineering Department Microcomputer Lab.
Arduino Code:
Arduino includes a special function called 'shiftOut' that is designed specifically
for sending data to shift registers.
Here is the full sketch, the discussion of how it works follows on from it.
The first thing we do is define the three pins we are going to use. These are the
Arduino digital outputs that will be connected to the latch, clock and data pins of
the 74HC595.
7
Al-Mustansiriyah University Third Class
Faculty of engineering
Computer engineering Department Microcomputer Lab.
Next, a variable called 'leds' is defined. This will be used to hold the pattern of
which LEDs are currently turned on or off. Data of type 'byte' represents numbers
using eight bits. Each bit can be either on or off, so this is perfect for keeping track
of which of our eight LEDs are on or off.
The 'setup' function just sets the three pins we are using to be digital outputs.
The 'loop' function initially turns all the LEDs off, by giving the variable 'leds' the
value 0. It then calls 'updateShiftRegister' that will send the 'leds' pattern to the
shift register so that all the LEDs turn off. We will deal with how
'updateShiftRegister' works later. The loop function pauses for half a second and
then begins to count from 0 to 7 using the 'for' loop and the variable 'i'. Each time,
it uses the Arduino function 'bitSet' to set the bit that controls that LED in the
variable 'leds'. It then also calls 'updateShiftRegister' so that the leds update to
reflect what is in the variable 'leds'. There is then a half second delay before 'i' is
incremented and the next LED is lit.
8
Al-Mustansiriyah University Third Class
Faculty of engineering
Computer engineering Department Microcomputer Lab.
The function 'update Shift Register', first of all sets the latch Pin to low, then calls
the Arduino function 'shift Out' before putting the 'latch Pin' high again. This takes
four parameters, the first two are the pins to use for Data and Clock respectively.
The third parameter specifies which end of the data you want to start at. We are
going to start with the right most bit, which is referred to as the 'Least Significant
Bit' (LSB). The last parameter is the actual data to be shifted into the shift register,
which in this case is 'leds'.
If you wanted to turn one of the LEDs off rather than on, you would call a similar
Arduino function (bit Clear) on the 'leds' variable. This will set that bit of 'leds' to
be 0 and you would then just need to follow it with a call to 'update Shift Register'
to update the actual LEDs.
Brightness Control:
One pin of the 74HC595 that I have not mentioned is a pin called 'Output Enable'.
This is pin 13 and on the breadboard, it is permanently connected to Ground. This
pin acts as a switch, that can enable or disable the outputs - the only thing to watch
for is it is 'active low' (connect to ground to enable). So, if it is connected to 5V, all
the outputs go off. Whereas if it is connected to Ground, those outputs that are
supposed to be on are on and those that should be off are off. We can use this pin
along with the 'analogWrite' function that we used back in exp. 3, to control the
brightness of the LEDs using PWM (also see Exp.4).
9
Al-Mustansiriyah University Third Class
Faculty of engineering
Computer engineering Department Microcomputer Lab.
To do this, all you need to do, is to change the connection to pin 13 of the
74HC595 so that instead of connecting it to Ground, you connect it to pin 3 of the
Arduino. The sketch below, will once all the LEDs have been lit gradually fade
them back to off.
10
Al-Mustansiriyah University Third Class
Faculty of engineering
Computer engineering Department Microcomputer Lab.
5. Discussion:
Make an electronic dice. Arrange 6 of the LEDs as two columns of three LEDs
with one LED in the middle. Hint – take at a look at the Arduino function called
'random'?
11
Al-Mustansiriyah University Third Class
Faculty of engineering
Computer engineering Department Microcomputer Lab.
12
Al-Mustansiriyah University Third Class
Faculty of engineering
Computer engineering Department Microcomputer Lab.
1. Object:
Learn how to send and receive text messages, handy for debugging and also
controlling the Arduino from a keyboard.
2. Requirements:
In this Exp. We will use exactly the same parts and a similar breadboard layout as
Exp. 5.
3. Theory:
The Serial Monitor:
In this Exp. adding the facility to control the LEDs from your computer using the
Arduino Serial Monitor. The serial monitor is the 'tether' between the computer and
your Arduino.
4. Procedure: Lets you send and receive text messages Upload the following
sketch to your Arduino. Later on, we will see exactly how it works.
1
Al-Mustansiriyah University Third Class
Faculty of engineering
Computer engineering Department Microcomputer Lab.
2
Al-Mustansiriyah University Third Class
Faculty of engineering
Computer engineering Department Microcomputer Lab.
After you have uploaded this sketch onto your Arduino, click on the right-most
button on the toolbar in the Arduino IDE. The button is circled below.
This window is called the Serial Monitor and it is part of the Arduino IDE
software. Its job is to allow you to both send messages from your computer to an
3
Al-Mustansiriyah University Third Class
Faculty of engineering
Computer engineering Department Microcomputer Lab.
Arduino board (over USB) and also to receive messages from the Arduino. The
message “Enter LED Number 0 to 9 or 'x' to clear” has been sent by the Arduino,
and it is telling us what commands we can send to the Arduino which is either to
send the 'x' (to turn all the LEDs off) or the number of the LED you want to turn on
(where 0 is the bottom LED, 1 is the next one up right up to 7 for the top LED).
Try typing the following commands, into the top area of the Serial Monitor that is
level with the 'Send' button. Press 'Send', after typing each of these characters: x 0
3 5. Typing x, will have no effect, if the LEDs are already all off, but as you enter
each number, the corresponding LED should light and you will get a confirmation
message from the Arduino board, so that the Serial Monitor will appear as shown
below.
You can see that I am about to press send after entering 'x' again. Do this and all
the LEDs will turn off.
4
Al-Mustansiriyah University Third Class
Faculty of engineering
Computer engineering Department Microcomputer Lab.
Arduino Code:
As you might expect, the sketch is based on the sketch used in lesson 4. So, we
will just cover the new bits here. You will find it useful to refer to the full sketch in
your Arduino IDE.
Firstly, in the 'setup' function, there are three new lines on the end:
5
Al-Mustansiriyah University Third Class
Faculty of engineering
Computer engineering Department Microcomputer Lab.
The last of the new lines in 'setup' sends out the message that we see at the top of
the serial monitor. The 'loop' function is where all the action happens:
Everything that happens inside the loop is contained within an 'if' statement. So
unless the call to the built-in Arduino function 'Serial.available()' is 'true' then
nothing else will happen. Serial.available() will return 'true' if data has been send to
the Arduino and is there ready to be processed. Incoming messages are held in
what is called a buffer and Serial.available() returns true if that buffer is Not
empty. If a message has been received, then its on to the next line of code:
This reads the next character from the buffer, and removes it from the buffer. It
also assigns it to the variable 'ch'. The variable 'ch' is of type 'char' which stands for
6
Al-Mustansiriyah University Third Class
Faculty of engineering
Computer engineering Department Microcomputer Lab.
'character' and as the name suggests, holds a single character. If you have followed
the instructions in the prompt at the top of the Serial Monitor, then this character
will either be a single digit number between 0 and 7 or the letter 'x'. The 'if'
statement on the next line checks to see if it is a single digit by seeing if 'ch' is
greater than or equal to the character '0' and less than or equal to the character '7'. It
looks a little strange comparing characters in this way, but is perfectly acceptable.
Each character is represented by a unique number, called its ASCII value. This
means that when we compare characters using <= and >= it is actually the ASCII
values that were being compared. If the test passes, then we come to the next line:
Now we are performing arithmetic on characters! We are subtracting the digit '0'
from whatever digit was entered. So, if you typed '0' then '0' – '0' will equal 0. If
you typed '7' then '7' – '0' will equal the number 7 because it is actually the ASCII
values that are being used in the subtraction. Since that we know the number of the
LED that we want to turn on, we just need to set that bit in the variable 'leds' and
update the shift register.
The next two lines write back a confirmation message to the Serial Monitor.
The first line uses Serial. Print rather than Serial.println. The different between the
two is that Serial. Print does not start a new line after printing whatever is in its
7
Al-Mustansiriyah University Third Class
Faculty of engineering
Computer engineering Department Microcomputer Lab.
parameter. We use this in the first line, because we are printing the message in two
parts. Firstly the general bit: 'Turned on LED ' and then the number of the LED.
The number of the LED is held in an 'int' variable rather than being a text string.
Serial. Print can take either a text string enclosed in double-quotes, or an 'int' or for
that matter pretty much any type of variable. After the 'if' statement that handles
the case, when a single digit has been handled, there is a second 'if' statement that
checks to see if 'ch' is the letter 'x'.
If it is, then it clears all the LEDs and sends a confirmation message.
The Serial Monitor is also a great way of debugging a sketch that is misbehaving.
Sometimes, when a sketch is not behaving how you think it should behave, placing
Serial. println() statements in key places will help you see what is going on.
5. Discussion:
1. We sent the character to control the LEDs separately, by clicking send after each
character. Try entering the following into the Serial Monitor and clicking 'Send':
x0246?
2. Change the baud rate in the sketch from 9600 to 115200 and upload it to the
board again. Then after opening the Serial Monitor select 115200 from the drop-
down list?
8
Al-Mustansiriyah University Third Class
Faculty of engineering
Computer engineering Department Microcomputer Lab.
9
Al-Mustansiriyah University Third Class
Faculty of engineering
Computer engineering Department Microcomputer Lab.
10
Al-Mustansiriyah University Third Class
Faculty of engineering
Computer engineering Department Microcomputer Lab.
1. Object:
Learn to use push buttons with digital inputs to turn an LED on and off.
2. Requirements:
1
Al-Mustansiriyah University Third Class
Faculty of engineering
Computer engineering Department Microcomputer Lab.
3. Theory:
Push Switches:
Switches are really simple components. When we press a button or flip a lever,
they connect two contacts together so that electricity can flow through them. The
little tactile switches that are used in this Exp. have four connections, which can be
a little confusing.
Actually, there are only really two electrical connections, as inside the switch
package pins B and C are connected together, as are A and D.
2
Al-Mustansiriyah University Third Class
Faculty of engineering
Computer engineering Department Microcomputer Lab.
4. Procedure:
Breadboard Layout:
Although the bodies of the switches are square, the pins protrude from opposite
sides of the switch. This means that the pins will only be far enough apart when
they are the correct way around on the breadboard.
Remember that the LED has to be the correct way around with the shorter negative
lead to the right.
Arduino Code:
Load the following sketch onto our Arduino board. Pressing the top button will
turn the LED on, pressing the bottom button will turn it off again.
3
Al-Mustansiriyah University Third Class
Faculty of engineering
Computer engineering Department Microcomputer Lab.
The first part of the sketch defines three variable for the three pins that are to be
used. The 'ledPin' is the output pin and 'buttonApin' will refer to the switch nearer
the top of the breadboard and 'buttonBpin' to the other switch. The 'setup' function
defines the ledPin as being an OUTPUT as normal, but now we have the two
inputs to deal with. In this case, we use the set the pinMode to be
'INPUT_PULLUP' like this:
The pin mode of INPUT_PULLUP means that the pin is to be used as an input, but
that if nothing else is connected to the input it should be 'pulled up' to HIGH. In
other words, the default value for the input is HIGH, unless it is pulled LOW by
the action of pressing the button. This is why the switches are connected to GND.
4
Al-Mustansiriyah University Third Class
Faculty of engineering
Computer engineering Department Microcomputer Lab.
When a switch is pressed, it connects the input pin to GND, so that it is no longer
HIGH. Since the input is normally HIGH and only goes LOW, when the button is
pressed, the logic is a little up-side-down. We will handle this in the 'loop'
function.
In the 'loop' function there are two 'if' statements. One for each button. Each does
an 'digitalRead' on the appropriate input. Remember that if the button is pressed,
the corresponding input will be LOW, if button A is low, then a 'digitalWrite' on
the ledPin turns it on. Similarly, if button B is pressed, a LOW is written to the
ledPin.
5. Discussion:
There are a couple of things we could try with this hardware. Firstly, we could try
taking what we learnt in Exp. 5 and adding some commands to the sketch that print
something to the Serial Monitor whenever either switch is pressed. Remember that
as well as printing out a message using something like this in our 'loop' function:
We will also need to start serial communication in the 'setup' function by doing
this:
5
Al-Mustansiriyah University Third Class
Faculty of engineering
Computer engineering Department Microcomputer Lab.
6
Al-Mustansiriyah University Third Class
Faculty of engineering
Computer engineering Department Microcomputer Lab.
1. Object:
1
Al-Mustansiriyah University Third Class
Faculty of engineering
Computer engineering Department Microcomputer Lab.
3. Theory:
In this exp., you will be combining some of the things that you learnt in earlier
experiments to use three push switches (from exp.7) to control the color of the
RGB LED that you used in exp.4 in order to make a Color Organ!
2
Al-Mustansiriyah University Third Class
Faculty of engineering
Computer engineering Department Microcomputer Lab.
4. Procedure:
Breadboard Layout:
The breadboard layout is shown below. The RGB LED should have the longest
lead in row 2 of the breadboard. This will be connected to GND. This wiring
diagram assumes you have a co mmo n catho de LED - if you have a common
anode LED, connect the longest pin to +5V instead of ground. Note that with a
common anode display the LED color cycling will be reversed.
Arduino Code:
Load the following sketch onto your Arduino board. To start with, all the LEDs
will be off. If you press and hold one of the buttons, then the LED will
gradually get brighter. The color will be red for the top button, green for the
middle one and blue for the bottom button. When you have got enough of one
color, try pressing another button and see how they mix together. If you want to
start over, then press the reset button on the Arduino. This is the red button,
next to the USB connector.
3
Al-Mustansiriyah University Third Class
Faculty of engineering
Computer engineering Department Microcomputer Lab.
The sketch is similar to that of exp.4. Again, we have three output pins to control
the LED. These are PWM pins so that we can control how much power goes to
4
Al-Mustansiriyah University Third Class
Faculty of engineering
Computer engineering Department Microcomputer Lab.
each color of the LED. There are three other pins needed, one for each of the
buttons and these are configured in 'setup' to be inputs that are pulled up to HIGH,
unless the button is pressed, which will cause them to become LOW. After the pin
definition, there is another little group of variables called 'red', 'green' and 'blue'.
These variables are used to hold the current values for the intensity of each of the
LED channels. So, if 'red' is 0 then the red part of the LED will be off. However, if
it is 255 then it will be at maximum brightness. The 'loop' function is in two parts.
The first part checks the buttons and makes any necessary changes to 'red', 'green'
or 'blue' depending on the button. Each button works in the same way, just for a
different color. The section for checking the red button is like this:
If, when we carry out a 'digitalRead' on the red switch pin, we find it is LOW, then
that means the button is pressed, so we add 1 to 'red'. The command ++ adds one to
a variable. However, we need to be careful here, because the maximum value that
you can use for PWM is 255. So on the next line, we check to see if we have gone
over the limit, and if we have then red is set back to 0, so we start over. The second
part of the 'loop' function carries out the 'analogWrite's to each of the LED colors.
5
Al-Mustansiriyah University Third Class
Faculty of engineering
Computer engineering Department Microcomputer Lab.
Finally there is a short delay at the end of the loop, that slows down the color
changing to a manageable speed.
5. Discussion:
1. Try removing the delay at the end of 'loop'. You can do this by 'commenting out'
the delay line by putting // at the start of the line like this:
This is a useful technique, because when you find out that you need to put the line
back in again, you can do so, just by taking the // away again. Without the delay,
you will find that basically, whenever you release the button, you will be left with
a random level of brightness for that color. What is happening is that it is cycling
through the brightness levels so fast, that you have no chance of actually
controlling it?
2. Another experiment you could make would be to change the function of the
three buttons so that they control the LED as if it was a traffic signal. Try to make
it so that the top button turns the LED fully green, the middle button Orange and
the bottom button red?
6
Al-Mustansiriyah University Third Class
Faculty of engineering
Computer engineering Department Microcomputer Lab.
1. Object:
In this exp. we will start by using the Serial Monitor to display analog readings,
and then extend the project using eight LEDs from exp.5, so that we can control
the number of LEDs that are lit by turning the knob on a variable resistor.
2. Requirements:
1
Al-Mustansiriyah University Third Class
Faculty of engineering
Computer engineering Department Microcomputer Lab.
3. Theory:
2
Al-Mustansiriyah University Third Class
Faculty of engineering
Computer engineering Department Microcomputer Lab.
Your pot has a circular 'track' that acts as a resistor, in our case it's a 10 kΩ resistor.
However, the difference with a pot, is that there is also a middle connection called
the 'slider'. This connection is rotated when you turn the pot. So if you connect one
end of the pot to 5V and the other to GND, then the voltage at the slider will vary
between 0 and 5V as you turn it.
4. Procedure:
Before we go ahead and use the LEDs, you can try a little experiment using just the
variable resistor also known as a potentiometer (often called a 'pot' for short) and
the Arduino Serial Monitor. Connect up your breadboard as shown below:
3
Al-Mustansiriyah University Third Class
Faculty of engineering
Computer engineering Department Microcomputer Lab.
Now open the Serial Monitor, and you will see a stream of numbers appearing.
Turn the knob on the variable resistor and you will see the number change between
0 and 1023. The Serial Monitor is displaying the analog reading value from A0
using the line:
4
Al-Mustansiriyah University Third Class
Faculty of engineering
Computer engineering Department Microcomputer Lab.
Breadboard Layout:
Let's do something more interesting with the pot. We can use it to control the
number of LEDs lit. This breadboard layout is based on that of exp.5, there are a
few jumpers moved, and the pot and it's connections to the Arduino have been
added.
5
Al-Mustansiriyah University Third Class
Faculty of engineering
Computer engineering Department Microcomputer Lab.
Arduino Code:
Load the following sketch onto your Arduino board.
You should recognize much of this code from exp.5. So refer back to that exp.
for more information about how the LEDs are controlled. The key parts of the
sketch as far as analog inputs are concerned are the line where we define the
analog pin that we are going to connect to the slider of the pot:
6
Al-Mustansiriyah University Third Class
Faculty of engineering
Computer engineering Department Microcomputer Lab.
Note that we do not need to put anything in 'setup' to set the pin mode for an
analog input. In the main loop, we read the analog value like this:
But then this reading between 0 and 1023 needs converting into a number of
LEDs to light, between 0 and 8. The range of numbers, between 0 and 8 is
actually 9 values. So we need to scale the reading by 1023 divided by 9 or 114.
To light the right number of LEDs, we use the 'for' loop to count from 0 up to
'numLEDSLit' setting the bit at that position.
5. Discussion:
It is actually simpler to light a single LED to indicate the position of the knob. Try
modifying your sketch to do this.
7
Al-Mustansiriyah University Third Class
Faculty of engineering
Computer engineering Department Microcomputer Lab.
1. Object:
In this exp. we will learn how to measure light intensity using an Analog Input.
We will build on exp.9 and use the level of light to control the number of LEDs to
be lit.
2. Requirements:
1
Al-Mustansiriyah University Third Class
Faculty of engineering
Computer engineering Department Microcomputer Lab.
2
Al-Mustansiriyah University Third Class
Faculty of engineering
Computer engineering Department Microcomputer Lab.
3. Theory:
Photocells :
The photocell used is of a type called a light dependent resistor, sometimes called
an LDR. As the name suggests, these components act just like a resistor, except
that the resistance changes in response to how much light is falling on them. This
one has a resistance of about 50 kΩ in near darkness and 500 Ω in bright light. To
convert this varying value of resistance into something we can measure on an
Arduino's analog input, it need to be converted into a voltage. The simplest way to
do that is to combine it with a fixed resistor.
The resistor and photocell together behave rather like a pot. When the light is very
bright, then the resistance of the photocell is very low compared with the fixed
value resistor, and so it is as if the pot were turned to maximum. When the
photocell is in dull light the resistance becomes greater than the fixed 1kΩ resistor
and it is as if the pot were being turned towards GND. Load up the sketch given in
the next section and try covering the photocell with your finger, and holding it near
a light source.
3
Al-Mustansiriyah University Third Class
Faculty of engineering
Computer engineering Department Microcomputer Lab.
4. Procedure:
Breadboard Layout:
The breadboard layout for this exp.is the same as for exp.9, except that the pot is
replaced by an LDR and a 1 kΩ resistor. Here is the layout for exp.9, near the pot.
4
Al-Mustansiriyah University Third Class
Faculty of engineering
Computer engineering Department Microcomputer Lab.
Arduino Code:
The sketch that you used in exp.9, will work, but you will find that you will not
be able to find a light bright enough to light all the LEDs. This is because of the
fixed resistor, so we need to compensate for the fact that no matter how low the
resistance of the photocell falls, there will always be the 1 kΩ of the fixed
resistor offsetting it. The slightly modified exp.9 sketch is listed below:
5
Al-Mustansiriyah University Third Class
Faculty of engineering
Computer engineering Department Microcomputer Lab.
The first thing to note is that we have changed the name of the analog pin to be
'lightPin' rather than 'potPin' since we no longer have a pot connected. The only
other substantial change to the sketch is the line that calculate how many of the
LEDs to light:
This time we divide the raw reading by 57 rather than 114 from lesson 8. In other
words we divide it by half as much as we did with the pot, to split it into nine
zones, from no LEDs lit, to all eight lit. This extra factor is to account for the fixed
1 kΩ resistor. This means that when the photocell has a resistance of 1 kΩ (the
same as the fixed resistor) the raw reading will be 1023 / 2 = 511. This will equate
to all the LEDs being lit and then a bit (numLEDSLit will be 9).
5. Discussion:
1. To vary the sensitivity of the light meter you have just made, try changing the
value of the factor (57) that you divide the analog reading by. Increasing this value
will make the reading less sensitive?
2. You could try is to change the sketch so that while the reading is below a certain
level, the LEDs are on, but they automatically turn off when a threshold is
exceeded. So putting your finger near the photocell to cut out most of the light will
turn on the LEDs?