Arduino Inventors Kit Manual
Arduino Inventors Kit Manual
B2CQSHOP
2012 - 3 - 04
Contents
The Kit Contents ...............................................................................................................................4
Introduction.......................................................................................................................................5
What exactly is an Arduino? .............................................................................................................7
Getting Started ................................................................................................................................11
COMPONENT DETAILS...............................................................................................................18
Introduction
Thank you for purchasing this Arduino Kit. You are now well on your way in
your journey into the wonderful world of the Arduino and microcontroller electronics.
This book will guide you, step by step, through using the Starter Kit to learn about the
Arduino hardware, software and general electronics theory. Through the use of electronic
projects we will take you from the level of complete beginner through to having an
intermediate set of skills in using the Arduino.
The purpose of this book and the kit is to give you a gentle introduction to the Arduino,
electronics and programming in C and to set you up with the necessary skills needed to
progress beyond the book and the kit into the world of the Arduino and microcontroller
electronics.
The booklet has been written presuming that you have no prior knowledge of
electronics, the Arduino hardware, software environment or of computer programming. At
no time will we get too deep into electronics or programming in C. There are many other
resources available for free that will enable you to learn a lot more about this subject if you
wish to go further. The best possible way to learn the Arduino, after using this kit of course,
is to join the Arduino Forum on the Arduino website and to check out the code and
hardware examples in the ‘Playground’ section of the Arduino website too.
We hope you enjoy using the kit and get satisfaction from creating the projects and seeing
your creations come to life.
How to use it
The book starts off with an introduction to the Arduino, how to set up the hardware,
install the software, etc.
We then explain the Arduino IDE and how to use it before we dive right into some
projects progressing from very basic stuff through to advanced topics. Each project will
start off with a description of how to set up the hardware and what code is needed to get it
working. We will then describe separately the code and the hardware and explain in some
detail how it works.
Everything will be explained in clear and easy to follow steps. The book contains a lot
of diagrams and photographs to make it as easy as possible to check that you are
following along with the project correctly.
( Thank you very much for the book of “Sparkfun” , book title is “ Sparkfun inventors
kit for arduino guide ”
Thank you very much for the book of “ Mike McRoberts “ , book title is “ Arduino Starter
Kit Manual Mar2010 “
Thank you very much for the book of “Michael.Margolis “,book title is “Arduino
Cookbook 2011”.
And Thank you very much the team of B2CQSHOP , too )
B2CQSHOP
Webstite : www.b2cqshop.com
Email : [email protected]
MSN : [email protected]
Skype : evanjoo
an Arduino is a tiny computer that you can program to process inputs and outputs
going to and from the chip.
The Arduino is what is known as a Physical or Embedded Computing platform, which
means that it is an interactive system, that through the use of hardware and software can
interact with it’s environment.
For example, a simple use of the Arduino would be to turn a light on for a set period of
time, let’s say 30 seconds, after a button has been pressed (we will build this very same
project later in the book). In this example, the Arduino would have a lamp connected to it
as well as a button. The Arduino would sit patiently waiting for the button to be pressed.
When you press the button it would then turn the lamp on and start counting. Once it had
counted 30 seconds it would then turn the lamp off and then carry on sitting there waiting
for another button press. You could use this set-up to control a lamp in an under-stairs
cupboard for example. You could extend this example to sense when the cupboard door
was opened and automatically turn the light on, turning it off after a set period of time.
The Arduino can be used to develop stand-alone interactive objects or it can be
connected to a computer to retrieve or send data to the Arduino and then act on that data
(e.g. Send sensor data out to the internet).
The Arduino can be connected to LED displays, LED’s. Dot Matrix displays, buttons,
switches, motors, temperature sensors, pressure sensors, distance sensors, SD card,
webcams, printers, GPS receivers, ethernet modules, and so on .
The Arduino board is made of an an Atmel AVR Microprocessor, a crystal or oscillator
(basically a crude clock that sends time pulses to the microcontroller to enable it to
operate at the correct speed) and a 5-volt linear regulator. Depending on what type of
Arduino you have, you may also have a USB connector to enable it to be connected to a
PC or Mac to upload or retrieve data. The board exposes the microcontroller’s I/O
(Input/Output) pins to enable you to connect those pins to other circuits or to sensors, etc.
To program the Arduino (make it do what you want it to) you also use the Arduino
IDE (Integrated Development Environment), which is a piece of free software, that
enables you to program in the language that the Arduino understands. In the case of the
Arduino the language is C. The IDE enables you to write a computer program, which is a
set of step-bystep instructions that you then upload to the Arduino. Then your Arduino will
carry out those instructions and interact with the world outside. In the Arduino world,
programs are known as ‘ Sketches
‘.
The Arduino hardware and software are both Open Source, which means the code,
the schematics, design, etc. are all open for anyone to take freely and do what they like
with it.
This means there is nothing stopping anyone from taking the schematics and PCB
designs of the Arduino and making their own and selling them. This is perfectly legal, and
indeed the whole purpose of Open Source, and indeed the Freeduino that comes with the
Earthshine Design Arduino Starter Kit is a perfect example of where someone has taken
the Arduino PCB design, made their own and are selling it under the Freeduino name.
You could even make your own Arduino, with just a few cheap components, on a
breadboard.
The only stipulation that the Arduino development team put on outside developers is
that the Arduino name can only be used exclusively by them on their own products and
hence the clone boards have names such as Dfrobot, Freeduino, Boarduino, Roboduino,
etc.
As the designs are open source, any clone board, such as the Freeduino is 100%
compatible with the Arduino and therefore any software, hardware, shields, etc. will all be
100% compatible with a genuine Arduino.
The Arduino can also be extended with the use of ‘Shields’ which are circuit boards
containing other devices (e.g. GPS receivers, LCD Displays, Ethernet connections, etc.)
that you can simply slot into the top of your Arduino to get extra functionality. You don’t
have to use a shield if you don’t want to as you can make the exact same circuitry using a
breadboard, some veroboard or even by making your own PCB’s.
There are many different variants of the Arduino available. The most common one is
the Diecimila or the Duemilanove. You can also get Mini, Nano and Bluetooth Arduino’s.
New to the product line is the new Arduino Mega with increased memory and number
of I/O pins.
Probably the most versatile Arduino, and hence the reason it is the most popular, is
the Duemilanove. This is because it uses a standard 28 pin chip, attached to an IC Socket.
The beauty of this systems is that if you make something neat with the Arduino and then
want to turn it into something permanent (e.g. Or understairs cupboard light), then instead
of using the relatively expensive Arduino board, you can simply use the Arduino to
develop your device, then pop the chip out of the board and place it into your own circuit
board in your custom device. You would then have made a custom embedded device,
which is really cool. Then, for a couple of quid or bucks you can replace the AVR chip in
your Arduino with a new one. The chip must be pre-programmed with the Arduino
Bootloader to enable it to work with the Arduino IDE, but you can either burn the
bootloader yourself if you purchase an AVR Programmer, or you can buy these
preprogrammed from many suppliers around the world. Of course, Earthshine Design
provide preprogrammed Arduino chips in it’ store for a very reasonable price.
If you do a search on the Internet by simply typing ‘Arduino’ into the search box of
your favourite search engine, you will be amazed at the huge amount of websites
dedicated to the Arduino. You can find a mind boggling amount of information on projects
made with the Arduino and if you have a project in mind, will easily find information that
will help you to get your project up and running easily.
www.b2cshop.com Ebay store: b2cqshop , E-qstore 9
www.b2cqshop.com Ebay store: b2cqshop , E-qstore
The Arduino is an amazing device and will enable you to make anything from
interactive works of art to robots. With a little enthusiasm to learn how to program the
Arduino and make it interact with other components a well as a bit of imagination, you can
build anything you want.
This book and the kit will give you the necessary skills needed to get started in this
exciting and creative hobby.
So, now you know what an Arduino is and what you can do with it, let’s open up the
starter kit and dive right in.
Getting Started
This section will presume you have a PC running Windows or a Mac running OSX ,
Linux (on the playground wiki).
Connect the Arduino board to your computer using the USB cable. The green power
LED (labelled PWR) should go on.
• Plug in your board and wait for Windows to begin it's driver installation
process. After a few moments, the process will fail, despite its best efforts
• Click on the Start Menu, and open up the Control Panel.
• While in the Control Panel, navigate to System and Security. Next, click on
System. Once the System window is up, open the Device Manager.
• Look under Ports (COM & LPT). You should see an open port named "Arduino
UNO (COMxx)"
• Right click on the "Arduino UNO (COmxx)" port and choose the "Update Driver
Software" option.
• Next, choose the "Browse my computer for Driver software" option.
• Finally, navigate to and select the Uno's driver file, named "ArduinoUNO.inf",
located in the "Drivers" folder of the Arduino Software download (not the "FTDI
USB Drivers" sub-directory).
• Windows will finish up the driver installation from there.
When you connect the board, Windows should initiate the driver installation
process (if you haven't used the computer with an Arduino board before).
Double click the ICON to open up the IDE. You will then be
presented with a blue and white screen with a default sketch loaded
inside.
This is the Arduino IDE (Integrated Development Environment) and is where you will write
your Sketches (programs) to upload to your Arduino board .
1) Open the LED blink example sketch: File > Examples > 1.Basics > Blink.
Now, simply click the "Upload" button in the environment. Wait a few
seconds - you should see the RX and TX leds on the board flashing. If the
upload is successful, the message "Done uploading." will appear in the
status bar. (Note: If you have an Arduino Mini, NG, or other board, you'll
need to physically present the reset button on the board immediately
before pressing the upload button.)
A few seconds after the upload finishes, you should see the pin 13
(L) LED on the board start to blink (in orange). If it does,
congratulations! You've gotten Arduino up-and-running.
Tips :
The Toolbar buttons are listed above. The functions of each button are as follows :
z Verify/Compile Checks the code for errors
The Verify/Compile button is used to check that yourcode is correct, before you
upload it to your Arduino.
The Stop button will stop the Serial Monitor from operating. It will also un-highlight
other selected buttons. Whilst the Serial Monitor is operating you may wish to press the
Stop button to obtain a ‘snapshot’ of the serial data so far to examine it. This is particularly
useful if you are sending data out to the Serial Monitor quicker than you can read it.
The New button will create a completely new and blank Sketch read for you to enter
code into. The IDE will ask you to enter a name and a location for your Sketch (try to use
the default location if possible) and will then give you a blank Sketch ready to be coded.
The tab at the top of the Sketch will now contain the name you have given to your new
sketch.
The Open button will present you with a list of Sketches stored within your
sketchbook as well as a list of Example sketches you can try out with various peripherals
once connected.
The Save button will save the code within the sketch window to your sketch file. Once
complete you will get a ‘Done Saving message at the bottom of the code window.
The Upload to I/O Board button will upload the code within the current sketch
window to your Arduino. You need to make sure that you have the correct board and port
selected (in the Tools menu) before uploading. It is essential that you Save your sketch
before you upload it to your board in case a strange error causes your system to hang or
the IDE to crash.
It is also advisable to Verify/Compile the code before you upload to ensure there are
no errors that need to be debugged first.
The Serial Monitor is a very useful tool, especially for debugging your code. The
To the right of this is a blank text box for you to enter text to send back to the Arduino
and a Send button to send the text within that field. Note that no serial data can be
received by the Serial Monitor unless you have set up the code inside your sketch to do so.
Similarly, the Arduino will not receive any data sent unless you have coded it to do so.
Finally, the black area is where your serial data will be displayed. In the image above,
the Arduino is running the ASCIITable sketch, that can be found in the Communications
examples. This program outputs ASCII characters, from the Arduino via serial (the USB
cable) to the PC where the Serial monitor then displays them.
To start the Serial Monitor press the Serial Monitor button and to stop it press the
Stop button. On a Mac or in Linux, Arduino board will reset itself (rerun the code from the
beginning) when you click the Serial Monitor button.
Once you are proficient at communicating via serial to and from the Arduino you can
use other programs such as Processing, Flash, MaxMSP, etc. To communicate between
the Arduino and your PC.
COMPONENT DETAILS
1) Solderless Breadboard
The breadboard has 400 Tie points. 1) Terminal Strip, Tie-point 300 ;2)
Distribution strip, Tie-point 100 .
Accepts a variety of wire sizes (29-20 AWG) .
It is Compatible with all kind of ProtoShield. Completely reusable,Reusable for fast build
a prototype of an electronic circuit. With Twin adhesive back, it could be fix and remove to
any position easily. Its Dimension: 83.5mm x 54.5mm x 8.5mm.
2) LED
More Details:
http://ardx.org/LED
3) Diode
More Details:
http://ardx.org/DIOD
4) Resistors
5) Transistor
More Details:
http://ardx.org/TRAN
6)Small Servo
More Details:
http://ardx.org/SERV
7) DC Motor
More Details:
http://ardx.org/MOTO
7) Piezo Element
www.b2cshop.com Ebay store: b2cqshop , E-qstore 20
www.b2cqshop.com Ebay store: b2cqshop , E-qstore
More Details:
http://ardx.org/PIEZ
More Details:
http://ardx.org/ICIC
9) Pushbutton
10) Potentiometer
More Details:
http://ardx.org/POTE
Photo Resistor
What it Does: No. of Leads:
Produces a variable resistance dependant 2
on the amount of incident light. Things to watch out for:
Identifying: - Remember it needs to be in a voltage
Usually a little disk with a clear top and a divider before it provides a useful input.
curvy line underneath.
More Details:
http://ardx.org/PHOT
LEAD CLIPPING
Some components in this kit come with very long wire leads. To make them more compatible
with a breadboard a couple of changes are required.
LEDs:
Clip the leads so the long lead is ~10mm (3/8”) long and the short one is ~7mm (9/32”).
Resistors:
Bend the leads down so they are 90 degrees to the cylinder. Then snip them so they are
~6mm (1/4”) long.
Other Components:
Other components may need clipping.
Use your discretion when doing so.
Connect it up
Now, first make sure that your Arduino is powered off. You can do this either by
unplugging the USB cable or by taking out the Power Selector Jumper on the Arduino
board. Then connect everything up like this :
It doesn’t matter if you use different coloured wires or use different holes on the
Now press the Verify/Compile button at the top of the IDE to make sure there are no
errors in your code. If this is successful you can now click the Upload button to upload the
code to your Arduino.
If you have done everything right you should now see the Red LED on the
breadboard flashing on and off every second. Now let’s take a look at the code and the
hardware and find out how they both work.
Now let’s take a look at the code and the hardware and find out how they both work.
Our setup function only has one statement and that is pinMode. Here we are telling the
Arduino that we want to set the mode of one of our digital pins to be Output mode, rather
than Input. Within the parenthesis we put the pin number and the mode (OUTPUT or
INPUT). Our pin number is ledPin, which has been previously set to the value 10 in our
program. Therefore, this statement is simply telling the Arduino that the Digital Pin 10 is to
be set to OUTPUT mode. As the setup() function runs only once, we now move
onto the main function loop.
void loop() {
digitalWrite(ledPin, HIGH);
delay(1000);
digitalWrite(ledPin, LOW);
delay(1000);
}
The loop() function is the main program function and runs continuously as long as our
Arduino is turned on.Every statement within the loop() function (within the curly braces) is
carried out, one by one, step by step, until the bottom of the function is reached, then the
loop starts again at the top of the function, and so on forever or until you turn the Arduino
off or press the Reset switch.
www.b2cshop.com Ebay store: b2cqshop , E-qstore 28
www.b2cqshop.com Ebay store: b2cqshop , E-qstore
In this project we want the LED to turn on, stay on for one second, turn off and remain
off for one second, and then repeat. Therefore, the commands to tell the Arduino to do
that are contained within the loop() function as we wish them to repeat over and over.
The first statement is
digitalWrite(ledPin, HIGH);
and this writes a HIGH or a LOW value to the digital pin within the statement (in this
case ledPin, which is Digital Pin 10). When you set a digital pin to HIGH you are sending
out 5 volts to that pin. When you set it to LOW the pin becomes 0 volts, or Ground. This
statement therefore sends out 5v to digital pin 10 and turns the LED on.
After that is
delay(1000);
and this statement simply tells the Arduino to wait for 1000 milliseconds (to 1 second as
there are 1000 milliseconds in a second) before carrying out the next statement which is
digitalWrite(ledPin, LOW);
which will turn off the power going to digital pin 10 and therefore turn the LED off.
There is then another delay statement for another 1000 milliseconds and then the function
ends. However, as this is our main loop() function, the function will now start again at the
beginning. By following the program structure step by step again we can see that it is very
simple.
// Project 1 - LED Flasher
int ledPin = 10;
void setup() {
pinMode(ledPin, OUTPUT);
}
void loop() {
digitalWrite(ledPin, HIGH);
delay(1000);
digitalWrite(ledPin, LOW);
delay(1000);
}
We start off by assigning a variable called ledPin, giving that variable a value of 10.
Then we move onto the setup() function where we simply set the mode for digital pin 10
as an output.
In the main program loop we set Digital Pin 10 to high, sending out 5v. Then we wait for
a second and then turn off the 5v to Pin 10, before waiting another second. The loop then
starts again at the beginning and the LED will therefore turn on and off continuously for as
long as the Arduino has power.
Now that you know this you can modify the code to turn the LED on for a different period
of time and also turn it off for a different time period.
seconds, then go off for half a second we could do
this:-
void loop() {
digitalWrite(ledPin, HIGH);
www.b2cshop.com Ebay store: b2cqshop , E-qstore 29
www.b2cqshop.com Ebay store: b2cqshop , E-qstore
delay(2000);
digitalWrite(ledPin, LOW);
delay(500);
}
or maybe you would like the LED to stay off for 5 seconds and then flash briefly (250ms),
like the LED indicator on a car alarm then you could do this :
void loop() {
digitalWrite(ledPin, HIGH);
delay(250);
digitalWrite(ledPin, LOW);
delay(5000);
}
or make the LED flash on and off very fast
void loop() {
digitalWrite(ledPin, HIGH);
delay(50);
digitalWrite(ledPin, LOW);
delay(50);
}
By varying the on and off times of the LED you create any effect you want. Well, within
the bounds of a single LED going on and off that is.
Before we move onto something a little more exciting let’s take a look at the hardware
and see how it works.
LED
The longer one lead is Anode ( “+”), the another one is Cathode (“ --”) .
For example , If We need a 150Ω resistor, so if we look at the colour table we see that
we need 1 in the first band, which is Brown, followed by a 5 in the next band which is
Green and we then need to multiply this by 101 (in other words add 1 zero) which is
www.b2cshop.com Ebay store: b2cqshop , E-qstore 33
www.b2cqshop.com Ebay store: b2cqshop , E-qstore
Brown in the 3rd
band. The final band is irrelevant for our purposes as this is the tolerance. Our resistor has
a gold band and therefore has a tolerance of ±5% which means the actual value of the
resistor can vary between 142.5Ω and 157.5Ω. We therefore need a resistor with a Brown,
Green, Brown, Gold colour band combination
Our final component is an LED (I’m sure you can figure out what the jumper wires do
for yourself), which stands for Light Emitting Diode. A Diode is a device that permits
current to flow in only one direction. So, it is just like a valve in a water system, but in this
case it is letting electrical current to go in one direction, but if the current tried to reverse
and go back in the opposite direction the diode would stop it from doing so. Diodes can be
useful to prevent someone from accidently connecting the Power and Ground to the
wrong terminals in a circuit and damaging the components.
An LED is the same thing, but it also emits light. LED’s come in all kinds of different
colours and brightnesses and can also emit light in the ultraviolet and infrared
part of the spectrum (like in the LED’s in your TV remote control).
If you look carefully at the LED you will notice two things. One is that the legs are of
different lengths and also that on one side of the LED, instead of it being cylindrical, it is
flattened. These are indicators to show you which leg is the Anode (Positive) and which is
the Cathode (Negative). The longer leg gets connected to the Positive Supply (3.3v) and
the leg with the flattened side goes to Ground.
If you connect the LED the wrong way, it will not damage it (unless you put very high
currents through it) and indeed you can make use of that ‘feature’ as we will see later on.
It is essential that you always put a resistor in series with the LED to ensure that the
correct current gets to the LED. You can permanently damage the LED if you fail to do
this.
As well as single colour resistors you can also obtain bi-colour and tricolour LED’s.
These will have several legs coming out of them with one of them being common (i.e.
Common anode or common cathode).
Supplied with your kit is an RGB LED, which is 3 LED’s in a single package. An RGB
www.b2cshop.com Ebay store: b2cqshop , E-qstore 34
www.b2cqshop.com Ebay store: b2cqshop , E-qstore
LED has a Red, Green and a Blue (hence RGB) LED in one package.
The LED has 4 legs, one will be a common anode or cathode, common to all 3 LED’s
and the other 3 will then go to the anode or cathode of the individual Red, Green and Blue
LED’s. By adjusting the brightness values of the R, G and B channels of the RGB LED you
can get any colour you want. The same effect can be obtained if you used 3 separate red,
green and blue LED’s.
Now that you know how the components work and how the code in this project works,
let’s try something a bit more interesting.
/*
* setup() - this function runs once when you turn your Arduino on
* We the three control pins to outputs
*/
void setup()
{
//Set each pin connected to an LED to output mode (pulling high (on) or low (off)
www.b2cshop.com Ebay store: b2cqshop , E-qstore 37
www.b2cqshop.com Ebay store: b2cqshop , E-qstore
for(int i = 0; i < 8; i++){ //this is a loop and will repeat eight times
pinMode(ledPins[i],OUTPUT); //we use this to set each LED pin to output
} //the code this replaces is below
/*
* loop() - this function will start after setup finishes and then repeat
* we call a function called oneAfterAnother(). if you would like a different behaviour
* uncomment (delete the two slashes) one of the other lines
*/
void loop() // run over and over again
{
oneAfterAnotherNoLoop(); //this will turn on each LED one by one then turn each off
//oneAfterAnotherLoop(); //does the same as oneAfterAnotherNoLoop but with
//much less typing
//oneOnAtATime(); //this will turn one LED on then turn the next one
//on turning the
//former off (one LED will look like it is scrolling
//along the line
//inAndOut(); //lights the two middle LEDs then moves them out then back
//in again
}
/*
* oneAfterAnotherNoLoop() - Will light one LED then delay for delayTime then light
* the next LED until all LEDs are on it will then turn them off one after another
*
* this does it without using a loop which makes for a lot of typing.
* oneOnAtATimeLoop() does exactly the same thing with less typing
www.b2cshop.com Ebay store: b2cqshop , E-qstore 38
www.b2cqshop.com Ebay store: b2cqshop , E-qstore
*/
void oneAfterAnotherNoLoop(){
int delayTime = 100; //the time (in milliseconds) to pause between LEDs
//make smaller for quicker switching and larger for slower
digitalWrite(ledPins[0], HIGH); //Turns on LED #0 (connected to pin 2 )
delay(delayTime); //waits delayTime milliseconds
digitalWrite(ledPins[1], HIGH); //Turns on LED #1 (connected to pin 3 )
delay(delayTime); //waits delayTime milliseconds
digitalWrite(ledPins[2], HIGH); //Turns on LED #2 (connected to pin 4 )
delay(delayTime); //waits delayTime milliseconds
digitalWrite(ledPins[3], HIGH); //Turns on LED #3 (connected to pin 5 )
delay(delayTime); //waits delayTime milliseconds
digitalWrite(ledPins[4], HIGH); //Turns on LED #4 (connected to pin 6 )
delay(delayTime); //waits delayTime milliseconds
digitalWrite(ledPins[5], HIGH); //Turns on LED #5 (connected to pin 7 )
delay(delayTime); //waits delayTime milliseconds
digitalWrite(ledPins[6], HIGH); //Turns on LED #6 (connected to pin 8 )
delay(delayTime); //waits delayTime milliseconds
digitalWrite(ledPins[7], HIGH); //Turns on LED #7 (connected to pin 9 )
delay(delayTime); //waits delayTime milliseconds
/*
* oneAfterAnotherLoop() - Will light one LED then delay for delayTime then light
* the next LED until all LEDs are on it will then turn them off one after another
www.b2cshop.com Ebay store: b2cqshop , E-qstore 39
www.b2cqshop.com Ebay store: b2cqshop , E-qstore
*
* this does it using a loop which makes for a lot less typing.
* than oneOnAtATimeNoLoop() does exactly the same thing with less typing
*/
void oneAfterAnotherLoop(){
int delayTime = 100; //the time (in milliseconds) to pause between LEDs
//make smaller for quicker switching and larger for slower
/*
* oneOnAtATime() - Will light one LED then the next turning off all the others
*/
void oneOnAtATime(){
int delayTime = 100; //the time (in milliseconds) to pause between LEDs
//make smaller for quicker switching and larger for slower
/*
* inAndOut() - This will turn on the two middle LEDs then the next two out
* making an in and out look
*/
void inAndOut(){
int delayTime = 100; //the time (in milliseconds) to pause between LEDs
//make smaller for quicker switching and larger for slower
digitalWrite(ledPins[onLED1], HIGH);
digitalWrite(ledPins[onLED2], HIGH);
digitalWrite(ledPins[offLED1], LOW);
digitalWrite(ledPins[offLED2], LOW);
delay(delayTime);
}
digitalWrite(ledPins[onLED1], HIGH);
digitalWrite(ledPins[onLED2], HIGH);
digitalWrite(ledPins[offLED1], LOW);
digitalWrite(ledPins[offLED2], LOW);
delay(delayTime);
}
}
2) MAKING IT BETTER
www.b2cshop.com Ebay store: b2cqshop , E-qstore 43
www.b2cqshop.com Ebay store: b2cqshop , E-qstore
code to:
//oneAfterAnotherNoLoop(); Testing out your own animations:
oneAfterAnotherLoop(); Jump into the included code and start changing
//oneOnAtATime(); things. The main point is to turn an LED on use
//inAndOut(); digitalWrite(pinNumber, HIGH); then to turn
Upload the program, and notice that nothing has it off use digitalWrite(pinNumber, LOW); .
changed. You can take a look at the two Type away, regardless of what you change you won't
functions, each does the same thing, but use break anything.
different approaches (hint: the second one uses
a for loop).
Connect it up
The notes of the tune are stored in a character array as a text string.
char notes[] = "ccggaagffeeddc ";
Another array, this time of integers, is set up to store the length of each note.
int beats[] = { 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 2, 4 };
Next you will notice that we declare two functions before our setup() and loop() functions.
It doesn’t matter if we put our own functions before or after setup() and loop(). When the
program runs, the code within these two functions will not run before setup() runs as we have
not called those functions yet.
Let’s look at the setup and loop functions before we look at the playTone and playNote
functions. All that happens in setup() is we assign the speaker pin (9) as an output.
void setup() {
pinMode(speakerPin, OUTPUT);
}
In the main program loop we have an if/else statement inside a for loop.
for (int i = 0; i < length; i++) {
if (notes[i] == ' ') {
delay(beats[i] * tempo); // rest
} else {
playNote(notes[i], beats[i] * tempo);
}
As you can see, the first if statement has as it’s condition, that the array element [i] that
the element contains a space character.
if (notes[i] == ' ')
and this simply works out the value of eats[i] * empo nd causes a delay of that length to
cause a rest in the notes. We then have an else statement.
else {
Then if ‘test' had a value of 10 (which it does) the ledPin would be set to HIGH. If the
value of test was anything other than 10, the code within the else statement would be
carried out instead and the ledPin would be set to LOW.
The else statement calls a function called playNote and passes two parameters. The
first parameter is the value of notes[i] and the second is the value calculated from beats[i]
* tempo.
playNote(notes[i], beats[i] * tempo);
After if/else statement has been carried out, there is a delay whose value is
calculated by dividing tempo by 2.
delay(tempo / 2);
Let us now take a look at the two functions we have created for this project.
The first function that is called from the main program loop is playNote.
void playNote(char note, int duration) {
char names[] = { 'c', 'd', 'e', 'f', 'g', 'a',
'b', 'C' };
int tones[] = { 1915, 1700, 1519, 1432, 1275, 1136, 1014, 956 };
// play the tone corresponding to the note name
for (int i = 0; i < 8; i++) {
if (names[i] == note) {
playTone(tones[i], duration);
}
}
Two parameters have been passed to the function and within the function these have
been given the names note (character) and duration (integer).
The function sets up a local variable array of data type char called names . This
variable has local scope so is only visible to this function and not outside of it.
This array stores the names of the notes from middle C to high C.
We then create another array of data type integer and this array stores numbers that
correspond to the frequency of the tones, in Kilohertz, of each of the notes in the names[]
array.
int tones[] = { 1915, 1700, 1519, 1432, 1275, 1136, 1014, 956 };
After setting up the two arrays there is a for loop that looks through the 8 notes in the
www.bestqshop.com Ebay store: b2cqshop , E-qstore
www.b2cqshop.com Ebay store: b2cqshop , E-qstore
names[] array and compares it to the note sent to the function.
for (int i = 0; i < 8; i++) {
if (names[i] == note) {
playTone(tones[i], duration);
}
}
The tune that is sent to this function is ‘ccggaagffeeddc’ so the first note will be a middle
C.
The for loop compares that note with the notes in the names[] array and if there is a match,
calls up the second function, called play Tone, to play thecorresponding tone using in the
tones[] array using a note length of ‘duration’.
The second function is called playTone.
void playTone(int tone, int duration) {
for (long i = 0; i < duration * 1000L; i +=tone * 2) {
digitalWrite(speakerPin, HIGH);
delayMicroseconds(tone);
digitalWrite(speakerPin, LOW);
delayMicroseconds(tone);
}
}
Two parameters are passed to this function. The first is the tone (in kilohertz) that we want
the piezo speaker to reproduce and the second is the duration (made up by calculating beats[i]
* tempo.
As each for loop must be of a different length to make each note the same length (as
the delay differs between clicks to produce the desired frequency) the for loop will run to
duration multiplied by 1000 and the increment of the loop is the value of ‘tone’
multiplied by 2.
Inside the for loop we simply make the pin connected to the piezo speaker go high, wait a
short period of time, then go low, then wait another short period of time, then repeat.
digitalWrite(speakerPin, HIGH);
delayMicroseconds(tone);
digitalWrite(speakerPin, LOW);
delayMicroseconds(tone);
These repetitive clicks, of different lengths and with different pauses (of only
microseconds in length) in between clicks, makes the piezo produce a tone of varying
frequencies.
THE CIRCUIT:
Code :
/*
* Button
*
* Turns on and off a light emitting diode(LED) connected to digital
* pin 13, when pressing a pushbutton attached to pin 7.
* http://www.arduino.cc/en/Tutorial/Button
*/
int ledPin = 13; // choose the pin for the LED
int inputPin = 2; // choose the input pin (for a pushbutton)
int val = 0; // variable for reading the pin status
void setup() {
pinMode(ledPin, OUTPUT); // declare LED as output
pinMode(inputPin, INPUT); // declare pushbutton as input
}
void loop(){
val = digitalRead(inputPin); // read input value
if (val == HIGH) { // check if the input is HIGH
digitalWrite(ledPin, LOW); // turn LED OFF
} else {
digitalWrite(ledPin, HIGH); // turn LED ON
}
}
Upload the program to your board, and start toggling the LED on and off.
int value = 0;
void loop(){
if (digitalRead(inputPin1) == LOW) { value--; }
else if (digitalRead(inputPin2) == LOW) { value++; }
value = constrain(value, 0, 255);
analogWrite(ledPin, value);
In the light intensity is strong , it’s resistance decreases; however , when the light is
weak, this sensor’s resistance increases.
First Experiment:
Prepare: 1 X Ambient Light sensor , 1 X buzzer , some Jumper cable.
To build the circuit, attach buzzer’s long, positive leg (called the anode) to pin 6 . Connect
the cathode (the shorter, negative leg) directly to ground.
Attach the Ambient Light sensor pin to the 5 volt supply, the other side to Analog Pin 5 .
/*
Created By: Samleong
Created On: 2011-9-17
Website / More Infomation: http://www.b2cqshop.com
Email: [email protected]
*/
void setup()
{
pinMode(6,OUTPUT);
}
void loop()
{
www.bestqshop.com Ebay store: b2cqshop , E-qstore
www.b2cqshop.com Ebay store: b2cqshop , E-qstore
int val = analogRead(5);
char i,j;
if(val>1000)
{
for(i=0;i<80;i++) //Output a frequency of sound
{
digitalWrite(6,HIGH);
delay(1);
digitalWrite(6,LOW);
delay(1);
}
}
else if(val>800)
{
for(i=0;i<100;i++) //Output another frequency of sound
{
digitalWrite(6,HIGH);
delay(4);
digitalWrite(6,LOW);
delay(4);
}
}
}
THE CIRCUIT:
Code :
/* Analog Input
* Demonstrates analog input by reading an analog sensor on analog
* pin 0 and turning on and off a light emitting diode(LED) connected to
digital pin 13.
* The amount of time the LED will be on and off depends on the value obtained by
* analogRead().
* Created by David Cuartielles
* Modified 16 Jun 2009
* By Tom Igoe
* http://arduino.cc/en/Tutorial/AnalogInput
*/
int sensorPin = 0; // select the input pin for the potentiometer
int ledPin = 13; // select the pin for the LED
int sensorValue = 0; // variable to store the value coming from the sensor
void setup() {
pinMode(ledPin, OUTPUT); //declare the ledPin as an OUTPUT:
}
void loop() {
sensorValue = analogRead(sensorPin);// read the value from the sensor:
digitalWrite(ledPin, HIGH); // turn the ledPin on
delay(sensorValue); // stop the program for <sensorValue> milliseconds:
digitalWrite(ledPin, LOW); // turn the ledPin off:
delay(sensorValue); // stop the program for for <sensorValue> milliseconds:
}
void loop() {
sensorValue = analogRead(sensorPin);// read the value from the sensor:
digitalWrite(ledPin, HIGH); // turn the ledPin on
delay(sensorValue); // stop the program for <sensorValue> milliseconds:
digitalWrite(ledPin, LOW); // turn the ledPin off:
delay(sensorValue); // stop the program for for <sensorValue> milliseconds:
}
This will cause the LED to turn on when the value is above 512 (about halfway), you can
adjust the sensitivity by changing the threshold value.
Fading:
Let’s control the brightness of an LED directly from the potentiometer. To do this we need
to first change the pin the LED is connected to. Move the wire from pin 13 to pin 9 and
change one line in the code.
void loop() {
int value = analogRead(potPin) / 4;
analogWrite(ledPin, value);
}
Upload the code and watch as your LED fades in relation to your potentiometer spinning.
(Note: the reason we divide the value by 4 is the analogRead() function returns a value
from 0 to 1024 (10 bits), and analogWrite() takes a value from 0 to 255 (8 bits) )
Controlling a servo:
This is a really neat example and brings a couple of circuits together. Wire up the
servo , then open the example program Knob , then change one line of code.
THE CIRCUIT:
Code :
/*
* setup() - this function runs once when you turn your Arduino on
* We set the motors pin to be an output (turning the pin high (+5v) or low (ground) (-))
* rather than an input (checking whether a pin is high or low)
*/
void setup()
{
pinMode(motorPin, OUTPUT);
}
/*
* loop() - this function will start after setup finishes and then repeat
* we call a function called motorOnThenOff()
www.bestqshop.com Ebay store: b2cqshop , E-qstore
www.b2cqshop.com Ebay store: b2cqshop , E-qstore
*/
/*
* motorOnThenOff() - turns motor on then off
* (notice this code is identical to the code we used for
* the blinking LED)
*/
void motorOnThenOff(){
int onTime = 2500; //the number of milliseconds for the motor to turn on for
int offTime = 1000; //the number of milliseconds for the motor to turn off for
/*
* motorOnThenOffWithSpeed() - turns motor on then off but uses speed values as well
* (notice this code is identical to the code we used for
* the blinking LED)
*/
void motorOnThenOffWithSpeed(){
int onSpeed = 200; // a number between 0 (stopped) and 255 (full speed)
int onTime = 2500; //the number of milliseconds for the motor to turn on for
int offSpeed = 50; // a number between 0 (stopped) and 255 (full speed)
int offTime = 1000; //the number of milliseconds for the motor to turn off for
// motorOnThenOff();
motorOnThenOffWithSpeed();
// motorAcceleration();
Then upload the program. You can change the speeds by changing the variables
onSpeed and offSpeed.
Why stop at two speeds, why not accelerate and decelerate the motor. To do this
simply change the loop() code to read
// motorOnThenOff();
// motorOnThenOffWithSpeed();
motorAcceleration();
Then upload the program and watch as your motor slowly accelerates up to full speed
then slows down again. If you would like to change the speed of acceleration change the
variable delayTime (larger means a longer acceleration time).
THE CIRCUIT:
Code :
// Sweep
#include <Servo.h>
Servo myservo; // create servo object to control a servo
int pos = 0; // variable to store the servo position
void setup() {
myservo.attach(9); // attaches the servo on pin 9 to the servo object
}
void loop() {
for(pos = 0; pos < 180; pos += 1) // goes from 0 degrees to 180 degrees
{ // in steps of 1 degree
myservo.write(pos); // tell servo to go to position in variable 'pos'
delay(15); // waits 15ms for the servo to reach the position
}
for(pos = 180; pos>=1; pos-=1) // goes from 180 degrees to 0 degrees
{
myservo.write(pos); // tell servo to go to position in variable 'pos'
delay(15); // waits 15ms for the servo to reach the position
}
}
Potentiometer control:
We have yet to experiment with inputs but if you would like to read ahead, there is an
example program File > Servo > Knob. This uses a potentiometer (CIRC08) to control
the servo. You can find instructions online here: http://ardx.org/KNOB
Self timing:
While it is easy to control a servo using the Arduino's included library sometimes it is
fun to figure out how to program something yourself. Try it. We're controlling the pulse
directly so you could use this method to control servos on any of the Arduino's 20
available pins (you need to highly optimize this code before doing that).
int servoPin = 9;
void setup(){
pinMode(servoPin,OUTPUT);
}
void loop() {
int pulseTime = 2100; //(the number of microseconds
//to pause for (1500 90 degrees // 900 0 degrees 2100 180 degrees)
digitalWrite(servoPin, HIGH);
delayMicroseconds(pulseTime);
digitalWrite(servoPin, LOW);
delay(25);
}
Great ideas:
Servos can be used to do all sorts of great things, here are a few of our favorites.
Open Source Robotic Arm (uses a servo controller as well as the Arduino)
http://ardx.org/RARM
Servo Walker
http://ardx.org/SEWA
www.bestqshop.com Ebay store: b2cqshop , E-qstore
www.b2cqshop.com Ebay store: b2cqshop , E-qstore
THE CIRCUIT:
Code :
/* ---------------------------------------------------------
* | Arduino Experimentation Kit Example Code |
* | 8 More LEDs :. (74HC595 Shift Register) |
* ---------------------------------------------------------
*
* We have already controlled 8 LEDs however this does it in a slightly
* different manner. Rather than using 8 pins we will use just three
* and an additional chip.
*
*
*/
//Pin Definitions
//Pin Definitions
//The 74HC595 uses a serial communication
//link which has three pins
int data = 2;
www.bestqshop.com Ebay store: b2cqshop , E-qstore
www.b2cqshop.com Ebay store: b2cqshop , E-qstore
int clock = 3;
int latch = 4;
/*
* setup() - this function runs once when you turn your Arduino on
* We set the three control pins to outputs
*/
void setup()
{
pinMode(data, OUTPUT);
pinMode(clock, OUTPUT);
pinMode(latch, OUTPUT);
}
/*
* loop() - this function will start after setup finishes and then repeat
* we set which LEDs we want on then call a routine which sends the states to the
74HC595
*/
void loop() // run over and over again
{
int delayTime = 100; //the number of milliseconds to delay between LED updates
for(int i = 0; i < 256; i++){
updateLEDs(i);
delay(delayTime);
}
}
/*
* updateLEDs() - sends the LED states set in ledStates to the 74HC595
* sequence
*/
void updateLEDs(int value){
digitalWrite(latch, LOW); //Pulls the chips latch low
shiftOut(data, clock, MSBFIRST, value); //Shifts out the 8 bits to the shift register
digitalWrite(latch, HIGH); //Pulls the latch high displaying the data
}
//These are used in the bitwise math that we use to change individual LEDs
//For more details http://en.wikipedia.org/wiki/Bitwise_operation
int bits[] = {B00000001, B00000010, B00000100, B00001000, B00010000, B00100000,
B01000000, B10000000};
int masks[] = {B11111110, B11111101, B11111011, B11110111, B11101111, B11011111,
B10111111, B01111111};
/*
* changeLED(int led, int state) - changes an individual LED
* LEDs are 0 to 7 and state is either 0 - OFF or 1 - ON
*/
void changeLED(int led, int state){
ledState = ledState & masks[led]; //clears ledState of the bit we are addressing
if(state == ON){ledState = ledState | bits[led];} //if the bit is on we will add it to ledState
updateLEDs(ledState); //send the new LED state to the shift register
}
Our implementation.
Replace the loop() code with
int delayTime = 100; //the number of milliseconds
//to delay
//between LED updates
for(int i = 0; i < 8; i++){
changeLED(i,ON);
delay(delayTime);
}
for(int i = 0; i < 8; i++){
changeLED(i,OFF);
delay(delayTime);
}
Uploading this will cause the lights to light up one after another and then off in a
similar manner. Check the code and wikipedia to see how it works, or shoot us an e-mail if
you have questions.
More animations:
Now things get more interesting. If you look back to the code from (8 LED Fun) you
see we change the LEDs using digitalWrite(led, state), this is the same format as the
routine we wrote changeLED(led, state). You can use the animations you wrote for Blink
LEDs by copying the code into this sketch and changing all the digitalWrite()'s to
changeLED()'s. Powerful? Very. (you'll also need to change a few other things but follow
the compile errors and it works itself out).
www.bestqshop.com Ebay store: b2cqshop , E-qstore
www.b2cqshop.com Ebay store: b2cqshop , E-qstore
THE CIRCUIT:
Code :
// Serial controlled RGB Lamp
char buffer[18];
int red, green, yellow;
int RedPin = 9;
int GreenPin = 10;
int BluePin = 11;
void setup()
{
Serial.begin(9600);
Serial.flush();
pinMode(RedPin, OUTPUT);
pinMode(GreenPin, OUTPUT);
pinMode(BluePin, OUTPUT);
}
void loop()
{
if (Serial.available() > 0) {
int index=0;
delay(100); // let the buffer fill up
int numChar = Serial.available();
if (numChar>15) {
numChar=15;
}
while (numChar--) {
buffer[index++] = Serial.read();
}
splitString(buffer);
}
}
void splitString(char* data) {
Serial.print("Data entered: ");
Serial.println(data);
char* parameter;
parameter = strtok (data, " ,");
while (parameter != NULL) {
setLED(parameter);
parameter = strtok (NULL, " ,");
}
// Clear the text and serial buffers
for (int x=0; x<16; x++) {
buffer[x]='\0';
www.bestqshop.com Ebay store: b2cqshop , E-qstore
www.b2cqshop.com Ebay store: b2cqshop , E-qstore
}
Serial.flush();
}
void setLED(char* data) {
if ((data[0] == 'r') || (data[0] == 'R')) {
int Ans = strtol(data+1, NULL, 10);
Ans = constrain(Ans,0,255);
analogWrite(RedPin, Ans);
Serial.print("Red is set to: ");
Serial.println(Ans);
}
if ((data[0] == 'g') || (data[0] == 'G')) {
int Ans = strtol(data+1, NULL, 10);
Ans = constrain(Ans,0,255);
analogWrite(GreenPin, Ans);
Serial.print("Green is set to: ");
Serial.println(Ans);
}
if ((data[0] == 'b') || (data[0] == 'B')) {
int Ans = strtol(data+1, NULL, 10);
Ans = constrain(Ans,0,255);
analogWrite(BluePin, Ans);
Serial.print("Blue is set to: ");
Serial.println(Ans);
}
}
E.g. If you enter R255 the Red LED will display at full brightness.
If you enter R255, G255, then both the red and green LED’s will display at full
brightness.
Now enter R127, G100, B255 and you will get a nice purplish colour.
If you type, r0, g0, b0 all the LED’s will turn off.
The input text is designed to accept both a lowercase or upper-case R, G and B and
then a value from 0 to 255. Any values over 255 will be dropped down to 255 maximum.
You can enter a comma or a space in between parameters and you can enter 1, 2 or 3
LED values at any one time.
E.g.
r255 b100
r127 b127 g127
G255, B0
B127, R0, G255
Etc.
The internal structure Of LED display. This is the Common cathode 7seg-4digit LED
Display that we will use in this Experiment.
www.bestqshop.com Ebay store: b2cqshop , E-qstore
www.b2cqshop.com Ebay store: b2cqshop , E-qstore
First Experiment:
Prepare: 1 X 7seg-4digit LED Display , 8 X 220-ohm resistor , some Jumper
cable.
//设置控制各段的数字 IO 脚
int a = 12;
int b = 11;
int c = 10;
int d = 9;
int e = 8;
int f = 7;
int g = 6;
int dp = 5;
www.bestqshop.com Ebay store: b2cqshop , E-qstore
www.b2cqshop.com Ebay store: b2cqshop , E-qstore
int ls1 = 1; //最右边第一位数码管
int ls2 = 2; //第二位数码管
int ls3 = 3; //第三位数码管
int ls4 = 4; //第四位数码管
//显示数字 0 , 11111100
void digital_0(void)
{
unsigned char j;
digitalWrite(dp,LOW);//给数字 5 引脚低电平,熄灭小数点 DP 段
digitalWrite(g,LOW);//熄灭 g 段
for(j=7;j<=12;j++)//点亮其余段
digitalWrite(j,HIGH);
}
//显示数字 1 , 01100000
void digital_1(void)
{
unsigned char j;
digitalWrite(a,LOW);
for(j=5;j<=9;j++)
digitalWrite(j,LOW);
digitalWrite(b,HIGH);
digitalWrite(c,HIGH);
}
//显示数字 2
void digital_2(void)
{
unsigned char j;
digitalWrite(c,LOW);
digitalWrite(f,LOW);
digitalWrite(dp,LOW);
for(j=11;j<=12;j++)
digitalWrite(j,HIGH);
for(j=8;j<=9;j++)
digitalWrite(j,HIGH);
digitalWrite(g,HIGH);
}
//显示数字 3 22
void digital_3(void)
{
unsigned char j;
digitalWrite(e,LOW);
www.bestqshop.com Ebay store: b2cqshop , E-qstore
www.b2cqshop.com Ebay store: b2cqshop , E-qstore
digitalWrite(f,LOW);
digitalWrite(dp,LOW);
for(j=9;j<=13;j++)
digitalWrite(j,HIGH);
digitalWrite(g,HIGH);
}
//显示数字 4
void digital_4(void)
{
digitalWrite(a,LOW);
digitalWrite(d,LOW);
digitalWrite(e,LOW);
digitalWrite(dp,LOW);
digitalWrite(b,HIGH);
digitalWrite(c,HIGH);
digitalWrite(f,HIGH);
digitalWrite(g,HIGH);
}
//显示数字 5
void digital_5(void)
{
unsigned char j;
digitalWrite(b,LOW);
digitalWrite(e,LOW);
digitalWrite(dp,LOW);
digitalWrite(a,HIGH);
for(j=6;j<=7;j++)
digitalWrite(j,HIGH);
for(j=9;j<=10;j++)
digitalWrite(j,HIGH);
}
//显示数字 6
void digital_6(void)
{
unsigned char j;
digitalWrite(b,LOW);
digitalWrite(dp,LOW);
digitalWrite(a,HIGH);
for(j=6;j<=10;j++)
digitalWrite(j,HIGH);
}
www.bestqshop.com Ebay store: b2cqshop , E-qstore
www.b2cqshop.com Ebay store: b2cqshop , E-qstore
//显示数字 7
void digital_7(void)
{
unsigned char j;
for(j=5;j<=9;j++)
digitalWrite(j,LOW);
for(j=10;j<=12;j++)
digitalWrite(j,HIGH);
}
//显示数字 8
void digital_8(void)
{
unsigned char j;
digitalWrite(dp,LOW);
for(j=6;j<=12;j++)
digitalWrite(j,HIGH);
}
//显示数字 9
void digital_9(void)
{
unsigned char j;
digitalWrite(e,LOW);
digitalWrite(dp,LOW);
for(j=9;j<=12;j++)
digitalWrite(j,HIGH);
for(j=6;j<=7;j++)
digitalWrite(j,HIGH);
}
//显示----------------------------
void Display(unsigned char mun)
{
switch (mun) {
case 0:
digital_0();//显示数字 0
break;
case 1:
digital_1();
break;
case 2:
digital_2();
break;
www.bestqshop.com Ebay store: b2cqshop , E-qstore
www.b2cqshop.com Ebay store: b2cqshop , E-qstore
case 3:
digital_3();
break;
case 4:
digital_4();
break;
case 5:
digital_5();
break;
case 6:
digital_6();
break;
case 7:
digital_7();
break;
case 8:
digital_8();
break;
case 9:
digital_9();
break;
default: return;
// if nothing else matches, do the default
// default is optional
}
}
void setup()
{
int i;//定义变量
for(i=1;i<=12;i++)
pinMode(i,OUTPUT);//设置 1~12 引脚为输出模式
}
void loop()
{
unsigned char i, j, t;
while(1)
{
t = 1;
for(j=0; j<4 ; j++)
{
digitalWrite(j,LOW); //熄灭数码管使能端
}
www.bestqshop.com Ebay store: b2cqshop , E-qstore
www.b2cqshop.com Ebay store: b2cqshop , E-qstore
Connect it up
LCD RS pin to digital pin 12
LCD Enable pin to digital pin 11
LCD D4 pin to digital pin 5
LCD D5 pin to digital pin 4
LCD D6 pin to digital pin 3
LCD D7 pin to digital pin 2
Additionally, wire a 10K pot to +5V and GND, with it's wiper (output) to LCD screen's
VO pin (pin3).
The LCDs have a parallel interface, meaning that the microcontroller has to
manipulate several interface pins at once to control the display. The interface consists of
the following pins:
A register select (RS) pin that controls where in the LCD's memory you're writing
data to. You can select either the data register, which holds what goes on the screen, or
an instruction register, which is where the LCD's controller looks for instructions on what to
do next.
8 data pins (D0 -D7). The states of these pins (high or low) are the bits that you're
writing to a register when you write, or the values you're reading when you read.
There's also a display constrast pin (Vo), power supply pins (+5V and Gnd) and
LED Backlight (Bklt+ and BKlt-) pins that you can use to power the LCD, control the
display contrast, and turn on and off the LED backlight, respectively.
The process of controlling the display involves putting the data that form the image of
what you want to display into the data registers, then putting instructions in the instruction
register. The LiquidCrystal Library simplifies this for you so you don't need to know the
low-level instructions.
The LM35 series are precision integrated-circuit temperature sensors, whose output voltage
is linearly proportional to the Celsius (Centigrade) temperature.
Connection Diagrams
First Experiment:
Prepare: 1 X LM35 Temperature Sensor , 1 X 1602 LCD display , some Jumper cable.
Please check the Lesson 7 : 1602 LCD , to wire your LED screen to your Arduino .
Attach the LM35’s Pin Vout ( the middle pin) to your arduino’s Analog Pin 0 . Vcc to
+5v , Gnd to your arduino board’s gnd
www.bestqshop.com Ebay store: b2cqshop , E-qstore
www.b2cqshop.com Ebay store: b2cqshop , E-qstore
Code :
open the folder Project_8 , and open the Project_8.pde
In the program, when the Light is stronger, the resistance of sensor will be smaller, and
then the buzzer speak louder.
/*
The circuit:
* LCD RS pin to digital pin 12
* LCD Enable pin to digital pin 11
* LCD D4 pin to digital pin 5
* LCD D5 pin to digital pin 4
* LCD D6 pin to digital pin 3
* LCD D7 pin to digital pin 2
* 10K resistor:
* ends to +5V and ground
* wiper to LCD VO pin (pin 3)
*/
void setup() {
Serial.begin(9600);
// set up the LCD's number of rows and columns:
lcd.begin(16, 2);
}
void loop() {
val=analogRead(0);
dat=(125*val)>>8; //计算温度值
lcd.setCursor(0,0);
lcd.print("Tep: ");
lcd.setCursor(6,0);
lcd.print(dat);
www.bestqshop.com Ebay store: b2cqshop , E-qstore
www.b2cqshop.com Ebay store: b2cqshop , E-qstore
lcd.setCursor(10,0);
lcd.print("'C");
delay(10);
lcd.setCursor(0,1);
if(dat>18)
{
lcd.print("Warm! B2CQSHOP");
}
else
{
lcd.print("Cold! B2CQSHOP");
}
delay(500);
}
Connect it up
/*
Created By: Samleong
Created On: 2011-9-17
Website / More Infomation: http://www.b2cqshop.com
Email: [email protected]
*/
#define IR_IN 8 //Infrared receiver Pin
while(digitalRead(IR_IN));//high wait
Pulse_Width=TCNT1;
TCNT1=0;
if(Pulse_Width>=68&&Pulse_Width<=72)//4.5ms
{
www.bestqshop.com Ebay store: b2cqshop , E-qstore 100
www.b2cqshop.com Ebay store: b2cqshop , E-qstore
pulse_deal();
return;
}
else if(Pulse_Width>=34&&Pulse_Width<=36)//2.25ms
{
while(!(digitalRead(IR_IN)));//low wait
Pulse_Width=TCNT1;
TCNT1=0;
if(Pulse_Width>=7&&Pulse_Width<=10)//560us
{
return;
}
}
}
}
void setup()
{
unsigned char i;
pinMode(IR_IN,INPUT);//Set the infrared receiver input pin
// start serial port at 9600 bps:
Serial.begin(9600);
}
void loop()
{
timer1_init();//Timer initialization
while(1)
{
remote_decode(); //Decoding
remote_deal(); //Perform decoding
results
}
}
The picture is the IRM_3638 Infrared Receiver . The Pin of it is showing in the picture,
when you wire this project, please check it carefully .
Modulation:
The NEC protocol uses pulse distance encoding of the bits. Each pulse is a 560µs
long 38kHz carrier burst (about 21 cycles). A logical "1" takes 2.25ms to transmit, while a
logical "0" is only half of that, being 1.125ms. The recommended carrier duty-cycle is 1/4
or 1/3.
www.bestqshop.com Ebay store: b2cqshop , E-qstore 102
www.b2cqshop.com Ebay store: b2cqshop , E-qstore
Protocol :
The picture above shows a pulse train of the NEC protocol. With this protocol the
LSB is transmitted first. In this case Address $59 and Command $16 is transmitted. A
message is started by a 9ms AGC burst, which was used to set the gain of the earlier IR
receivers. This AGC burst is then followed by a 4.5ms space, which is then followed by the
Address and Command. Address and Command are transmitted twice. The second time
all bits are inverted and can be used for verification of the received message. The total
transmission time is constant because every bit is repeated with its inverted length. If
you're not interested in this reliability you can ignore the inverted values, or you can
expand the Address and Command to 16 bits each!
A command is transmitted only once, even when the key on the remote control
remains pressed. Every 110ms a repeat code is transmitted for as long as the key
remains down. This repeat code is simply a 9ms AGC pulse followed by a 2.25ms space
and a 560µs burst.
In this Experiment, we will use a little different IR Remote Control , which use
WD6122 chip . ( Extended NEC protocol )
Pay attention: When there is no infrared signals, the receiver’s output is High ;
while, it receives an signal, its output is LOW . We can check the received pulse
through the Oscilloscope, analyse the program according to the waveform.
The Command Values of the IR Remote Control’s key like the following picture.
This next circuit is a bit of a test. We combine what we learned about using transistors
to control a relay. A relay is an electrically controlled mechanical switch. Inside the little
plastic box is an electromagnet that, when energized, causes a switch to trip (often with a
very satisfying clicking sound). You can buy relays that vary in size from a quarter of the
size of the one in this kit up to as big as a fridge, each capable of switching a certain
amount of current. They are immensely fun because there is an element of the physical to
them. While all the silicon we've played with to this point is fun sometimes, you may just
want to wire up a hundred switches to control something magnificent. Relays give you the
ability to dream it up then control it with your Arduino. Now to using today's technology to
control the past. (The 1N4001 diode is acting as a flyback diode, for details on why it's
there visit: http://ardx.org/4001)
In this Project, we combine the Project of Measure temperature and show in the 1602
LCD .
CODE
/*
The circuit:
* LCD RS pin to digital pin 12
* LCD Enable pin to digital pin 11
* LCD D4 pin to digital pin 5
* LCD D5 pin to digital pin 4
* LCD D6 pin to digital pin 3
* LCD D7 pin to digital pin 2
* 10K resistor:
* ends to +5V and ground
* wiper to LCD VO pin (pin 3)
* LM35 Temperation sensor pin is Analog 0 ;
* The pin to control relay is Digital Pin 9
*/
void setup() {
Serial.begin(9600);
// set up the LCD's number of rows and columns:
lcd.begin(16, 2);
pinMode(relayPin,OUTPUT);
}
void loop() {
// clear the screen
val=analogRead(0);
dat=((125*val)>>8)+12; //Calculate the temperation
lcd.setCursor(0,0);
lcd.print("Tep: ");
lcd.setCursor(6,0);
lcd.print(dat);
lcd.setCursor(10,0);
lcd.print("'C");
delay(10);
lcd.setCursor(0,1);
if(dat>29)
{
lcd.print("open conditioner");
digitalWrite(relayPin,HIGH);
delay(1000);
}
else
{
lcd.print("Cold! B2CQSHOP");
digitalWrite(relayPin,LOW);
delay(1000);
}
delay(1000);
lcd.clear();
}