Beginner Kit For Arduino Tutorial
Beginner Kit For Arduino Tutorial
What is Arduino
www.dfrobot.com
00
www.dfrobot.com 00. What is Arduino 01
What is Arduino?
Arduino is an open-source electronics prototyping platform based on flexible, easy-to-use hardware and
software. It is intended for artists, designers, hobbyists and anyone interested in creating interactive objects
or developing environments.
Arduino can sense its environment by receiving inputs from sensors, and interact with its environment by controlling
lights, motors, or other actuators. The Arduino integrated development environment (IDE) is a cross-platform
application written in Java, and is derived from the IDE for the Processing programming language and wiring
projects. It can run independently and communicate with other software such as Flash, Processing, MaxMSP
and more. Arduino IDE is open source so you can download and share thousands of interactive projects for
free!
Here are some Arduino projects just to give your some ideas of tasks it can complete.
Arduino UNO
Now lets take a close look at the Arduino micro-controller and try to locate I/O ports (input/output) and on
board LEDs.
USB Port
Power
Indicator
DC Power Jack
(6~12V)
Go to
http://arduino.cc/en/Main/Software
to download the installation file
according to your operation system.
Open Arduino IDE and take a moment to move your mouse along each icon to get to know their functions.
Here we will use a very basic sample code, Blink to go through the whole process and test whether the
controller is working.
Open the LED blink example sketch. You will find it under File > Examples > 01.Basics > Blink .
www.dfrobot.com 00. What is Arduino 08
V
Ve from
instructions that the computer can understand.
d mpiling.
www.dfrobot.com 00. What is Arduino 09
The code we are using should not have errors since it is an example
code. If a code does have errors in it it will fail to verify.
Then sele t your C M port by sele ting Serial Port and sele ting the
C M port number you saw earlier. In our example C M36 is in use.
www.dfrobot.com 00. What is Arduino 10
C pload
Arduino.
After it is finished, the Arduino will run the code automatically and
the onboard LED will start to blink, just as programmed!
Review
...
Project 1
LED Flashing
www.dfrobot.com.cn
01
www.dfrobot.com 01. LED Flashing 01
Required Components:
x1 x1
DFROBOT
DFRduino
UNO v3.0[R3]
a
050
x2 x1 x1
Jumper
M/M Resistor 220R 5MM LED
Normally red wire indicates power supply (Vcc), black wire indicates
ground (GND), green wire indicates digital pins, blue wire indicates analog
pins, and white is other.
Double check the orientation of LED leads on the circuit. LEDs are po-
larized (will only work if placed in the circuit the correct way around). he
long leg of the LED connects to Vcc. (In this e ample Pin 10) and the short
leg connects to GND.
When you finish the circuit, connect the Arduino controller and computer
with the provided
2
Are
f Gnd 13 12 11 10 9 8 7 6 5 4 3 2 1 0
1
- +
5V
1
GND
-
3 2 3 1 3 2
RS
T 3V 5V GND VI
N 0 1 2 3 4 5
4 1 4 1
Open the Arduino IDE and enter the code as sample code 1-1 shows.
(We highly recommend you type code instead of copying and pasting so
that you can develop your coding skills and learn to code by heart.)
Any line of code that has // put Similar to single line comments, It is so called
Declaring variableisdeclaration.
variables a useful wayA
before it will not be compiled by any text between / * and * / will variable
of namingis for
anddata storage.In
storing values this
for
the complier. The Arduino IDE be ignored by the compiler. Once sample,
later use integers(int) are applied
by the program. Inte-
indicates this by turning the line again, the Arduino IDE will turn which
gers (intrepresent
) representnumbers
numbersrange
of code grey automatically. This this text grey to show that it is is from -32768
ranging fromto-32768
32767.The storage
to 32767.
allows you to write plain English commented out. This is a useful content
In decides
the above thewe variable
example, have
descriptions of the code you or way of annotating code. type.Here
input an we input 10.
integer: 10, an
integer.
is
others have written and makes it the variable name we have chosen.
easier for other people who might variable
Of name
course, you ismay
the name of
it the
not be able to read code to variable, standing
anything for theofvalue.Of
you like instead
understand. We refer to this as course, but
ledPin, youit'smay name
better it at the
to name will
commenting out. instead of
variable ledPin), but
according it'sfunction.
to its better to
name the
Here the variable according
ledPin indi-to its
function.lHere
cates the isvariable
that the LED ledPin
connected to
indicates10that
Pin-out the LED is connected
of Arduino.
to Pin-out
Use 10 of Arduino.
a semicolon (;;) to conclude
Please
the use a ";" Ifto you
declaration. conclude the
dont use
declaration.The
the semicolon, thesemicolon under
program will not
English input
recognise themethod is necessary.
declaration, so this is
important
A variable is a place to store a piece of data. It has a name, a value, and a type. In the above
e ample, int (integer) is the type, ledPin is the name and 10 is the value. In this e ample
were declaring a variable named ledPin of type int (integer), meaning the LED is connected
a variable? before you use them. Later on in the program, you can simply type the variable name rather
than typing out the data over and over again in each line of code, at which point its value will
be looked up and used by the IDE.
When you try to name a variable, start it with a letter followed with letter, number or
underscore. The language we are using (C) is case sensitive. There are certain names that you
cannot use such as main, if, while as these have their own pre-assigned function in the IDE.
Dont forget the variable names are case-sensitive!
www.dfrobot.com 01. LED Flashing 06
The setup() function In this e ple there is only The function format is as follows:
one line in the setup() function:
void setup () {} pinMode pinMode
No return Empty
pinMode(ledPin, OUTPUT); Mode
Pin
value function b kets (OUTPUT/INPUT)
The setup() function is read by This function is used to define pinMode configures the spec-
the Arduino when a sketch digital pin working behavior. Dig- ified digital pin to behave either
starts. It is used it to initialize ital pins are defined as an input as an input or an output. It
variables, pin modes, initialize (INPUT) or an output (OUTPUT). has two parameters:
libraries, etc. The setup function In the e ample above you can pin: the number of the pin
will only run once after each see brackets containing two whose mode you wish to set
power-up or reset of the Ar- parameters: the variable (ledPin) mode: INPUT, OUTPUT,
duino board. and its behaviour (OUTPUT). or INPUT_PULLUP.
Difference of INPUT is signal that sent from outside events to Arduino such as button.
OUTPUT is signal that sent from Arduino to the environment such as LED
INPUT and and buzzer.
OUTPUT
www.dfrobot.com 01. LED Flashing 07
The Arduino program must In this project we want the LED digitalWrite writes a HIGH (on)
include the setup () and loop () to turn on for 1 second and then or a LOW (off) value to a digital
function, otherwise it won t work. turn off for 1 second, and re- pin. If the pin has been
After creating a setup() function, peat this action over and over. configured as an OUTPUT
which initializes and sets the initial How can we express this in code? with pinMode(), its voltage will
values, the loop() function does be set to the
precisely what its name suggests, Look at the loop () function within
corresponding value: 5V (or
and loops consecutively, allowing the first statement.
3.3V on 3.3V boards) for HIGH
your program to change and This involves another function:
and 0V (ground) for LOW. Please
respond. Use it to actively control digitalWrite ().
note that digitalWrite() is ap-
the Arduino board. Here we want plied only under the condition
to control the LED constantly on digitalWrite(ledPin,HIGH);
that pinMode() is set as
and off every other second. OUTPUT. Why? Read on
How can we make that happen?
If pinMode configures a digital pin to behave as an input, you should use the
The Relation digitalRead() function. If the pin is configured as an output, then you should use
digitalWrite().
of pinMode(), NOTE: If you do not set the pinMode() to OUTPUT, and connect an LED to a pin, when
digitalWrite() calling digitalWrite(HIGH), the LED may appear dim. This is because without explic-
itly setting a pin-Mode(), digitalWrite() will enable the internal pull-up resistor, which
and acts like a large current-limiting resistor.
digitalRead() e.g. LED, Buzzer e.g. Press button control
pinMode(pin,OUTPUT) pinMode(pin,INPUT)
digitalWrite(pin,HIGH/LOW) digitalRead(pin)
www.dfrobot.com 01. LED Flashing 08
Next
delay(1000);
Breadboard
vi
ty Direction
LEDs
A light-emitting diode (LED) is a
two-lead semiconductor
light
diode, which emits light
when activated.
www.dfrobot.com.cn
02
www.dfrobot.com 02. S.O.S distress signal 01
Lets build a Morse code generator with the circuit we built in lesson 1. Morse code is a
method of transmitting text information as a series of on-off tones, lights, or clicks. We can
use a slow blink and quick blink of an LED instead of dots and dashes to indicate letters of
the alphabet. For example, SOS. According to Morse code, S is represented with 3 dots
which we can represent with a slow blink, while O is represented with 3 dashes which we
can represent with a quick blink.
digitalWrite(ledPin,HIGH);
delay(150);
digitalWrite(ledPin,LOW);
delay(100);
digitalWrite(ledPin,HIGH);
delay(150);
digitalWrite(ledPin,LOW);
delay(100);
digitalWrite(ledPin,HIGH); digitalWrite(ledPin,HIGH);
delay(400); delay(150);
digitalWrite(ledPin,LOW); digitalWrite(ledPin,LOW);
delay(100); delay(100);
digitalWrite(ledPin,HIGH); digitalWrite(ledPin,HIGH);
delay(400); delay(150);
digitalWrite(ledPin,LOW); digitalWrite(ledPin,LOW);
delay(100); delay(100);
It requires a lot of repetitive work to code like this. Is there a better way? Take a look at the following
sample code.
After uploading the code, you will see the LED blinking the S.O.S signal and repeating it after 5 seconds.
If you were to put the circuit in to a water-proof case, you could use it for sailing or hiking!
www.dfrobot.com 02. S.O.S distress signal 05
CODE
The first part of the two sketches are identical: we have initialized a variable and configured digital pin 10 to carry
out the output signal. In the main code loop(), you can find lines similar to the last project to turn the LED on
and off. The difference here is that the main code contains 3 independent blocks of statements.
The first block is to output 3 dots. So for the for statement in the
for(int x=0;x<3;x++){ sketch
digitalWrite(ledPin,HIGH); //configure LED on
delay(150); //delay 150 milliseconds for(int x=0;x<3;x++){
digitalWrite(ledPin,LOW); //configure LED off
delay(100); //delay 100 milliseconds
}
}
Condition is true
} If we wanted it to repeat 100 times, we can use the fol-
lowing code: for(int x=0;x<100;x++){}
Exercise
Lets make some traffic lights by us-
ing 3 digital pins to control 3 LED
lights. red light
5S 2S 5S 2S
yellow light
green light
Project 3
Interactive traffic lights
www.dfrobot.com
03
www.dfrobot.com 03. Interactive traffic lights 01
Interactive traffic lights
You will start your first interactive Arduino project in this lesson by making button-controlled traffic lights. When
the button is pressed, the lights will change for pedestrians to pass by.
Required Components:
x1 x1
DFROBOT
DFRduino
UNO v3.0[R3]
a
050
x13 x6 x1
Jumper Cables
M/M Resistor 220R Pushbutton
5MM LED
x2 5MM LED
x2
*Why are there 5 LEDs with 6 resistors?
5MM LED
x1
The extra resistor is a pull-down resistor for the button.
2
Are
f Gnd 13 12 11 10 9 8 7 6 5 4 3 2 1 0
1
5V
1
GND
3 2 3 1 3 2
RS
T 3V 5V GND VI
N 0 1 2 3 4 5
4 1 4 1
void setup() {
//configure all LEDs as output
pinMode(carRed, OUTPUT);
pinMode(carYellow, OUTPUT);
pinMode(carGreen, OUTPUT);
pinMode(pedRed, OUTPUT);
pinMode(pedGreen, OUTPUT);
pinMode(button, INPUT); //configure button as input
digitalWrite(carGreen, HIGH); //initialize green traffic
light on
digitalWrite(pedRed, LOW); //initialize red pedestrian light off }
void loop() {
int state = digitalRead(button);
// test if the button is pressed and if 5 seconds have passed after it is pressed
lately.
if(state == HIGH && (millis() - changeTime)> 5000){
//carry out the function of changing LED
changeLights();
}
}
void changeLights() {
www.dfrobot.com 03. Interactive traffic lights 04
digitalWrite(carGreen, LOW); //green traffic light off After uploading the sketch, take a
digitalWrite(carYellow, HIGH); //yellow traffic light on look at how LED changes. First,
delay(2000); //wait for 2 secs the green traffic light is
on and the red pedestrian
digitalWrite(carYellow, LOW); // yellow traffic light off
digitalWrite(carRed, HIGH); //red traffic light on light is on to allow cars to pass.
delay(1000); // wait for 1 sec for safety reason Once you press the button,
the pedestrian light changes
from red to green and the traffic
digitalWrite(pedRed, LOW); //red pedestrian light off light changes from just green to
digitalWrite(pedGreen, HIGH); //light pedestrian light on
green and red. There is then a
delay(crossTime); // time for crossing street delay allowing time for pedes-
trians to cross the street.
//blink green pedestrian light to notify pedestrians to pass soon When the delay comes to the
for (int x=0; x<10; x++) { end, the green pedestrian light
digitalWrite(pedGreen, HIGH); blinks to notify pedestrians.
delay(250); When this finishes, the lights
digitalWrite(pedGreen, LOW);
change back to the initial state
delay(250);
} with the green traffic light on
digitalWrite(pedRed, HIGH); //red pedestrian light on and red pedestrian light on.
delay(500);
The above codes do look
digitalWrite(carRed, LOW); //red traffic light off complex, but actually, it is not that
digitalWrite(carYellow, HIGH); //yellow traffic light on
difficult to understand the ideas in
delay(1000);
delay(1000); practice.
digitalWrite(carYellow, LOW); //yellow traffic light off
digitalWrite(carGreen, HIGH); //green traffic light on If you find it is difficult for you to
follow, try to draw a diagram like
changeTime = millis() // record the duration since last the one in the homework
change of Project 2. This will help
//back to the loop of main code
you to comprehend the
}
codes a little better. Good luck!
www.dfrobot.com 03. Interactive traffic lights 05
Code
Based on the previous 2 projects, most of the Then we enter the setup() function to configure the
codes should make sense for you. The codes start LED and button.
from a set of variable declarations, but we have used
a new term. It is e plained below:
Before we use int to store integers from -32768 to We have been quite familiar with pinMode() function
32767. The long command we use in this project can introduced in Project 1. Its difference with LED project
store integers from -2147483648 to 2147483647. lies in that the button should be set as INPUT.
Unsigned long cannot store negative numbers. So it In setup() function, please initialize the pedestrian and
stores integers from 0 to 4294967295. traffic light:
If we use int, we might go over the limit of 32 seconds digitalWrite(carGreen, HIGH); //initializing green traffic
(32768ml sec) and risk having errors in running the light on
sketch.As a result, we need another command to store digitalWrite(pedRed, LOW); //pedestrian red light on
integers and exclude negative numbers, such as
unsigned long whose limit is 49 days. The first line of the main sketch is to test the state of
button in pin9.
Can the Why can some variables store large amounts of data while some can t? It
depends on storage space of the variable, a bit like a box. For example,
box of variable the storage capacity of int is much smaller than unsigned long .
be infinite big? Just like a computer has a limited storage space, a micro-controller, like
your Arduino, is the same. The maximum storage space of Arduino
UNOs main chip (Atmega328 is 32k, so if we can save some storage
space, we should definitely do that.
There are various type of variables. Int and long are for integers, char is for
characters, float and double are for variables with decimal point.
www.dfrobot.com 03. Interactive traffic lights 06
In the setup() function, there is a Here we use the if() command This is a command inside the if()
new command digitalRead() ! to test conditions. command.
Push Button
The push button we used has
4 pins. When you press
a button or flip a lever, they
1 2
connect two pins together
so that electricity can
flow through them. Actually, Fig 3-2 Structure of push button (front
4 3
back & back)
there are only really two elec-
trical connections; inside the
switch package pins 1 and 4 are
1 2 1 2
connected together, as are 2 press the button Fig 3-3 schematic diagram of push
and 3. The little tactile 4 3 4 3 button
switches that are used in this
lesson have four connections.
You might have one with 2 pins,
but it works the same way.
What is pull-down
resistor?
2
Are
f Gnd 13 12 11 10 9 8 7 6 5 4 3 2 1 0
1
5V
Pull-down resistors are used in
electronic logic circuits to ensure
5V
that inputs to the arduino settle at
1
GND
pull-down resistor weakly "pulls"
the voltage of the wire it is
without pull-down
3 2 3 1 3 2
RS
T 3V 5V GND VI
N 0 1 2 3 4 5
0V
like it is disconnected. Since the
5V
5V
1. of any color
Turn on the LED
and achieve the LED lights display.
2.
up the column of LEDs in the
middle and have them pass the
light towards either edge.
www.dfrobot.com
04
www.dfrobot.com 04. Breathing LED 01
Breathing LED
In previous lessons, we learned how to turn a LED on and off by Arduino programming. It is also possible to
control the brightness of your LED as well. There are 6 digital pins marked with ~ on your controller. This
means that these pins can use a PWM signal. We will build a RGB LED fader by controlling PWM creating a
smooth brightening and dimmming of your LED as it gradually turns on and off.
Components
x1 x1
DFROBOT
DFRduino
UNO v3.0[R3]
a
050
x2 x1 x1
Jumper Cables
M/M Resistor 220R 5MM LED
www.dfrobot.com 04. Breathing LED 02
Circuit
The wiring diagram is the same as Project 1. If you are not clear about it,
go back to Project 1 and have a look.
2
Are
f Gnd 13 12 11 10 9 8 7 6 5 4 3 2 1 0
1
- +
5V
1
GND
3 2 3 1 3 2
RS
T 3V 5V GND VI
N 0 1 2 3 4 5
4 1 4 1
Sample Code 4-1 You will see the LED getting brighter and
fading constantly after uploading the code.
// Project 4
int ledPin = 10;
void setup() {
pinMode(ledPin,OUTPUT);
}
void loop(){
fadeOn(1000,5);
fadeOff(1000,5);
}
Most of the code we are already very familiar with, such as initializing variable declarations, setting pins,
setting up the for loop, as well as the function call.
The format of the
In the main code, we only use 2
This is a new command in the analogWrite command is
functions. You will have a clear
for() function. as below:
idea after checking one of them
as below. analogWrite(ledPin, value) Value between 0 and 255
void fadeOn(unsigned int time,int How can we send analog values analogWrite(pin,value)
increment){ to a digital pin? We use pins
marked with a on the end, PWM pins
for (byte value = 0 ; value <
such as D3, D5, D6, D9, D10 and
255; value+=increment){ The analogWrite() function is
D11, to output a variable amount
to assign the PWM pin an ana-
analogWrite(ledPin, value); of power to the LED. These tech-
log value between 0 and 255.
delay(time/(255/5)); nique of controlling power is known
} as Pulse Width Modulation , or
} PWM for short.
Roughly every 1/500 of a second, the PWM pins outputs a The green line is the cycle of the pulse. The per-
pulse using digital signals. By controlling the length of on centage of length of high voltage and low voltage
and off, it creates an equivalent effect of carrying out according to the value of analogWrite() function is
voltage between 0 volts and 5 volts. The length of pulse is known as the Duty Cycle. The duty cycle of the first
called pulse width so PWM refers to pulse pulse is 0. So the value is 0 and the brightness of LED
width modulation. is 0, equivalent to off. The longer the signal is HIGH,
Lets take a closer look at PWM. the brighter the LED is. The duty cycle of the last
pulse is 100%. So the value is 255 and the brightness
Pulse Width Modulation of LED is 255. Likewise, 50% is half brightness and 25
0% Duty Cycle - analogWrite(0)
% is relatively dimmer.
5v
PWM is widely used in controlling light brightness. We
0v
also use it to control the rotating speed of motors,
25% Duty Cycle - analogWrite(64)
such as wheels of vehicles powered by motors.
5v
0v
This chapter is over! Although we have used the same
50% Duty Cycle - analogWrite(127) hardware as in Project 1, Arduino is running a different
5v program, resulting in a completely different effect.
0v
We think that the Arduino is amazing and we
75% Duty Cycle - analogWrite(191)
5v hope by now you do too!
0v
1. Create a flickering flame effect using LEDs by controlling the value of PWM at random. Cover it with
paper and it will become a little lamp at night.
Materials:
1 red LED
2
1 220
You can look up to the references below for more explanations of various commands.
https://www.arduino.cc/en/Reference/HomePage
2. Try a more challenging project: Control the LED with 2 buttons, one to make it brighter, the other to make it
dimmer.
Reference: http://www.geek-workshop.com/thread-1054-1-1.html
Project 5
Colour RGB LED
www.dfrobot.com
05
www.dfrobot.com 05. Colourful RGB LED 01
Color RGB LED
Lets start with a new component: an RBG LED. This component combines red, blue and green LEDs and can
display various colors by adjusting the different values of each light. A computer monitor uses many RBG LEDs to
display an image. We will learn how to create different colors with RGB LED randomly in the this lesson.
Components
x1 x1
DFROBOT
DFRduino
UNO v3.0[R3]
a
050
x4 x3 x1
Jumper Cables
M/M Resistor 220R 5mm RGB LED
www.dfrobot.com 05. Colourful RGB LED 02
Circuit
Before building the circuit, try to identify whether your RGB LED is
common cathode or common anode. If you dont know how to do it, skip
to the last part of this lesson. In this project, we assume that you are
using a common cathode RBG LED.
2
Are
f Gnd 13 12 11 10 9 8 7 6 5 4 3 2 1 0
1
5V
1
GND
3 2 3 1 3 2
RS
T 3V 5V GND VI
N 0 1 2 3 4 5
4 1 4 1
void setup(){
pinMode(redPin, OUTPUT);
pinMode(greenPin, OUTPUT);
pinMode(bluePin, OUTPUT);
}
void loop(){
//R:0-255 G:0-255 B:0-255
colorRGB(random(0,255),random(0,255),random(0,255));
delay(1000);
}
First, we will configure the 3 LEDs contained within the RGB LED to 3 PWM pins so we can adjust them to
different colors by declaring 3 pins as an OUTPUT .
The main part of this program is to create a new command: colorRGB() which has 3 parameters to assign a
value to red, green and blue light between the values of 0 and 255.
This way, when we want to configure a color, we can simply assign values to this command instead of
repeating the analogWrite() command constantly.
Here we will introduce constrain() and random() . Red, green and blue are our constrained parameters.
Do try to look them up with websites we mentioned in They are constrained between 0 and 255 (which falls
the last homework first and see if you can under- into the range of PWM values). Values are generated
stand them. at random using the random() function.
The format of the constrain function is as follows: The format of random() is as below:
Minimum value
The constrain() function requires three parameters: The first variable of this function is the minimum value
x, a and b. and the second is the maximum. So we configure as
random(0,255) in this program.
x is a constraint number here, a is the minimum,
and b is the maximum.
RGB LED
The RGB LED has four leads. If you
are using a common cathode RGB
LED, there is one lead going to the
positive connection of each of the
single LEDs and a single lead that
is connected to all three negative
sides of the LEDs. Thats why it is
called common cathode. There is Fig. 5-2 How 3 LEDs form A RGB LED (Common Cathode)
no difference in appearance be-
tween common cathode and
common anode RGB LEDs,
however, you do need to pay
attention when assigning color
values. For example, for the
common cathode RGB
red is B-0 . For
the common anode RGB LED, red
is R-0, G-255, B-255 . How can
we adjust the RGB LED to Fig. 5-3 Remixing red, green and
change to different colors? blue to achieve various colors
Fig. 5-1 Colours generated from combined PWM values of different LEDs
between ference between common anode and common cathode in terms of their
appearance. However, there are two key differences in their application:
common anode
and common (1) Different connections: for the common anode, the common port
should be connected to 5V but bot GND, otherwise the LED fails to be lit.
cathode
RBG (2) Colour matching: the common anode RGB LED is totally different than
the common cathode RGB LED. The common anode RGB LED decodes in
LEDs the opposite way: R-0, G-255 and B-255.
Fig. 5-4 Common Cathode RGB Diagram Fig. 5-5 Common Anode RGB Diagram
www.dfrobot.com 05. Colourful RGB LED 07
Exercise
1. Based colors by
playing with different values.
2. Take your rainbow se uence LED and make each color fade so that the transition between each color is
smoother.
www.dfrobot.com 05. Colourful RGB LED 08
www.dfrobot.com
06
www.dfrobot.com 06. Alarm 01
Alarm
Lets try a new component: the buzzer! It generates sounds of different frequencies using sinusoidal
waves. If you connect a LED with the same sinusoidal wave, you can make your own alarm.
Component
x1 x1
DFROBOT
DFRduino
UNO v3.0[R3]
a
050
x2 x1
Jumper Cables
M/M Buzzer
www.dfrobot.com 06. Alarm 02
Hardware Connections
Make the following connections. Notice that the longer leg on the buzzer
is positive, and the shorter leg is negative. Connect the negative lead
to GND and the positive lead to Pin 8.
2
Are
f Gnd 13 12 11 10 9 8 7 6 5 4 3 2 1 0
1
5V
1
GND
3 2 3 1 3 2
RS
T 3V 5V GND VI
N 0 1 2 3 4 5
4 1 4 1
void setup(){
pinMode(8, OUTPUT);
}
void loop(){
for(int x=0; x<180; x++){
//convert angle of sinusoidal to radian measure
sinVal = (sin(x*(3.1412/180)));
//generate sound of different frequencies by sinusoidal value
toneVal = 2000+(int(sinVal*1000));
//Set a frequency for Pin-out 8
tone(8, toneVal);
delay(2); You can hear alarm of high and
} low pitches after uploading the
} code.
www.dfrobot.com 06. Alarm 04
Code
First, define two variables: Then we change this value to a Here we introduce 3 functions
sound frequency of an alarm: relevant to tone:
sinVal=(sin(x*(3.1412/180)));
www.dfrobot.com 06. Alarm 05
Components
The Buzzer
A buzzer is an electronic component that can generate sound. There
are generally two types: piezo buzzers and magnetic buzzers.
If you want to explore buzzers further, here are some project ideas:
Set up our circuit so that the LED changes in in unison with the sin function so that the light
intensit changes with the sound.
2. Using what ou learned in Project 3, can ou make a door bell? When the button is pressed, the
buzzer should make a sound.
Project 7
Temperature Alarm
www.dfrobot.com
07
www.dfrobot.com 07. Temperature Alarm 01
Temperature Alarm
We added a temperature sensor to the previous circuit to trigger the buzzer to make a sound when the
temperature reaches a certain range. This is our first project using an actuator responding to a sensor.
Component
x1 x1
DFROBOT
DFRduino
UNO v3.0[R3]
a
050
x5 x1 x1
Jumper Cables
M/M Buzzer Tem. Sensor
www.dfrobot.com 07. Temperature Alarm 02
Hardware
2
Are
f Gnd 13 12 11 10 9 8 7 6 5 4 3 2 1 0
1
5V
1
GND
3 2 3 1 3 2
RS
T 3V 5V GND VI
N 0 1 2 3 4 5
4 1 4 1
void setup(){
pinMode(8, OUTPUT); // configure pin of buzzer
Serial.begin(9600); // configure baud rate to 9600 bps
}
void loop(){
int val; //save the value of LM35
double data; // save the converted value of temperature
val=analogRead(0); //Connect LM35 to analog pin and read
value from it
data = (double) val * (5/10.24); //Convert the voltage value to
temperature value
After the code is successfully uploaded, open the serial monitor of Arduino IDE.
Read temperature value from the serial port. If you put your fingers on
the LM35 sensor, you will find the temperature rises immediately. Your
fingers are transferring heat to the sensor!
Most of the above codes are the same as those in Project 6. Almost all of the syntax has been mentioned in
previous projects. Hopefully you have some understanding about the variables and functions by now.
We initialize 3 variables at the top There are many functions for serial This is a new function, analogRead
of the program. port communication: (pin).
The Serial Port The serial port allows the Arduino to communicate with the external world
by transmitting and receiving data. There is at least one serial port in each
Arduino micro-controller, separately connected to digital pin 0 (RX/data
receive) and analog pin 1 (TX/data transmit). Digital pin 1 and 0 cannot be
used for I/O function when the serial port is in use. You download code to
the Arduino via the serial port. When downloading code, the USB will oc-
cupy digital pin RX and analog pin TX. The RX and TX pins can not receive
other signals during this, or there will be interference. The best way to use
these 2 pins is to insert components after downloading your code.
www.dfrobot.com 07. Temperature Alarm 06
In the following program, we If the temperature is higher than 3. Add single quotation mark to
evaluate the condition by using 27, The program runs the first part character and add double quota-
the if/else statement. of the program, following the if tion mark to character string.
statement to activate the buzzer. e.g. Serial.print(N); outputs N
The if/else statement format:
If not, it runs the else statement
if (expression) { to stop the buzzer. Serial.print(Hello world.);
Statement 1; Apart from detecting temperature outputs Hello world.
} else{ change for our alarm, we also
Statement 2;
need to display the temperature the The difference between println()
}
Arduino reads via the serial port. and print() is that println()
This function is known as a condi- We need to use the millis() has a new line character.
tional. It works as follows: function again to send out da-
An expression is specified. If the ta every 500ms. (See Project 3 for
Another common command is
conditions of the expression are more details if you are unsure.)
Serial.write(). It does not output in
true, statment 1 is executed and After the serial port has received
ASCII format but in a byte format.
statement 2 is skipped. data, how can we display it on the
Check the reference on Arduino.cc
If the expression is false, statment serial monitor?
if you are interested in finding out
2 is executed and statment 1 is more.
Serial.print(val);
skipped.
Serial.println(val); Serial.print(data);
Either statement 1 or 2 is to be
executed but simultaneous exe- print() works to convert val Is data a character string?
cution is prevented. Put in simple to a readable ASCII format Why does it output numbers?
terms, this is the Arduino making (standard text) output from the
a decision between two pre serial port. The answer is because we de-
determined variables. clared the variable in the program
if(data>27){ for(int There are various formats for this setup function to assign a number
x=0; x<180; x++){ function: to it.
1. numbers output as a num-
} ber
} else { e.g.: Serial.print(78); outputs 78
}
5V
If you want to learn more about this
component, you can consult the data +
sheet. his gives extra detail on how
a method for converting temperature Vout=10 mV/ C (TAMBIENT+1 C)
6.8k 200
data into voltage. FROM + 2C TO +40C
5% 1%
Formula of LM35
www.dfrobot.com 07. Temperature Alarm 08
Exercise
Exercise
Add a LED to the project above. When the temperature is in a defined range, make the LED turn on
and make the buzzer sound.
You can assign different colored LEDs and different buzzer sounds for different temperature ranges
E.g.:
- When the temperature is lower than 10 or higher than 35, a red LED turns on and the buzzer
makes a rapidly-oscillating sound
- When the temperature falls between 25 and 35, a yellow LED turns on and buzzer makes a
smooth-osciallating sound
- When the temperature falls between 10 and 25, a green LED turns on and the buzzer is off.
Project 8
Vibration Sensor
www.dfrobot.com
08
www.dfrobot.com 08. Vibration Sensor 01
Vibration Sensor
In this project we are going to use the tilt sensor included in your kit. The tilt sensor can detect basic motion
and orientation. It contains two contacts and a small metal ball. Once held at a particular orientation, the ball
bridges the two contacts and completes the circuit. We have also added an LED to this project. When the
sensor detects movement, the LED lis HIGH (on). When no movement is detected the LED is LOW (off).
Component
x1 x1
DFROBOT
DFRduino
UNO v3.0[R3]
a
050
x5 x1
Jumper Cables
M/M 5MM LED
Resistor 220R
x2 x1
Tilt Switch Sensor
www.dfrobot.com 08. Vibration Sensor 02
Circuit
A tilt sensor behaves much like a push button. You need to add a pull-
down resistor to the sensor to ensure the circuit is disconnected when
no signal is detected.
You also need to add a current-limiting resistor to the LED.
2
Are
f Gnd 13 12 11 10 9 8 7 6 5 4 3 2 1 0
1
5V
1
GND
3 2 3 1 3 2
RS
T 3V 5V GND VI
N 0 1 2 3 4 5
4 1 4 1
void setup() {
pinMode(SensorLED, OUTPUT); //configure LED as output mode
pinMode(SensorINPUT, INPUT); //configure tilt sensor as input mode
//when low voltage changes to high voltage, it triggers interrupt 1 and runs
the blink function
attachInterrupt(1, blink, RISING);
}
void loop(){
if(state!=0){ // if state is not 0
state = 0; // assign state value 0
digitalWrite(SensorLED,HIGH);
// turn on LED
delay(500); // delay for 500ms
}
else{
digitalWrite(SensorLED,LOW); // if not, turn off LED
}
Expected behaviour:
}
When we shake the board, the
LED is HIGH (on). When we stop
void blink(){ // interrupt function blink()
shaking, the LED is LOW (off).
state++; //once trigger the interrupt, the state
keeps increment
}
www.dfrobot.com 08. Vibration Sensor 04
Code
In this section we are going to examine the interrupt function that we used in the code. The program works as
follows: when there is no interruption to the program, the code keeps running and the LED stays LOW (off).
When there is an external event and the tilt sensor is activated, such as someone shaking the board, the pro-
gram runs the blink() function and state starts incrementing. When the if statement detects that the state
is no longer 0, it triggers the LED to be HIGH (on). At the same time, it resets state to 0 and waits for the next
interruption. If there is no interruption, the LED is LOW (off).
have different interrupt pins. tect any signal, pin 3 is LOW. When
- The function cannot read val- it detects a signal, it connects with 5
Check the references on arduino.cc
ues from the serial port. You
for details: http://arduino.cc/en/ might lose data connected from volts and this change the pin from
Reference/AttachInterrupt serial port. LOW to HIGH.
www.dfrobot.com 08. Vibration Sensor 05
Components
Tilt Sensor
The tilt sensor goes by many dif-
ferent names: ball switch, bead
switch, vibration switch, etc.
Though it has different names, its
g b f
working principles are same. In a d
simple terms, it is a switch made
up of a cylinder a small metal ball
c e
inside. When the metal ball rolls
a. Bronze Cover b. Bronze Bead c. Bronze Pipe
to either edge of the cylinder,
d. PC set e. Heat-shrinkable Pipe
they touch one of the contact
pins and the circuit is complete. f . Bronze Conductive Pin
Examine the diagram for further g . Phosphor Copper Pinch Cock
detail.
Fig. 8-2 Vibration Sensor Diagram
Project 9
Light Sensitive LED
www.dfrobot.com
09
www.dfrobot.com 09. Light Sensitive LED 01
Light Sensitive LED
Lets introduce a new sensor component: the photo diode. In simple terms, when the sensor detects light, its
resistance changes. The stronger light in the surrounding environment, the lower the resistance value the pho-
to diode will read. By reading the photo diode
s resistance value, we can work out the ambient lighting in an
environment. The photo diode provided in the starter kit is a typical light sensor.
In this project, we will make an automatic light that can adjust itself according to the ambient lighting around it.
When it is dark, the photo diode detects the change and triggers the light, and vice versa.
Components
x1 x1
DFROBOT
DFRduino
UNO v3.0[R3]
a
050
x5 x1 x1
Jumper Cables Ambient Light
M/M 5MM LED Sensor
Be aware that photo diodes are polarized, just like LEDs, so they will only work if connected the correct
way around.
The photo diode has to be connected with a 10k resistor rather than a 220 resistor.
2
Are
f Gnd 13 12 11 10 9 8 7 6 5 4 3 2 1 0
1
5V
1
GND
3 2 3 1 3 2
RS
T 3V 5V GND VI
N 0 1 2 3 4 5
4 1 4 1
void loop(){
val = analogRead(0); // Read voltage value ranging from 0 -1023 After uploading the code, you can
Serial.println(val); // read voltage value from serial monitor shine a flashlight on the photodi-
if(val<1000){ // If lower than 1000, turn off LED ode to alter the light levels in the
digitalWrite(LED,LOW); environment. When it is dark, the
}else{ // Otherwise turn on LED
should light up. When it is bright,
digitalWrite(LED,HIGH);
the LED should turn off.
}
delay(10); // delay for 10ms
}
www.dfrobot.com 09. Light Sensitive LED 04
Code
Photo Diode
Vin
The input voltage Vin(5V) is connected to 2 resistors. By measuring the
voltage of R2 as below, you can get the resistance value of photo diode.
R2 Vout
In our project, R1 is the 10k resistor and R2 is the photo diode. The re-
sistance value of R2 in dark is so high that it almost reaches 5V. Once pho-
tons are absorbed, the value of R2 will decrease, and so will its voltage Diagram of voltage divider
value. For this project it is preferable to use a fixed resistor ranging from
1k to 10k, otherwise the voltage dividing ratio is not obvious. This is why
in this project we have used a 10k resistor for R1. R2
Vout = x Vin
R1+R2
Formula of voltage divider
Project 10
How to Drive A Servo
www.dfrobot.com
10
www.dfrobot.com 10. How to Drive A Servo 01
How to Drive A Servo
Servos are ideal for embedded electronics applications because they can move to a specific position
accurately. Most servos can turn 180 degrees at maximum. Some even larger ones can turn to 360 degrees.
They can be used in mobile platforms for detection devices such as cameras and detectors of smart vehicles,
or in robotic joints.
Component
x3
Jumper Cables
M/M
x1
DFROBOT
DFRduino
UNO v3.0[R3]
x1
a
050
The servo has three leads. The color of the leads varies between servos but the red
lead is always 5V and GND will either be black or brown. The other lead is the
signal lead and this is usually orange or yellow. This signal lead is connected to
digital pin 9.
DFROBOT
DFRduino
UNO v3.0[R3]
a
050
void loop() {
for(pos = 0; pos < 180; pos += 1){ //servo turns from 0 to 180 in steps
of 1 degree
myservo.write(pos); //tell servo to go to position in variable 'pos'
delay(15); //wts 15ms for the servo to reach the position
}
for(pos = 180; pos>=1; pos-=1) { // servo turns from 180 to 0 in steps
of 1 degree
myservo.write(pos); //tell servo to go to position in variable 'pos' After uploading the sketch, you will
delay(15); //waits 15ms for the servo to reach the position see servo sweeping back and forth
} from 0 to 180 degrees.
}
www.dfrobot.com 10. How to Drive A Servo 04
Code
www.dfrobot.com
11
www.dfrobot.com 11. Controllable Servo 01
Controllable Servo
Weve learned to turn the servo to a specific an gleusing an external signal. In the new project, we will use a poten-
tiometer to control a servo. You can also modify this circuit by swapping the potentiometer for a sensor such as
a tilt switch, or changing the actuator to an LED. Get tinkering and use your imagination!
Component
x1 x1
DFROBOT
DFRduino
UNO v3.0[R3]
a
050
x3 x3
Jumper Cables Jumper Cables
M/M F/M
10K
Potentiometer Servo
x1
www.dfrobot.com 11. Controllable Servo 02
Circuit
This is a little different from our previous project as we are using a potentiometer. Potentiometers are sometimes
called variable resistors, and they are just that. By turning the knob, you are altering the electrical resistance of
the component. It has 3 pins: two side by side and one on top. Connect the side by side pins to 5V and GND on
the Arduino respectively, and the single pin on the opposite side of the potentiometer to the analog 0 pin on the
Arduino.
void setup() {
myservo.attach(9); //Attach the servo on pin 9 to the servo object.
}
void loop() {
val = analogRead(potpin); //eads the value of the potentiommeter
(value between 0 and 1023)
val = map(val, 0, 1023, 0, 179); // scale it to use it with the servo (value After uploading the sketch, you can
between 0 and 180) see the servo turn according to the
myservo.write(val); // sets the servo position according to the position of the potentiometer.
scaled value
delay(15); // wait for 15 ms to turn to certain position
}
www.dfrobot.com 11. Controllable Servo 04
Code
We declare to insert the <Servo.h> library first and Note that the "lower bounds" of either range may be
then define the potentiometer on Analog pin 0 to larger or smaller than the "upper bounds" so the map()
read its value. function may be used to reverse a range of numbers,
e.g.:
Now lets dig into the map function. y = map(x, 1, 50, 50, 1);
The format of map function is as below:
map(value, fromLow, fromHigh, The function also handles negative numbers well, so
toLow, toHigh) that this example is also valid and works well:
Parameters
value: the number to map
fromLow: the lower bound of the value's current range
fromHigh: the upper bound of the value's current
range
toLow: the lower bound of the value's target range
toHigh: the upper bound of the value's target range
www.dfrobot.com 11. Controllable Servo 05
Circuit
Potentiometer
A potentiometer is a simple knob that provides a variable resistance
which Arduino can read as an analog value
In this proje we connected three wires to the Arduino. The first went
to ground from one of the outer pins of the potentiometer. The second
went from 5 volts to the other outer pin of the potentiometer. The
third went from analog input 2 to the middle pin of the potentiometer. 3
A potentiometer works in a similar way to the voltage divider in project 9.
The potentiometer is divided in to 2 resistors by the shaft. By turning
1 2
the shaft of the potentiometer, we change the amount of resistnce on ei-
ther side of the wiper which is connected to the center pin of
the potentiometer. This changes the relative "closeness" of that pin to 5
volts and ground, giving us a different analog input. When the shaft is
turned all the way in one direction, there are 0 volts going to the pin, and
we read 0. When the shaft is turned all the way in the other direction to
the upper limit, there are 5 volts going to the pin, and we read 1023. In
between, analogRead() returns a number between 0 and 1023 that is
proportional to the amount of voltage being applied to the pin.
R1 R1
Vin Vin
R2 Vout R2 Vout
Project 12
Interactive Adjustable
RGB LED
www.dfrobot.com
12
www.dfrobot.com 12. Interactive Adjustable RGB LED 01
Interactive Adjustable RGB LED
In Project 5, we learned about how to adjust an RBG LED to various colors. This time we will try to make it
interactive by adding 3 potentiomters so that you can choose any color you want for your lighting at home.
Component
x1 x1
DFROBOT
DFRduino
UNO v3.0[R3]
a
050
x13 x3
Jumper Cables
M/M Resistor 220R
x3 x1
10K
Potentiometer 5mm RGB LED
www.dfrobot.com 12. Interactive Adjustable RGB LED 02
Circuit
void setup(){
pinMode(redPin,OUTPUT);
pinMode(greenPin,OUTPUT);
pinMode(bluePin,OUTPUT);
Serial.begin(9600); // Initialize the serial port
}
void loop(){
int potRed = analogRead(potRedPin); // read value from potentiometer of
red LED
int potGreen = analogRead(potGreenPin); // read value from potentiometer of
green LED
int potBlue = analogRead(potBluePin); // read value from potentiometer of
blue LED
int val1 = map(potRed,0,1023,0,255); //map the voltage value ranging from
0~ 1023 to analog value ranging from 0 ~255
int val2 = map(potGreen,0,1023,0,255);
int val3 = map(potBlue,0,1023,0,255);
// print value of red, green and blues LEDs from serial port
Serial.print("Red:");
Serial.print(val1);
Serial.print("Green:");
Serial.print(val2);
Serial.print("Blue:");
Serial.println(val3);
colorRGB(val1,val2,val3); // configure the analog value for RGB LED
}
}
www.dfrobot.com
13
www.dfrobot.com 13. DIY A Fan 01
DIY Fan
In this project, we will use a relay and a motor to make a small fan. A relay is an electrically operated switch that
allows you to turn on or off a circuit using voltage and/or current much higher than the Arduino can handle.
Component
x1 x1
DFROBOT
DFRduino
UNO v3.0[R3]
a
050
x9 x1 x1
Jumper Cables
M/M 5MM LED Pushbutton
Resistor 220R
x2 Relay
x1 130 Motor
x1
Fan
x1
www.dfrobot.com 13. DIY A Fan 02
Wiring
Connect the button with a 220 pull-down resistor in order to hold the logic signal near zero volts when the
button is disconnected. The relay has 6 pins. Pin 1 and 2 on the relay are input signals and are separately con-
nected to digital pin 3 and GND on the Arduino. Pins 3, 4, 5, and 6 on the relay are the output signals but we
will only use pin 4 and pin 6 at this time. A relay is similar to a push button, which has 2 connections as well.
void setup() {
pinMode(buttonPin, INPUT);
pinMode(relayPin, OUTPUT);
void loop() {
int reading = digitalRead(buttonPin); //read the value of button
if (buttonState == HIGH) {
relayState = !relayState;
}
}
}
digitalWrite(relayPin, relayState);
//change the last state of button After uploading the sketch, you
lastButtonState = reading; can control the relay and LED with
} the button.
www.dfrobot.com 13. DIY A Fan 04
Code
if (reading != lastButtonState) {
lastDebounceTime = millis();
}
if ((millis() - lastDebounceTime) > debounceDelay) {
if (reading != buttonState) {
}
}
When signals are received by the Arduino, the program does not oper-
ate on them immediately - it tests if the signal is correct and waits for
a certain time to confirm . If the signal is correct, the program will be
operating accordingly.
The reason the program tests for a correct signal is because there is a
bouncing process for the button when pressed. It might generate the
wrong signal, so we test it to solve the problem in hardware.
www.dfrobot.com 13. DIY A Fan 05
Hardware
Relay
A relay is an electrically operated switch that allows you to turn on or off a
circuit using voltage and/or current much higher than the Arduino can
normally handle. There is no connection between the low voltage circuit
operated by Arduino and the high power circuit - the relay isolates the
circuits from each other.
Lets take a look at the inner structure of relay:
NC COM
NO COM
Relays have 6 pins. Pins 1 and 2 are connected to the digital pin and
GND. We use these 2 pins to power the relay. There is a coil between
Pin 1 and Pin 2. When the circuit is HIGH, current flows in the coil, gen-
erates a magnetic field, closes the switch contacts and connects the
NO (Normally Open) to COM(commonpin. When the circuit is LOW,
no current runs in the coil, therefore the NC (Normally Closed)
connects to the common pin. We connect Pin 4 and Pin 6 to control the
switching on and off of the relay and the the LED.
www.dfrobot.com
14
www.dfrobot.com 14. IR Remote Controlled LED 01
IR Remote Controlled LED
An infrared receiver, or IR receiver, is hardware device that sends information from an infrared remote control to
another device by receiving and decoding signals. In general, the receiver outputs a code to uniquely identify the
infrared signal that it receives. This code is then used in order to convert signals from the remote control into a
format that can be understood by the other device. Because infrared is light, it requires line-of-sight visibility for
the best possible operation, but can however still be reflected by itemsProject
such as glass and walls. Poorly placed
IR receivers can result in what is called "tunnel vision", where the operational range of a remote control is
reduced because they are set so far back into the chassis of a device.
Warm-up Experiment:
Components
x1 x1
DFROBOT
DFRduino
UNO v3.0[R3]
a
050
VO
L+
FU
x3 x1 x1
STO NC/
P
VO
L-
EQ
1
S
RE T/
4 2 PT
8 6
9
www.dfrobot.com
DFRobot 14. IR Remote Controlled LED 02
Wiring
Note that the V-out lead of the infrared receiver must be connected
to Digital Pin 11 on the Arduino.
Vout GND 5V
2
Are
f Gnd 13 12 11 10 9 8 7 6 5 4 3 2 1 0
1
5V
1
GND
3 2 3 1 3 2
RS
T 3V 5V GND VI
N 0 1 2 3 4 5
4 1 4 1
We need to invoke the IRremote library first. Unzip the RAR and save it to the file Arduino libraries directory.
Run IRrecvDemo in the example.
If you dont know how to invoke a library in the Arduino IDE, refer back to the exercise in Project 5.
void setup(){
Serial.begin(9600); // configure the baud rate 9600
irrecv.enableIRIn(); //Boot infrared decoding
}
void loop() {
//test if receive decoding data and save it to variable results
if (irrecv.decode(&results)) {
// print data received in a hexadecimal
Serial.println(results.value, HEX);
irrecv.resume(); //wait for the next signal
}
}
www.dfrobot.com 14. IR Remote Controlled LED 04
After uploading the code, open the serial monitor of the Arduino IDE and
configure the baud rate 9600 in line with Serial.begin(9600).
If you keep pressing one button, the serial monitor reads FFFFFFFF.
If it is received properly in the serial port, the code should be six digits
starting with FD. If the controller does not send out the signal towards the
infrared receiver, it might receive wrong code as we can see below.
Component
x1 x1
DFROBOT
DFRduino
UNO v3.0[R3]
a
050
VO
L+
FU
x3 x1
STO NC/
P
VO
L-
EQ
1
S
RE T/
4 2 PT
x1
8 6
9
5MM LED
x1 Resistor 220R
www.dfrobot.com 14. IR Remote Controlled LED 06
Wiring
Based on the previous circuit, add an LED and a resistor. Connect the LED to digital
pin 10 and the signal LED of infrared receiver to digital pin 11.
Vout GND 5V
void setup(){
Serial.begin(9600);
irrecv.enableIRIn();
pinMode(ledPin,OUTPUT); // define LED as output signal
}
void loop() {
if (irrecv.decode(&results)) {
Serial.println(results.value, HEX);
//once receive code from power button, the state of LED is changed from HIGH
to LOW or from LOW to HIGH.
if(results.value == 0xFD00FF){
ledState = !ledState; //reverse
digitalWrite(ledPin,ledState); //change the state of LED
}
irrecv.resume();
}
}
www.dfrobot.com 14. IR Remote Controlled LED 08
Code
if (irrecv.decode(&results))
Once the Arduino receives data, the program does two things: first it
tests whether infrared code is received from the power button.
if(results.value == 0xFD00FF)
1. Combine the fan project with the current project. Add one more
function to the mini controller to control a LED and a fan.
2. Make a DIY a remote controlled project, e.g.: a small figure that can
move with servos controlled by infrared signals.
Project 15
IR Remote Controlled LED
Module
www.dfrobot.com
15
www.dfrobot.com 15. IR Remote Controlled LED Module 01
IR Remote Controlled LED Module
An 8-segment LED is a formed of electronic display device for displaying decimal numerals. It is an alternative
to more complex dot matrix displays. By controlling each LED in each segment connected to a digital pin,
numbers can be displayed on this LED.
Components
x1 x1
DFROBOT
DFRduino
UNO v3.0[R3]
a
050
Jumper Cables
M/M
x10 x8
Resistor 220R
x1
8-Segment LED
www.dfrobot.com 15. IR Remote Controlled LED Module 02
Wiring
The 8 segment LED has 10 pins. The 5 pins on the upper position are connected to digital
pin 2 to digital pin 5. The other 5 pins on the lower position with decimal point are
connected to digital pin 6 to 9. 8 resistors are included to limit the current for the LEDs.
2
Are
f Gnd 13 12 11 10 9 8 7 6 5 4 3 2 1 0
1
5V
1
GND
3 2 3 1 3 2
RS
T 3V 5V GND VI
N 0 1 2 3 4 5
4 1 4 1
void loop() {
// display number 0
int n0[8]={0,0,0,1,0,0,0,1};
//display the array of n0[8] in digital pin 2-9
for(int pin = 2; pin <= 9 ; pin++){
digitalWrite(pin,n0[pin-2]);
}
delay(500);
// display number1
int n1[8]={0,1,1,1,1,1,0,1};
// display the array of n1[8] in digital pin 2-9
for(int pin = 2; pin <= 9 ; pin++){
digitalWrite(pin,n1[pin-2]);
}
delay(500);
// display number 2
int n2[8]={0,0,1,0,0,0,1,1};
// display the array of n2[8] in digital pin 2-9
for(int pin = 2; pin <= 9 ; pin++){
digitalWrite(pin,n2[pin-2]);
}
delay(500);
// display number 3
int n3[8]={0,0,1,0,1,0,0,1};
// display the array of n3[8] in digital pin 2-9
for(int pin = 2; pin <= 9 ; pin++){
digitalWrite(pin,n3[pin-2]);
}
delay(500);
// display number 4
int n4[8]={0,1,0,0,1,1,0,1};
// display the array of n4[8] in digital pin 2-9
www.dfrobot.com 15. IR Remote Controlled LED Module 04
// display number 5
int n5[8]={1,0,0,0,1,0,0,1};
// display the array of n5[8] in digital pin 2-9
for(int pin = 2; pin <= 9 ; pin++){
digitalWrite(pin,n5[pin-2]);
}
delay(500);
// display number 6
int n6[8]={1,0,0,0,0,0,0,1};
//display the array of n6[8] in digital pin 2-9
for(int pin = 2; pin <= 9 ; pin++){
digitalWrite(pin,n6[pin-2]);
}
delay(500);
// display number 7
int n7[8]={0,0,1,1,1,1,0,1};
// display the array of n7[8] in digital pin 2-9
for(int pin = 2; pin <= 9 ; pin++){
digitalWrite(pin,n7[pin-2]);
}
delay(500);
// display number 8
int n8[8]={0,0,0,0,0,0,0,1};
// display the array of n8[8] in digital pin 2-9
for(int pin = 2; pin <= 9 ; pin++){
digitalWrite(pin,n8[pin-2]);
}
delay(500);
// display number 9
int n9[8]={0,0,0,0,1,1,0,1};
// display the array of n9[8] in digital pin 2-9
for(int pin = 2; pin <= 9 ; pin++){
After uploading the sketch, the LED
digitalWrite(pin,n9[pin-2]);
will display 0 to 9 repeatedly. To
}
delay(500); understand the code, you need to
} know the structure of 8-segment
LED.
www.dfrobot.com 15. IR Remote Controlled LED Module 05
Circuit
8-segment LED
Common All of the cathodes (negative terminals) or all of the anodes (positive
terminals) of the segment LEDs are connected and brought out to a
Cathode and
common pin; this is referred to as a "common cathode" or "common
Common Anode anode" device. The common pin of cathodes LEDs is connected to GND.
Differences When you configure this pin HIGH, it triggers the LED to be on. The
common pin of anode LEDs is connected to 5V. When you configure this
pin LOW, it triggers the LED to be off.
www.dfrobot.com 15. IR Remote Controlled LED Module
Code
a for loop.
with loops to
simplify things. Segment b a f g e d c - for(int
digitalWrite
}
for(int
pinMode ); for loop
digitalWrite );
} -
ray with value 0/LOW. So the b segment is on. When
and initialize the a segment is on.
. the f segment is
number etc.
Let us take a look at the code of displaying 0.
pin= 2 n0 [0] b segment on
int pin= 3 n0 [1] e a segment on
the concept of an pin= n0 [2] =0 f segment on
is a collection of variables that are accessed with an pin= 5 0[3] = 1 digitalWrite(5 1) g segment off
int pin= n0 [ ] e 0) e segment on
name it n0 pin= n0 [5] d segment on
that arrays are zero s. When declaring an pin= 8 n0 0 c segment on
array of one more element than your initializa-
pin= n0 ] =1 e 1)
Now it displays 0.
-
is tus is clear.
brackets (n0 ) elements.
. ll be introduced on
the following page.
www.dfrobot.com 15. IR Remote Controlled LED Module 07
Code 2
In this section, we will introduce an even simpler way to manipulate the loops for number 0 to 9 in the 8-
segment LED. In the sketch above, we created 10 arrays to display 0 to 9. This is a one-dimensional array. What
about creating a two-dimensional array to make it simpler?
void loop() {
for(int j = 0; j <= 9 ; j++){
numberShow(j); // call numberShow() function to
display 0-9.
delay(500);
}
}
www.dfrobot.com 15. IR Remote Controlled LED Module 08
Code 2
void numberShow(int
for(int
digitalWrite
}
void loop
al array element al array for(int
delay
}
will manipulate
}
dimensional arrays together to form
dimensional array. for loops manipulate
the variable is as
number[0][0] signed with a value, the function runs
int accordingly.
The
is . As it skips to the
the
// display number 0
int n0[8]={0,0,0,1,0,0,0,1};
// display the array of n0[8] in digital pin 2-9
for(int pin = 2; pin <= 9 ; pin++){
digitalWrite(pin,n0[pin-2]);
}
Components
x1 x1
DFROBOT
DFRduino
UNO v3.0[R3]
a
050
x13 x8 x1
Jumper Cables
M/M Resistor 220R 8-Segment LED
VO
L+
FU
x1 x1
STO NC/
P
VO
L-
IR Remote
0
EQ
1
S
RE T/
4 2 PT
IR Receiver controller
5 3
7
8 6
9
www.dfrobot.com 15. IR Remote Controlled LED Module 11
Wiring
2
Are
f Gnd 13 12 11 10 9 8 7 6 5 4 3 2 1 0
1
5V
1
GND
3 2 3 1 3 2
RS
T 3V 5V GND VI
N 0 1 2 3 4 5
4 1 4 1
void loop() {
//Evaluate whether decoding data are received and store the data in
variable results.
if (irrecv.decode(&results)) {
for(int i = 0; i <= 11; i++){
//Evaluate whether IR codes are received of press button 0 to 9.
if(results.value == codes[i]&& i <= 9){
numberShow(i); //Display 0 to 9 on
corresponding position of the LED module.
currentNumber = i; //Assign value displayed to
variable currentNumber.
Serial.println(i);
break;
}
Backward VO
//Evaluate whether decreasing IR codes are received and current
L +
FU
ST NC/
OP
value is not 9. VO
L -
Forward
0
5
numberShow(currentNumber); //The LED module displays 0-9
7
8 6
increasing value.
9
Serial.println(results.value, HEX); //View IR codes via serial port Codes downloaded, have a try to
monitor. press some press buttons as
irrecv.resume(); //Wait for next signal. shown in Fig. 15-4 to check the
} status of the LED module.
}
www.dfrobot.com 15. IR Remote Controlled LED Module 14
Code Review
int
int
: . This variable is
A number
represents a
h .
additional buttons on the remote controller.
www.dfrobot.com 15. IR Remote Controlled LED Module 15
First step:
There are three conditions require consideration. Firstly, the 8-segment
LED module should display 0 to 9 when corresponding press buttons are
pressed.Secondly, every time Backward is pressed, number displayed
decreases by 1 each time until it reaches 0. Thirdly, every time Forward is
pressed, number displayed increases by 1 each time until it reaches 0.
To decide for above conditions, we adopt if statement. What differs from
previous sample codes is that we use ifelse if.iWhat is the difference?An
evaluation expression usually follows else if but not for else.However,
neither else nor else if fails to work independently but an if statement is a
must.
Get back to the codes for three conditions mentioned below:
if
if
if
if
is based on whether data is received from results. Value
Using these applications, you can make a movable toy man. You could use servos, explained in the projects
mentioned before, and use different press buttons on the remote controller to have the servos move to
various angles. Use your imagination and have fun.