ks0077 (78,79) Super Learning Kit For Arduino PDF
ks0077 (78,79) Super Learning Kit For Arduino PDF
www.keyestudio.com 1
keyestudio
Content
1. Introduction..................................................................................................................................... 3
2. Component List............................................................................................................................... 3
3. Project List...................................................................................................................................... 9
4. Project Details............................................................................................................................... 10
Project 1: Hello World...............................................................................................................10
Project 2: LED Blinking............................................................................................................13
Project 3: PWM.........................................................................................................................15
Project 4: Traffic Light..............................................................................................................20
Project 5: LED Chasing Effect..................................................................................................23
Project 6: Button-Controlled LED............................................................................................ 25
Project 7: Active Buzzer............................................................................................................28
Project 8: Passive Buzzer.......................................................................................................... 31
Project 9: RGB LED................................................................................................................. 34
Project 10: Photo Resistor.........................................................................................................37
Project 11: Flame Sensor...........................................................................................................40
Project 12: LM35 Temperature Sensor..................................................................................... 44
Project 13: Tilt Switch...............................................................................................................47
Project 14: IR Remote Control..................................................................................................49
Project 15: Analog Value Reading............................................................................................ 58
Project 17: 1-digit LED Segment Display................................................................................ 64
Project 18: 4-digit LED Segment Display................................................................................ 71
Project 19: 8*8 LED Matrix......................................................................................................79
Project 20: 1602 LCD............................................................................................................... 83
Project 21: 9g Servo Control.....................................................................................................92
Project 22: 5V Stepper Motor................................................................................................... 97
Project 23: PIR Motion Sensor............................................................................................... 100
Project 24: Analog Gas Sensor................................................................................................102
Project 25: ADXL345 Three Axis Acceleration Module....................................................... 104
Project 26: HC-SR04 Ultrasonic Sensor.................................................................................109
Project 27: Joystick Module....................................................................................................112
Project 28: 5V Relay Module .................................................................................................114
Project 29: DS3231 Clock Module......................................................................................... 116
Project 30: DHT11 Temperature and Humidity Sensor .........................................................120
Project 31: Soil Humidity Sensor........................................................................................... 123
Project 32: RC522 RFID Module........................................................................................... 125
www.keyestudio.com 2
keyestudio
1. Introduction
keyestudio super learning kit is suitable for Arduino enthusiasts. This kit includes 32 projects with
detailed tutorials, starting from the basics to more complex projects. Different from other kits, it
adds some functional modules, such as RFID, temperature and humidity module. There is
connection diagram and code for each project, making it easy for you to learn.
2. Component List
1 LED - Blue 5
2 LED - Red 5
3 LED - Yellow 5
4 LED - RGB 1
www.keyestudio.com 3
keyestudio
5 220 Ω Resistor 8
6 10K Ω Resistor 5
7 1K Ω resistor 5
8 10K Ω Potentiometer 1
9 Buzzer (Active) 1
10 Buzzer (Passive) 1
www.keyestudio.com 4
keyestudio
12 Ball Tilt Sensor 2
13 Photo Resistor 3
14 Flame Sensor 1
www.keyestudio.com 5
keyestudio
20 2x16 LCD display 1
21 IR Receiver 1
22 IR Remote Control 1
23 Servo Motor 1
24 Stepper Driver 1
25 Stepper Motor 1
26 Joystick Module 1
www.keyestudio.com 6
keyestudio
27 Relay Module 1
www.keyestudio.com 7
keyestudio
DHT11 Temperature and
33 1
Humidity Sensor
36 RFID Card 1
37 Access Key 1
38 Pin Headers 40
www.keyestudio.com 8
keyestudio
39 830-hole Breadboard 1
40 Dupont Wire 10
41 Jumper Wire 30
43 USB Cable 1
3. Project List
www.keyestudio.com 9
keyestudio
Project 8: Passive Buzzer
Project 9: RGB LED
Project 10: Photo Resistor
Project 11: Flame Sensor
Project 12: LM35 Temperature Sensor
Project 13: Tilt Switch
Project 14: IR Remote Control
Project 15: Analog Value Reading
Project 16: 74HC595
Project 17: 1-digit LED Segment Display
Project 18: 4-digit LED Segment Display
Project 19: 8*8 LED Matrix
Project 20: 1602 LCD
Project 21: 9g Servo Control
Project 22: Stepper Motor
Project 23: PIR Motion Sensor
Project 24: Analog Gas Sensor
Project 25: ADXL345 Three Axis Acceleration Module
Project 26: HC-SR04 Ultrasonic Sensor
Project 27: Joystick Module
Project 28: 5V Relay Module
Project 29: DS3231 Clock Module
Project 30: DHT11 Temperature and Humidity Sensor
Project 31: Soil Humidity Sensor
Project 32: RC522 RFID Module
4. Project Details
Introduction
As for starters, we will begin with something simple. In this project, you only need an Arduino
and a USB Cable to start the "Hello World!" experiment. It is not only a communication test of
your Arduino and PC, but also a primer project for you to have your first try in the Arduino world!
Hardware Required
Arduino Board *1
USB Cable *1
www.keyestudio.com 10
keyestudio
Sample Code
After installing driver for Arduino, let's open Arduino software and compile code that enables
Arduino to print "Hello World!" under your instruction. Of course, you can compile code for
Arduino to continuously echo "Hello World!" without instruction. A simple If () statement will do
the instruction trick. With the onboard LED connected to pin 13, you can instruct the LED to blink
first when Arduino gets an instruction and then to print "Hello World!”.
//////////////////////////////////////////////////////////
int val;//define variable val
int ledpin=13;// define digital interface 13
void setup()
{
Serial.begin(9600);// set the baud rate at 9600 to match the software set up. When connected to
a specific device, (e.g. bluetooth), the baud rate needs to be the same with it.
pinMode(ledpin,OUTPUT);// initialize digital pin 13 as output. When using I/O ports on an
Arduino, this kind of set up is always needed.
}
void loop()
{
val=Serial.read();// read the instruction or character from PC to Arduino, and assign them to
Val.
if(val=='R')// determine if the instruction or character received is “R”.
{ // if it’s “R”,
digitalWrite(ledpin,HIGH);// set the LED on digital pin 13 on.
delay(500);
digitalWrite(ledpin,LOW);// set the LED on digital pin 13 off. delay(500);
Serial.println("Hello World!");// display“Hello World!”string.
}
}
////////////////////////////////////////////////////////////////
www.keyestudio.com 11
keyestudio
Test Result
Click to open the serial monitor, input an “ R”, LED 13 will blink once, PC will receive the
information from Arduino: Hello World
After choosing the proper port, the experiment is easy for you!
www.keyestudio.com 12
keyestudio
Project 2: LED Blinking
Introduction
Blinking LED experiment is quite simple. In the "Hello World!" program, we have come across
LED. This time, we are going to connect an LED to one of the digital pins rather than using
LED13 soldered to the board. Apart from an Arduino and a USB cable, you will need extra parts
as below:
Hardware Required
Red M5 LED*1
220Ω Resistor*1
Breadboard*1
Breadboard Jumper Wires
Circuit Connection
We follow below diagram from the experimental schematic link. Here we use digital pin 10. We
connect LED to a 220 ohm resistor to avoid high current damaging the LED.
www.keyestudio.com 13
keyestudio
Connection for UNO R3:
www.keyestudio.com 14
keyestudio
Sample Code
//////////////////////////////////////////////////////////
int ledPin = 10; // define digital pin 10.
void setup()
{
pinMode(ledPin, OUTPUT);// define pin with LED connected as output.
}
void loop()
{
digitalWrite(ledPin, HIGH); // set the LED on.
delay(1000); // wait for a second.
digitalWrite(ledPin, LOW); // set the LED off.
delay(1000); // wait for a second
}
//////////////////////////////////////////////////////////
Result
After uploading this program, in the experiment, you will see the LED connected to pin 10 turning
on and off, with an interval of approximate one second.
In this way, blinking LED experiment is now completed. Thank you!
Project 3: PWM
www.keyestudio.com 15
keyestudio
Introduction
PWM, short for Pulse Width Modulation, is a technique used to encode analog signal level into
digital ones. A computer cannot output analog voltage but only digital voltage values such as 0V
or 5V. So we use a high resolution counter to encode a specific analog signal level by modulating
the duty cycle of PMW. The PWM signal is also digitalized because in any given moment, fully
on DC power supply is either 5V (ON), or 0V (OFF). The voltage or current is fed to the analog
load (the device that uses the power) by repeated pulse sequence being ON or OFF. Being on, the
current is fed to the load; being off, it's not. With adequate bandwidth, any analog value can be
encoded using PWM. The output voltage value is calculated via the on and off time.
Output voltage = (turn on time/pulse time) * maximum voltage value
PWM has many applications: lamp brightness regulating, motor speed regulating, sound making,
etc.
The following are the three basic parameters of PMW:
Width
Level
Cycle
www.keyestudio.com 16
keyestudio
1. The amplitude of pulse width (minimum / maximum)
2. The pulse period (The reciprocal of pulse frequency in one second)
3. The voltage level(such as:0V-5V)
There are 6 PMW interfaces on Arduino, namely digital pin 3, 5, 6, 9, 10, and 11. In previous
experiments, we have done "button-controlled LED", using digital signal to control digital pin,
also one about potentiometer. This time, we will use a potentiometer to control the brightness of
the LED.
Hardware Required
Potentiometer*1
Red M5 LED*1
220Ω Resistor
Breadboard*1
Breadboard Jumper Wires
Circuit Connection
The input of potentiometer is analog, so we connect it to analog port, and LED to PWM port.
Different PWM signal can regulate the brightness of the LED.
www.keyestudio.com 17
keyestudio
Connection for 2560 R3:
Sample Code
In the program compiling process, we will use the analogWrite (PWM interface, analog value)
function. In this experiment, we will read the analog value of the potentiometer and assign the
value to PWM port, so there will be corresponding change to the brightness of the LED. One final
part will display the analog value on the screen. You can consider this as the "analog value
reading" project adding the PWM analog value assigning part. Below is a Sample Code for your
reference.
//////////////////////////////////////////////////////////
int potpin=0;// initialize analog pin 0
int ledpin=11;//initialize digital pin 11(PWM output)
int val=0;// Temporarily store variables' value from the sensor
void setup()
{
pinMode(ledpin,OUTPUT);// define digital pin 11 as “output”
Serial.begin(9600);// set baud rate at 9600
// attention: for analog ports, they are automatically set up as “input”
}
www.keyestudio.com 18
keyestudio
void loop()
{
val=analogRead(potpin);// read the analog value from the sensor and assign it to val
Serial.println(val);// display value of val
analogWrite(ledpin,val/4);// turn on LED and set up brightness(maximum output of PWM is 255)
delay(10);// wait for 0.01 second
}
//////////////////////////////////////////////////////////
Test Result
After uploading the program, when rotating the potentiometer knob, you can see the value change,
and also obvious brightness change of the LED on the breadboard.
www.keyestudio.com 19
keyestudio
Project 4: Traffic Light
Introduction
In the previous program, we have done the LED blinking experiment with one LED. Now, it’s
time to up the stakes to do a bit more complicated experiment-traffic light. Actually, these two
experiments are similar. While in this traffic light experiment, we use three LEDs with different
colors rather than an LED.
Hardware Required
Arduino Board *1
USB Cable *1
Red M5 LED*1
Yellow M5 LED*1
Green M5 LED*1
220Ω Resistor *3
Breadboard*1
Breadboard Jumper Wires
www.keyestudio.com 20
keyestudio
Circuit Connection
www.keyestudio.com 21
keyestudio
Sample Code
Since it is a simulation of traffic lights, the blinking time of each LED should be the same with
those in traffic lights system. In this program, we use Arduino delay () function to control delay
time, which is much simpler than C language.
//////////////////////////////////////////////////////////
int redled =10; // initialize digital pin 8.
int yellowled =7; // initialize digital pin 7.
int greenled =4; // initialize digital pin 4.
void setup()
{
pinMode(redled, OUTPUT);// set the pin with red LED as “output”
pinMode(yellowled, OUTPUT); // set the pin with yellow LED as “output”
pinMode(greenled, OUTPUT); // set the pin with green LED as “output”
}
void loop()
{
digitalWrite(greenled, HIGH);//// turn on green LED
delay(5000);// wait 5 seconds
digitalWrite(greenled, LOW); // turn off green LED
for(int i=0;i<3;i++)// blinks for 3 times
{
delay(500);// wait 0.5 second
digitalWrite(yellowled, HIGH);// turn on yellow LED
delay(500);// wait 0.5 second
digitalWrite(yellowled, LOW);// turn off yellow LED
}
delay(500);// wait 0.5 second
digitalWrite(redled, HIGH);// turn on red LED
delay(5000);// wait 5 second
digitalWrite(redled, LOW);// turn off red LED
}
//////////////////////////////////////////////////////////
Result
When the uploading process is completed, you can see traffic lights of your own design.
Note: this circuit design is very similar with the one in LED chasing effect.
The green light will be on for 5 seconds, and then off, followed by the yellow light blinking for 3
times, and then the red light is on for 5 seconds, repeatedly forming a cycle.
Experiment is now completed, thank you!
www.keyestudio.com 22
keyestudio
Project 5: LED Chasing Effect
Introduction
We can see many billboards composed of colorful LEDs. They are constantly changing to form
various effects. In this experiment, we compile a program to simulate chase effect.
Hardware Required
Red LED*6
220Ω Resistor *6
Breadboard Jumper Wires
Circuit Connection
www.keyestudio.com 23
keyestudio
Connection for 2560 R3:
Sample Code
//////////////////////////////////////////////////////////
int BASE = 2 ; // the I/O pin for the first LED
int NUM = 6; // number of LEDs
void setup()
{
for (int i = BASE; i < BASE + NUM; i ++)
{
pinMode(i, OUTPUT); // set I/O pins as output
}
}
void loop()
{
for (int i = BASE; i < BASE + NUM; i ++)
{
digitalWrite(i, LOW); // set I/O pins as “low”, turn off LEDs one by one.
delay(200); // delay
www.keyestudio.com 24
keyestudio
}
for (int i = BASE; i < BASE + NUM; i ++)
{
digitalWrite(i, HIGH); // set I/O pins as “high”, turn on LEDs one by one
delay(200); // delay
}
}
//////////////////////////////////////////////////////////
Result
Introduction
I/O port means interface for INPUT and OUTPUT. Up to now, we have only used the OUTPUT
function. In this experiment, we will try to use the INPUT function, which is to read the output
value of device connecting to it. We use 1 button and 1 LED using both input and output to give
you a better understanding of the I/O function. Button switch, familiar to most of us, is a switch
value (digital value) component. When it's pressed, the circuit is in closed (conducting) state.
www.keyestudio.com 25
keyestudio
Hardware Required
Button switch*1
Red M5 LED*1
220ΩResistor*1
10KΩ Resistor*1
Breadboard*1
Breadboard Jumper Wires
Circuit Connection
www.keyestudio.com 26
keyestudio
Sample Code
Now, let's begin the compiling. When the button is pressed, the LED will be on. Based on the
previous study, the coding should be easy for you. In this program, we add a statement of
judgment. Here, we use an if () statement.
Arduino IDE is based on C language, so statements of C language such as while, switch etc. can
certainly be used for Arduino program.
When we press the button, pin 7 will output high level. We can program pin 11 to output high
level and turn on the LED. When pin 7 outputs low level, pin 11 also outputs low level and the
LED remains off.
//////////////////////////////////////////////////////////
int ledpin=11;// initialize pin 11
int inpin=7;// initialize pin 7
int val;// define val
void setup()
{
pinMode(ledpin,OUTPUT);// set LED pin as “output”
pinMode(inpin,INPUT);// set button pin as “input”
}
void loop()
{
www.keyestudio.com 27
keyestudio
val=digitalRead(inpin);// read the level value of pin 7 and assign if to val
if(val==LOW)// check if the button is pressed, if yes, turn on the LED
{ digitalWrite(ledpin,LOW);}
else
{ digitalWrite(ledpin,HIGH);}
}
//////////////////////////////////////////////////////////
Test Result
When the button is pressed, LED is on, otherwise, LED remains off. In this way, the button
controlled LED experiment is completed. The simple principle of this experiment is widely used
in a variety of circuit and electric appliances. You can easily come across it in your daily life. One
typical example is when you press a certain key on your phone, the backlight will be on.
*******************************************************************************
Introduction
Active buzzer is widely used as a sound making element on computer, printer, alarm, electronic
toy, telephone, timer and more. It has an inner vibration source. Simply connect it with 5V power
supply, it can buzz continuously.
www.keyestudio.com 28
keyestudio
Hardware Required
Buzzer*1
Key *1
Breadboard*1
Breadboard Jumper Wires
Circuit Connection
www.keyestudio.com 29
keyestudio
When connecting the circuit, pay attention to the positive and negative poles of the buzzer. In the
photo, you can see there are red and black lines. When the circuit is finished, you can begin the
programming.
Sample Code
Result
After uploading the program, the buzzer experiment is completed. You can see the buzzer is
ringing.
www.keyestudio.com 30
keyestudio
Project 8: Passive Buzzer
Introduction
We can use Arduino to make many interactive works. The most commonly used one is
acoustic-optic display. All the previous experiment has something to do with LED. However, the
circuit in this experiment can produce sound. Normally, the experiment is done with a buzzer but
not a speaker while buzzer is more simpler and easier to use. The buzzer we introduced here is a
passive buzzer. It cannot be actuated by itself, but by external pulse frequencies. Different
frequency produces different sound. We can use Arduino to code the melody of a song, which is
quite fun and simple.
Hardware Required
Passive Buzzer*1
Key *1
Breadboard*1
Breadboard Jumper Wires
Circuit Connection
www.keyestudio.com 31
keyestudio
www.keyestudio.com 32
keyestudio
Sample Code
//////////////////////////////////////////////////////////
int buzzer=8;// select digital IO pin for the buzzer
void setup()
{
pinMode(buzzer,OUTPUT);// set digital IO pin pattern, OUTPUT to be output
}
void loop()
{ unsigned char i,j;//define variable
while(1)
{ for(i=0;i<80;i++)// output a frequency sound
{ digitalWrite(buzzer,HIGH);// sound
delay(1);//delay1ms
digitalWrite(buzzer,LOW);//not sound
delay(1);//ms delay
}
for(i=0;i<100;i++)// output a frequency sound
{ digitalWrite(buzzer,HIGH);// sound
delay(2);//2ms delay
digitalWrite(buzzer,LOW);//not sound
delay(2);//2ms delay
}
}
}
//////////////////////////////////////////////////////////
Result
After uploading the program, buzzer experiment is finished, you can hear the buzzer sound.
www.keyestudio.com 33
keyestudio
Project 9: RGB LED
Introduction
Hardware Required
Arduino Board* 1
USB Cable * 1
RGB LED * 1
www.keyestudio.com 34
keyestudio
Circuit Connection
www.keyestudio.com 35
keyestudio
Sample Code
//////////////////////////////////////////////////////////
int redpin = 11; //select the pin for the red LED
int bluepin =10; // select the pin for the blue LED
int greenpin =9;// select the pin for the green LED
int val;
void setup() {
pinMode(redpin, OUTPUT);
pinMode(bluepin, OUTPUT);
pinMode(greenpin, OUTPUT);
Serial.begin(9600);
}
void loop()
{
for(val=255; val>0; val--)
{
analogWrite(11, val);
analogWrite(10, 255-val);
analogWrite(9, 128-val);
delay(1);
}
for(val=0; val<255; val++)
{
analogWrite(11, val);
analogWrite(10, 255-val);
analogWrite(9, 128-val);
delay(1);
}
Serial.println(val, DEC);
}
//////////////////////////////////////////////////////////
Test Result
Directly copy the above code into arduino IDE, and click upload , wait for a few seconds,
you can see a full-color LED.
www.keyestudio.com 36
keyestudio
Project 10: Photo Resistor
Introduction
After completing all the previous experiments, you may acquire some basic understanding and
knowledge about Arduino application. We have introduced digital input and output, analog input
and PWM. Now, let’s begin the learning of sensor applications.
Photo Resistor (Photovaristor) is a resistor whose resistance varies from different incident light
strength. It's based on the photoelectric effect of semiconductor. If the incident light is intense, its
resistance reduces; if the incident light is weak, the resistance increases. Photovaristor is
commonly applied in the measurement of light, light control and photovoltaic conversion (convert
the change of light into the change of electricity).
Photo resistor is also being widely applied to various light control circuit, such as light control and
adjustment, optical switches, etc.
www.keyestudio.com 37
keyestudio
Hardware Required
Photo Resistor*1
Red M5 LED*1
10KΩ Resistor*1
220Ω Resistor*1
Breadboard*1
Breadboard Jumper Wires
Circuit Connection
www.keyestudio.com 38
keyestudio
Connection for 2560 R3:
Sample Code
After wiring, let's begin the program compiling. The program is similar to the PWM.
For change detail, please refer to the Sample Code below.
//////////////////////////////////////////////////////////
int potpin=0;// initialize analog pin 0, connected with photovaristor
int ledpin=11;// initialize digital pin 11, output regulating the brightness of LED
int val=0;// initialize variable va
void setup()
{
pinMode(ledpin,OUTPUT);// set digital pin 11 as “output”
Serial.begin(9600);// set baud rate at “9600”
}
void loop()
{
val=analogRead(potpin);// read the analog value of the sensor and assign it to val
Serial.println(val);// display the value of val
analogWrite(ledpin,val/4);// turn on the LED and set up brightness(maximum output value 255)
www.keyestudio.com 39
keyestudio
delay(10);// wait for 0.01
}
//////////////////////////////////////////////////////////
Test Result
After downloading the program, you can change the light strength around the photovaristor, and
see the corresponding brightness change of the LED. Photovaristors has various applications in
our everyday. You can make other interesting interactive projects based on this one.
*******************************************************************************
Introduction
Flame sensor (infrared receiving triode) is specially used for robots to find the fire source. This
sensor is of high sensitivity to flame.
Working Principle
Flame sensor is based on the principle that infrared ray is highly sensitive to flame. It has an
infrared receiving tube specially designed to detect fire, and then to convert the flame brightness
into fluctuating level signal. The signals are then input into the central processor and be dealt with
accordingly.
Schematic Diagram
The shorter lead of the receiving triode is for negative, the other one for positive. Connect
negative to 5V pin, positive to resistor; connect the other end of the resistor to GND, connect one
end of a jumper wire to a clip which is electrically connected to sensor positive, the other end to
analog pin. As shown below:
www.keyestudio.com 40
keyestudio
Hardware Required
Flame Sensor *1
Buzzer *1
10K Resistor *1
Breadboard Jumper Wires
Circuit Connection
1)Connecting buzzer:
Connect the controller board, prototype board, breadboard and USB Cable according to the
Arduino tutorial. Connect the buzzer to digital pin 8.
www.keyestudio.com 41
keyestudio
www.keyestudio.com 42
keyestudio
Experiment Principle
When it's approaching a fire, the voltage value read from the analog port will differ. If you use a
multimeter, you can see that when there is no fire approaching, the voltage it reads is around 0.3V;
when there is fire approaching, the voltage it reads is around 1.0V. The nearer the fire is, the
higher the voltage is.
So in the beginning of the program, you can initialize voltage value i (no fire value); Then,
continuously read the analog voltage value j and obtain difference value k=j-i; compare k with
0.6V (123 in binary) to determine whether there is a fire approaching or not; if yes, the buzzer will
buzz.
Sample Code
//////////////////////////////////////////////////////////
int flame=0;// select analog pin 0 for the sensor
int Beep=9;// select digital pin 9 for the buzzer
int val=0;// initialize variable
void setup()
{
pinMode(Beep,OUTPUT);// set LED pin as “output”
pinMode(flame,INPUT);// set buzzer pin as “input”
Serial.begin(9600);// set baud rate at “9600”
}
void loop()
{
val=analogRead(flame);// read the analog value of the sensor
Serial.println(val);// output and display the analog value
if(val>=600)// when the analog value is larger than 600, the buzzer will buzz
{
digitalWrite(Beep,HIGH);
}else
{
digitalWrite(Beep,LOW);
}
delay(500);
}
//////////////////////////////////////////////////////////
Result
This program can simulate an alarm when there is a fire. Everything is normal when there is no
fire; when there is fire, the alarm will be set off immediately.
www.keyestudio.com 43
keyestudio
Project 12: LM35 Temperature Sensor
Introduction
LM35 is a common and easy-to-use temperature sensor. It does not require other hardware. You
just need an analog port to make it work. The difficulty lies in compiling the code to convert the
analog value it reads into Celsius temperature.
Hardware Required
LM35*1
Breadboard*1
Breadboard Jumper Wires
Circuit Connection
www.keyestudio.com 44
keyestudio
Connection for UNO R3:
www.keyestudio.com 45
keyestudio
Sample Code
//////////////////////////////////////////////////////////
int potPin = 0; // initialize analog pin 0 for LM35 temperature sensor
void setup()
{
Serial.begin(9600);// set baud rate at”9600”
}
void loop()
{
int val;// define variable
int dat;// define variable
val=analogRead(0);// read the analog value of the sensor and assign it to val
dat=(125*val)>>8;// temperature calculation formula
Serial.print("Tep:");// output and display characters beginning with Tep
Serial.print(dat);// output and display value of dat
Serial.println("C");// display “C” characters
delay(500);// wait for 0.5 second
}
//////////////////////////////////////////////////////////
Test Result
After uploading the program, you can open the monitoring window to see the current temperature.
Shown below.
www.keyestudio.com 46
keyestudio
Project 13: Tilt Switch
Introduction
Hardware Required
Ball switch*1
Led *1
220Ω Resistor*1
10KΩ resistor*1
Breadboard Jumper Wires
Circuit Connection
www.keyestudio.com 47
keyestudio
Connection for 2560 R3:
Connect the controller board, shield, breadboard and USB cable according to Arduino tutorial.
Connect the LED to digital pin 8, ball switch to analog pin 5.
Experiment Principle
When one end of the switch is below horizontal position, the switch is on. The voltage of the
analog port is about 5V (1023 in binary). The LED will be on. When the other end of the switch is
below horizontal position, the switch is off. The voltage of the analog port is about 0V (0 in
binary). The LED will be off. In the program, we determine whether the switch is on or off
according to the voltage value of the analog port, whether it's above 2.5V (512 in binary) or not.
Sample Code
//////////////////////////////////////////////////////////
void setup()
{
pinMode(8,OUTPUT);// set digital pin 8 as “output”
}
void loop()
{
int i;// define variable i
www.keyestudio.com 48
keyestudio
while(1)
{
i=analogRead(5);// read the voltage value of analog pin 5
if(i>512)// if larger that 512(2.5V)
{
digitalWrite(8,LOW);// turn on LED
}
else// otherwise
{
digitalWrite(8,HIGH);// turn off LED
}
}
}
//////////////////////////////////////////////////////////
Test Result
Hold the breadboard with your hand. Tilt it to a certain extent, the LED will be on. If there is no
tilt, the LED will be off.
The principle of this experiment can be also applied to relay control.
Experiment now is completed. Thank you!
*******************************************************************************
www.keyestudio.com 49
keyestudio
Introduction
Working Principle
The built-in receiver converts the light signal it received from the sender into feeble electrical
signal. The signal will be amplified by the IC amplifier. After automatic gain control, band-pass
filtering, demodulation, wave shaping, it returns to the original code. The code is then input to the
code identification circuit by the receiver's signal output pin.
Infrared receiver has 3 pins. When you use it, connect VOUT to analog pin, GND to GND, VCC
to +5V.
www.keyestudio.com 50
keyestudio
Hardware Required
Circuit Connection
First, connect the controller board; then connect the infrared receiver as the above mentioned,
connect VOUT to digital pin 11, connect the LEDs with resistors and connect the resistors to
pin 2,3,4,5,6,7.
www.keyestudio.com 51
keyestudio
Connection for 2560 R3:
Experimental Principle
If you want to decode the code from the remote controller, you must first know how it's coded.
The coding method we use here is NEC protocol. Below is a brief introduction.
• NEC protocol:
Features:
(1) 8 bit address and 8 bit command length
(2) address and command are transmitted twice for reliability
(3) pulse distance modulation
(4) carrier frequency of 38 KHZ
(5) bit time of 1.125ms or 2.25ms
Protocol is as below:
• Definition of logical 0 and 1 is as below
www.keyestudio.com 52
keyestudio
• Pulse transmitted when button is pressed and immediately released
The picture above shows a typical 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 are not interested in this reliability, you can ignore the
inverted values, or you can expend the Address and Command to 16 bits each!
• Pulse transmitted when button is pressed and released after a period of time
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.
• Repeat pulse
Note: when the pulse enters the integrated receiver, there will be decoding, signal amplifying and
wave shaping process. So you need to make sure the level of the output is just the opposite from
that of the signal sending end. That is when there is no infrared signal, the output end is in high
level; when there is infrared signal, the output end is in low level. You can see the pulse of the
receiving end in the oscilloscope. Try to better understand the program based on what you see.
www.keyestudio.com 53
keyestudio
Sample Code
//////////////////////////////////////////////////////////
#include <IRremote.h>
int RECV_PIN = 11;
int LED1 = 2;
int LED2 = 3;
int LED3 = 4;
int LED4 = 5;
int LED5 = 6;
int LED6 = 7;
long on1 = 0x00FF6897;
long off1 = 0x00FF9867;
long on2 = 0x00FFB04F;
long off2 = 0x00FF30CF;
long on3 = 0x00FF18E7;
long off3 = 0x00FF7A85;
long on4 = 0x00FF10EF;
long off4 = 0x00FF38C7;
long on5 = 0x00FF5AA5;
long off5 = 0x00FF42BD;
long on6 = 0x00FF4AB5;
long off6 = 0x00FF52AD;
IRrecv irrecv(RECV_PIN);
decode_results results;
// Dumps out the decode_results structure.
// Call this after IRrecv::decode()
// void * to work around compiler issue
//void dump(void *v) {
// decode_results *results = (decode_results *)v
void dump(decode_results *results) {
int count = results->rawlen;
if (results->decode_type == UNKNOWN)
{
Serial.println("Could not decode message");
}
else
{
if (results->decode_type == NEC)
{
Serial.print("Decoded NEC: ");
}
else if (results->decode_type == SONY)
www.keyestudio.com 54
keyestudio
{
Serial.print("Decoded SONY: ");
}
else if (results->decode_type == RC5)
{
Serial.print("Decoded RC5: ");
}
else if (results->decode_type == RC6)
{
Serial.print("Decoded RC6: ");
}
Serial.print(results->value, HEX);
Serial.print(" (");
Serial.print(results->bits, DEC);
Serial.println(" bits)");
}
Serial.print("Raw (");
Serial.print(count, DEC);
Serial.print("): ");
for (int i = 0; i < count; i++)
{
if ((i % 2) == 1) {
Serial.print(results->rawbuf[i]*USECPERTICK, DEC);
}
else
{
Serial.print(-(int)results->rawbuf[i]*USECPERTICK, DEC);
}
Serial.print(" ");
}
Serial.println("");
}
void setup()
{
pinMode(RECV_PIN, INPUT);
pinMode(LED1, OUTPUT);
pinMode(LED2, OUTPUT);
pinMode(LED3, OUTPUT);
pinMode(LED4, OUTPUT);
pinMode(LED5, OUTPUT);
pinMode(LED6, OUTPUT);
pinMode(13, OUTPUT);
www.keyestudio.com 55
keyestudio
Serial.begin(9600);
irrecv.enableIRIn(); // Start the receiver
}
int on = 0;
unsigned long last = millis();
void loop()
{
if (irrecv.decode(&results))
{
// If it's been at least 1/4 second since the last
// IR received, toggle the relay
if (millis() - last > 250)
{
on = !on;
// digitalWrite(8, on ? HIGH : LOW);
digitalWrite(13, on ? HIGH : LOW);
dump(&results);
}
if (results.value == on1 )
digitalWrite(LED1, HIGH);
if (results.value == off1 )
digitalWrite(LED1, LOW);
if (results.value == on2 )
digitalWrite(LED2, HIGH);
if (results.value == off2 )
digitalWrite(LED2, LOW);
if (results.value == on3 )
digitalWrite(LED3, HIGH);
if (results.value == off3 )
digitalWrite(LED3, LOW);
if (results.value == on4 )
digitalWrite(LED4, HIGH);
if (results.value == off4 )
digitalWrite(LED4, LOW);
if (results.value == on5 )
digitalWrite(LED5, HIGH);
if (results.value == off5 )
digitalWrite(LED5, LOW);
if (results.value == on6 )
digitalWrite(LED6, HIGH);
if (results.value == off6 )
www.keyestudio.com 56
keyestudio
digitalWrite(LED6, LOW);
last = millis();
irrecv.resume(); // Receive the next value
}
}
//////////////////////////////////////////////////////////
Note:add IRremote folder into installation directory \Arduino\compiler libraries, or you will fail
to compile it.
Infrared remote library: https://github.com/shirriff/Arduino-IRremote
Program Function
Decode the coded pulse signal emitted by the remote controller, then execute corresponding action
according to the results of the decoding. In this way, you will be able to control your device with
remote controller.
Test Result
Done uploading, open the serial monitor, you can see the result as below.
www.keyestudio.com 57
keyestudio
Project 15: Analog Value Reading
Introduction
In this experiment, we will begin the study of analog I/O interfaces. On an Arduino, there are 6
analog interfaces numbered from 0 to 5. These 6 interfaces can also be used as digital ones
numbered as 14-19. Next, let's begin our project. Potentiometer used here is a typical output
component of analog value that is familiar to us.
Hardware Required
Potentiometer *1
Breadboard*1
Breadboard Jumper Wires
Circuit Connection
In this experiment, we will convert the resistance value of the potentiometer to analog ones and
display it on the screen. This is an application you need to master well for our future experiments.
www.keyestudio.com 58
keyestudio
www.keyestudio.com 59
keyestudio
Sample Code
The program compiling is simple. An analogRead () Statement can read the value of the interface.
The A/D acquisition of Arduino 328 is in 10 bits, so the value it reads is among 0 to 1023. One
difficulty in this project is to display the value on the screen, which is actually easy to learn.
First, you need to set the baud rate in voidsetup (). Displaying the value is a communication
between Arduino and PC, so the baud rate of the Arduino should match the the one in the PC's
software set up. Otherwise, the display will be messy codes or no display at all.
In the lower right corner of the Arduino software monitor window, there is a button for baud rate
set up. The set up here needs to match the one in the program. The statement in the program is
Serial.begin(); enclosed is the baud rate value, followed by statement for displaying. You can
either use Serial.print() or Serial.println() statement.
//////////////////////////////////////////////////////////
int potpin=0;// initialize analog pin 0
int ledpin=13;// initialize digital pin 13
int val=0;// define val, assign initial value 0
void setup()
{
pinMode(ledpin,OUTPUT);// set digital pin as “output”
Serial.begin(9600);// set baud rate at 9600
}
void loop()
{
digitalWrite(ledpin,HIGH);// turn on the LED on pin 13
delay(50);// wait for 0.05 second
digitalWrite(ledpin,LOW);// turn off the LED on pin 13
delay(50);// wait for 0.05 second
val=analogRead(potpin);// read the analog value of analog pin 0, and assign it to val
Serial.println(val);// display val’s value
}
//////////////////////////////////////////////////////////
Test Result
The Sample Code uses the built-in LED connected to pin 13.
Each time the device reads a value, the LED blinks. When you rotate the potentiometer knob, you
can see the displayed value change. The reading of analog value is a very common function since
most sensors output analog value. After calculation, you can get the corresponding value you
need.
Below figure shows the analog value it reads.
www.keyestudio.com 60
keyestudio
*******************************************************************************
Introduction
To put it simply, 74HC595 is a combination of 8-digit shifting register, memorizer and equipped
with tri-state output. Here, we use it to control 8 LEDs. You may wonder why use a 74HC595 to
control LED? Well, think about how many I/O it takes for an Arduino to control 8 LEDs? Yes, 8.
For an Arduino 168, it has only 20 I/O including analog ports. To save port resources, using
74HC595 enables us to use 3 digital I/O ports to control 8 LEDs!
www.keyestudio.com 61
keyestudio
Hardware Required
74HC595 chip*1
Red M5 LED*4
Green M5 LED*4
220Ω Resistor*8
Breadboard*1
Breadboard Jumper Wires
Circuit Connection
www.keyestudio.com 62
keyestudio
Connection for 2560 R3:
The circuit may seem complicated, but once you wire it in order, you will find it more easier!
Sample Code
//////////////////////////////////////////////////////////
int data = 2;// set pin 14 of 74HC595as data input pin SI
int clock = 5;// set pin 11 of 74hc595 as clock pin SCK
int latch = 4;// set pin 12 of 74hc595 as output latch RCK
int ledState = 0;
const int ON = HIGH;
const int OFF = LOW;
void setup()
{
pinMode(data, OUTPUT);
pinMode(clock, OUTPUT);
pinMode(latch, OUTPUT);
}
void loop()
www.keyestudio.com 63
keyestudio
{
for(int i = 0; i < 256; i++)
{
updateLEDs(i);
delay(500);
}
}
void updateLEDs(int value)
{
digitalWrite(latch, LOW);//
shiftOut(data, clock, MSBFIRST, ~value);// serial data “output”, high level first
digitalWrite(latch, HIGH);// latch
}
//////////////////////////////////////////////////////////
Test Result
After downloading the program, you can see 8 LEDs display 8-bit binary number.
*******************************************************************************
Introduction
LED segment displays are common for displaying numerical information. It's widely applied on
displays of electromagnetic oven, full automatic washing machine, water temperature display,
electronic clock, etc. It is necessary for us to learn how it works.
LED segment display is a semiconductor light-emitting device. Its basic unit is a light-emitting
diode (LED). LED segment display can be divided into 7-segment display and 8-segment
www.keyestudio.com 64
keyestudio
display according to the number of segments. 8-segment display has one more LED unit ( for
decimal point display) than 7-segment one.
According to the wiring method of LED units, LED segment display can be divided into common
anode display and common cathode display. Common anode display refers to the one that
combine all the anodes of LED units into one common anode (COM).
For the common anode display, connect the common anode (COM) to +5V. When the cathode
level of a certain segment is low, the segment is on; when the cathode level of a certain segment is
high, the segment is off.
For the common cathode display, connect the common cathode (COM) to GND. When the anode
level of a certain segment is high, the segment is on; when the anode level of a certain segment is
low, the segment is off.
Each segment of the display consists of an LED. So when you use it, you also need to use a
current-limiting resistor. Otherwise, LED will be burnt out. In this experiment, we use a common
cathode display. As we mentioned above, for common cathode display, connect the common
cathode (COM) to GND. When the anode level of a certain segment is high, the segment is on;
when the anode level of a certain segment is low, the segment is off.
Hardware Required
Circuit Connection
www.keyestudio.com 65
keyestudio
www.keyestudio.com 66
keyestudio
Sample Code
There are seven segments for numerical display, one for decimal point display. Corresponding
segments will be turned on when displaying certain numbers. For example, when displaying
number 1, b and c segments will be turned on. We compile a subprogram for each number, and
compile the main program to display one number every 2 seconds, cycling display number 0 ~ 9.
The displaying time for each number is subject to the delay time, the longer the delay time, the
longer the displaying time.
//////////////////////////////////////////////////////////
// set the IO pin for each segment
int a=7;// set digital pin 7 for segment a
int b=6;// set digital pin 6 for segment b
int c=5;// set digital pin 5 for segment c
int d=10;// set digital pin 10 for segment d
int e=11;// set digital pin 11 for segment e
int f=8;// set digital pin 8 for segment f
int g=9;// set digital pin 9 for segment g
int dp=4;// set digital pin 4 for segment dp
void digital_0(void) // display number 5
{
unsigned char j;
digitalWrite(a,HIGH);
digitalWrite(b,HIGH);
digitalWrite(c,HIGH);
digitalWrite(d,HIGH);
digitalWrite(e,HIGH);
digitalWrite(f,HIGH);
digitalWrite(g,LOW);
digitalWrite(dp,LOW);
}
void digital_1(void) // display number 1
{
unsigned char j;
digitalWrite(c,HIGH);// set level as “high” for pin 5, turn on segment c
digitalWrite(b,HIGH);// turn on segment b
for(j=7;j<=11;j++)// turn off other segments
digitalWrite(j,LOW);
digitalWrite(dp,LOW);// turn off segment dp
}
void digital_2(void) // display number 2
{
unsigned char j;
www.keyestudio.com 67
keyestudio
digitalWrite(b,HIGH);
digitalWrite(a,HIGH);
for(j=9;j<=11;j++)
digitalWrite(j,HIGH);
digitalWrite(dp,LOW);
digitalWrite(c,LOW);
digitalWrite(f,LOW);
}
void digital_3(void) // display number 3
{digitalWrite(g,HIGH);
digitalWrite(a,HIGH);
digitalWrite(b,HIGH);
digitalWrite(c,HIGH);
digitalWrite(d,HIGH);
digitalWrite(dp,LOW);
digitalWrite(f,LOW);
digitalWrite(e,LOW);
}
void digital_4(void) // display number 4
{digitalWrite(c,HIGH);
digitalWrite(b,HIGH);
digitalWrite(f,HIGH);
digitalWrite(g,HIGH);
digitalWrite(dp,LOW);
digitalWrite(a,LOW);
digitalWrite(e,LOW);
digitalWrite(d,LOW);
}
void digital_5(void) // display number 5
{
unsigned char j;
digitalWrite(a,HIGH);
digitalWrite(b, LOW);
digitalWrite(c,HIGH);
digitalWrite(d,HIGH);
digitalWrite(e, LOW);
digitalWrite(f,HIGH);
digitalWrite(g,HIGH);
digitalWrite(dp,LOW);
}
void digital_6(void) // display number 6
{
www.keyestudio.com 68
keyestudio
unsigned char j;
for(j=7;j<=11;j++)
digitalWrite(j,HIGH);
digitalWrite(c,HIGH);
digitalWrite(dp,LOW);
digitalWrite(b,LOW);
}
void digital_7(void) // display number 7
{
unsigned char j;
for(j=5;j<=7;j++)
digitalWrite(j,HIGH);
digitalWrite(dp,LOW);
for(j=8;j<=11;j++)
digitalWrite(j,LOW);
}
void digital_8(void) // display number 8
{
unsigned char j;
for(j=5;j<=11;j++)
digitalWrite(j,HIGH);
digitalWrite(dp,LOW);
}
void digital_9(void) // display number 5
{
unsigned char j;
digitalWrite(a,HIGH);
digitalWrite(b,HIGH);
digitalWrite(c,HIGH);
digitalWrite(d,HIGH);
digitalWrite(e, LOW);
digitalWrite(f,HIGH);
digitalWrite(g,HIGH);
digitalWrite(dp,LOW);
}
void setup()
{
int i;// set variable
for(i=4;i<=11;i++)
pinMode(i,OUTPUT);// set pin 4-11as “output”
}
void loop()
www.keyestudio.com 69
keyestudio
{
while(1)
{
digital_0();// display number 0
delay(1000);// wait for 1s
digital_1();// display number 1
delay(1000);// wait for 1s
digital_2();// display number 2
delay(1000); // wait for 1s
digital_3();// display number 3
delay(1000); // wait for 1s
digital_4();// display number 4
delay(1000); // wait for 1s
digital_5();// display number 5
delay(1000); // wait for 1s
digital_6();// display number 6
delay(1000); // wait for 1s
digital_7();// display number 7
delay(1000); // wait for 1s
digital_8();// display number 8
delay(1000); // wait for 1s
digital_9();// display number 9
delay(1000); // wait for 1s
}
}
//////////////////////////////////////////////////////////
Test Result
www.keyestudio.com 70
keyestudio
Project 18: 4-digit LED Segment Display
Introduction
In this experiment, we use an Arduino to drive a common cathode, 4-digit, 7-segment LED
display. For LED display, current-limiting resistors are indispensable. There are two wiring
methods for Current-limiting resistor. One is to connect one resistor for each cathode end, 4 in
total for d1-d4 cathode. An advantage for this method is that it requires fewer resistors, only 4. But
it cannot maintain consistent brightness, 1 the brightest, 8, the least bright.
Another method is to connect one resistor to each pin. It guarantees consistent brightness, but
requires more resistors. In this experiment, we use 8 Resistors (220Ω). We use 220Ω Resistors
because of no 100Ω resistor available. If you use 100Ω, the displaying is more brighter.
Circuit Connection
For 4-digit display, there are 12 pins in total. When you place the decimal point downward, the pin
on the lower left part is refer to as 1, the upper left part 12. Shown below.
www.keyestudio.com 71
keyestudio
Manual for LED Segment Display:
www.keyestudio.com 72
keyestudio
Connection for 2560 R3:
Sample Code
//////////////////////////////////////////////////////////
// display 1234
// select pin for cathode
int a = 1;
int b = 2;
int c = 3;
int d = 4;
int e = 5;
int f = 6;
int g = 7;
int dp = 8;
// select pin for anode
int d4 = 9;
int d3 = 10;
int d2 = 11;
int d1 = 12;
// set variable
long n = 1230;
int x = 100;
int del = 55; // fine adjustment for clock
void setup()
{
pinMode(d1, OUTPUT);
pinMode(d2, OUTPUT);
pinMode(d3, OUTPUT);
pinMode(d4, OUTPUT);
pinMode(a, OUTPUT);
pinMode(b, OUTPUT);
www.keyestudio.com 73
keyestudio
pinMode(c, OUTPUT);
pinMode(d, OUTPUT);
pinMode(e, OUTPUT);
pinMode(f, OUTPUT);
pinMode(g, OUTPUT);
pinMode(dp, OUTPUT);
}
/////////////////////////////////////////////////////////////
void loop()
{
Display(1, 1);
Display(2, 2);
Display(3, 3);
Display(4, 4);
}
///////////////////////////////////////////////////////////////
void WeiXuan(unsigned char n)//
{
switch(n)
{
case 1:
digitalWrite(d1,LOW);
digitalWrite(d2, HIGH);
digitalWrite(d3, HIGH);
digitalWrite(d4, HIGH);
break;
case 2:
digitalWrite(d1, HIGH);
digitalWrite(d2, LOW);
digitalWrite(d3, HIGH);
digitalWrite(d4, HIGH);
break;
case 3:
digitalWrite(d1,HIGH);
digitalWrite(d2, HIGH);
digitalWrite(d3, LOW);
digitalWrite(d4, HIGH);
break;
case 4:
digitalWrite(d1, HIGH);
digitalWrite(d2, HIGH);
www.keyestudio.com 74
keyestudio
digitalWrite(d3, HIGH);
digitalWrite(d4, LOW);
break;
default :
digitalWrite(d1, HIGH);
digitalWrite(d2, HIGH);
digitalWrite(d3, HIGH);
digitalWrite(d4, HIGH);
break;
}
}
void Num_0()
{
digitalWrite(a, HIGH);
digitalWrite(b, HIGH);
digitalWrite(c, HIGH);
digitalWrite(d, HIGH);
digitalWrite(e, HIGH);
digitalWrite(f, HIGH);
digitalWrite(g, LOW);
digitalWrite(dp,LOW);
}
void Num_1()
{
digitalWrite(a, LOW);
digitalWrite(b, HIGH);
digitalWrite(c, HIGH);
digitalWrite(d, LOW);
digitalWrite(e, LOW);
digitalWrite(f, LOW);
digitalWrite(g, LOW);
digitalWrite(dp,LOW);
}
void Num_2()
{
digitalWrite(a, HIGH);
digitalWrite(b, HIGH);
digitalWrite(c, LOW);
digitalWrite(d, HIGH);
digitalWrite(e, HIGH);
digitalWrite(f, LOW);
digitalWrite(g, HIGH);
www.keyestudio.com 75
keyestudio
digitalWrite(dp,LOW);
}
void Num_3()
{
digitalWrite(a, HIGH);
digitalWrite(b, HIGH);
digitalWrite(c, HIGH);
digitalWrite(d, HIGH);
digitalWrite(e, LOW);
digitalWrite(f, LOW);
digitalWrite(g, HIGH);
digitalWrite(dp,LOW);
}
void Num_4()
{
digitalWrite(a, LOW);
digitalWrite(b, HIGH);
digitalWrite(c, HIGH);
digitalWrite(d, LOW);
digitalWrite(e, LOW);
digitalWrite(f, HIGH);
digitalWrite(g, HIGH);
digitalWrite(dp,LOW);
}
void Num_5()
{
digitalWrite(a, HIGH);
digitalWrite(b, LOW);
digitalWrite(c, HIGH);
digitalWrite(d, HIGH);
digitalWrite(e, LOW);
digitalWrite(f, HIGH);
digitalWrite(g, HIGH);
digitalWrite(dp,LOW);
}
void Num_6()
{
digitalWrite(a, HIGH);
digitalWrite(b, LOW);
digitalWrite(c, HIGH);
digitalWrite(d, HIGH);
digitalWrite(e, HIGH);
www.keyestudio.com 76
keyestudio
digitalWrite(f, HIGH);
digitalWrite(g, HIGH);
digitalWrite(dp,LOW);
}
void Num_7()
{
digitalWrite(a, HIGH);
digitalWrite(b, HIGH);
digitalWrite(c, HIGH);
digitalWrite(d, LOW);
digitalWrite(e, LOW);
digitalWrite(f, LOW);
digitalWrite(g, LOW);
digitalWrite(dp,LOW);
}
void Num_8()
{
digitalWrite(a, HIGH);
digitalWrite(b, HIGH);
digitalWrite(c, HIGH);
digitalWrite(d, HIGH);
digitalWrite(e, HIGH);
digitalWrite(f, HIGH);
digitalWrite(g, HIGH);
digitalWrite(dp,LOW);
}
void Num_9()
{
digitalWrite(a, HIGH);
digitalWrite(b, HIGH);
digitalWrite(c, HIGH);
digitalWrite(d, HIGH);
digitalWrite(e, LOW);
digitalWrite(f, HIGH);
digitalWrite(g, HIGH);
digitalWrite(dp,LOW);
}
void Clear() // clear the screen
{
digitalWrite(a, LOW);
digitalWrite(b, LOW);
digitalWrite(c, LOW);
www.keyestudio.com 77
keyestudio
digitalWrite(d, LOW);
digitalWrite(e, LOW);
digitalWrite(f, LOW);
digitalWrite(g, LOW);
digitalWrite(dp,LOW);
}
void pickNumber(unsigned char n)// select number
{
switch(n)
{
case 0:Num_0();
break;
case 1:Num_1();
break;
case 2:Num_2();
break;
case 3:Num_3();
break;
case 4:Num_4();
break;
case 5:Num_5();
break;
case 6:Num_6();
break;
case 7:Num_7();
break;
case 8:Num_8();
break;
case 9:Num_9();
break;
default:Clear();
break;
}
}
void Display(unsigned char x, unsigned char Number)// take x as coordinate and display number
{
WeiXuan(x);
pickNumber(Number);
delay(1);
Clear() ; // clear the screen
}
//////////////////////////////////////////////////////////
www.keyestudio.com 78
keyestudio
Result
Download the above code to the controller board, you can see the LED display shows the number
1234.
Note: if it’s not displaying correctly, check the wiring.
******************************************************************************
Introduction
With low-voltage scanning, LED dot-matrix has some advantages such as power saving, long
service life, low cost, high brightness, wide angle of view, long visual range, waterproof, and
numerous specifications. LED dot-matrix display can meet the needs of different applications,
thus has a broad development prospect. This time, we will conduct an LED dot-matrix experiment
to experience its charm firsthand.
Hardware Required
1 * Uno Board
1 * 8*8 Dot Matrix
8 * Resistor (220Ω)
1 * Breadboard
1 * USB Cable
Several* Jumper Wires
Circuit Connection
www.keyestudio.com 79
keyestudio
The external view of a dot-matrix is shown as follows:
The principle of 74HC595 has been previously illustrated. One chip is used to control the rows of
the dot-matrix, while the other chip is used to control the columns.
www.keyestudio.com 80
keyestudio
Connection for UNO R3:
//////////////////////////////////////////////////////////
// set an array to store character of “0”
unsigned char Text[]={0x00,0x1c,0x22,0x22,0x22,0x22,0x22,0x1c};
void Draw_point(unsigned char x,unsigned char y)// point drawing function
{ clear_();
digitalWrite(x+2, HIGH);
digitalWrite(y+10, LOW);
delay(1);
}
www.keyestudio.com 81
keyestudio
void show_num(void)// display function, call point drawing function
{
unsigned char i,j,data;
for(i=0;i<8;i++)
{
data=Text[i];
for(j=0;j<8;j++)
{
if(data & 0x01)Draw_point(j,i);
data>>=1;
}
}
}
void setup(){
int i = 0 ;
for(i=2;i<18;i++)
{
pinMode(i, OUTPUT);
}
clear_();
}
void loop()
{ show_num();
}
void clear_(void)// clear screen
{for(int i=2;i<10;i++)
digitalWrite(i, LOW);
for(int i=0;i<8;i++)
digitalWrite(i+10, HIGH);
}
//////////////////////////////////////////////////////////
Test Result
Burn the program into UNO board, the dot-matrix will display 0.
*******************************************************************************
www.keyestudio.com 82
keyestudio
Project 20: 1602 LCD
Introduction
www.keyestudio.com 83
keyestudio
Interface Description:
1. two power sources, one for module power, another one for back light, generally use 5V. In this
project, we use 3.3V for back light.
2. VL is the pin for adjusting contrast ratio; it usually connects a potentiometer(no more than 5KΩ)
in series for its adjustment. In this experiment, we use a 1KΩ resistor. For the connection, it has 2
methods, namely high potential and low potential. Here, we use low potential method; connect the
resistor and then the GND.
3. RS is a very common pin in LCD. It's a selecting pin for command/data. When the pin is in high
level, it's in data mode; when it's in low level, it's in command mode.
4. RW pin is also very common in LCD. It's a selecting pin for read/write. When the
pin is in high level, it's in read operation; when it's in low level, it's in write operation.
5. E pin is also very common in LCD. Usually, when the signal in the bus is stabilized, it sends out
a positive pulse requiring read operation. When this pin is in high level, the bus is not allowed to
have any change.
6. D0-D7 is 8-bit bidirectional parallel bus, used for command and data transmission.
7. BLA is anode for back light; BLK, cathode for back light.
Hardware Required
1 * Arduino Board
1 * 1602 LCD
1 * Potentiometer
1 * Breadboard
1 * USB Cable
Several* Jumper Wires
1602 can directly communicate with Arduino. According to the product manual, it has two
connection methods, namely 8-bit connection and 4-bit connection.
www.keyestudio.com 84
keyestudio
8-bit Connection Method:
www.keyestudio.com 85
keyestudio
Connection for 2560 R3:
Sample Code A:
//////////////////////////////////////////////////////////
int DI = 12;
int RW = 11;
int DB[] = {3, 4, 5, 6, 7, 8, 9, 10};// use array to select pin for bus
int Enable = 2;
www.keyestudio.com 86
keyestudio
digitalWrite(DI, HIGH);
digitalWrite(RW, LOW);
for (i=DB[0]; i <= DB[7]; i++) {
digitalWrite(i,value & 01);
value >>= 1;
}
digitalWrite(Enable,LOW);
delayMicroseconds(1);
digitalWrite(Enable,HIGH);
delayMicroseconds(1);
digitalWrite(Enable,LOW);
delayMicroseconds(1); // wait for 1ms
}
delay(20);
}
www.keyestudio.com 87
keyestudio
void loop (void) {
LcdCommandWrite(0x01); // clear the scree, cursor position returns to 0
delay(10);
LcdCommandWrite(0x80+3);
delay(10);
// write in welcome message
LcdDataWrite('W');
LcdDataWrite('e');
LcdDataWrite('l');
LcdDataWrite('c');
LcdDataWrite('o');
LcdDataWrite('m');
LcdDataWrite('e');
LcdDataWrite(' ');
LcdDataWrite('t');
LcdDataWrite('o');
delay(10);
LcdCommandWrite(0xc0+1); // set cursor position at second line, second position
delay(10);
LcdDataWrite('g');
LcdDataWrite('e');
LcdDataWrite('e');
LcdDataWrite('k');
LcdDataWrite('-');
LcdDataWrite('w');
LcdDataWrite('o');
LcdDataWrite('r');
LcdDataWrite('k');
LcdDataWrite('s');
LcdDataWrite('h');
LcdDataWrite('o');
LcdDataWrite('p');
delay(5000);
LcdCommandWrite(0x01); // clear the screen, cursor returns to 0
delay(10);
LcdDataWrite('I');
LcdDataWrite(' ');
LcdDataWrite('a');
LcdDataWrite('m');
LcdDataWrite(' ');
LcdDataWrite('h');
LcdDataWrite('o');
www.keyestudio.com 88
keyestudio
LcdDataWrite('n');
LcdDataWrite('g');
LcdDataWrite('y');
LcdDataWrite('i');
delay(3000);
LcdCommandWrite(0x02); // set mode as new characters replay old ones, where there is no new
ones remain the same
delay(10);
LcdCommandWrite(0x80+5); // set cursor position at first line, sixth position
delay(10);
LcdDataWrite('t');
LcdDataWrite('h');
LcdDataWrite('e');
LcdDataWrite(' ');
LcdDataWrite('a');
LcdDataWrite('d');
LcdDataWrite('m');
LcdDataWrite('i');
LcdDataWrite('n');
delay(5000);
}
//////////////////////////////////////////////////////////
www.keyestudio.com 89
keyestudio
Connection for 2560 R3:
After the connection, upload below code to the controller board and see how it goes.
Sample Code B:
//////////////////////////////////////////////////////////
/*
LiquidCrystal Library - Hello World
The circuit:
* LCD RS pin to digital pin 12
* LCD Enable pin to digital pin 11
* LCD D4 pin to digital pin 9
* LCD D5 pin to digital pin 8
* LCD D6 pin to digital pin 7
* LCD D7 pin to digital pin 6
* LCD R/W pin to ground
* LCD VSS pin to ground
* LCD VCC pin to 5V
www.keyestudio.com 90
keyestudio
* 10K resistor:
* ends to +5V and ground
* wiper to LCD VO pin (pin 3)
http://www.arduino.cc/en/Tutorial/LiquidCrystal
*/
void setup() {
// set up the LCD's number of columns and rows:
lcd.begin(16, 2);
// Print a message to the LCD.
lcd.print("hello, world!");
}
void loop() {
// set the cursor to column 0, line 1
// (note: line 1 is the second row, since counting begins with 0):
lcd.setCursor(0, 1);
// print the number of seconds since reset:
lcd.print(millis() / 1000);
}
//////////////////////////////////////////////////////////
www.keyestudio.com 91
keyestudio
Project 21: 9g Servo Control
Introduction
Servomotor is a position control rotary actuator. It mainly consists of housing, circuit board,
core-less motor, gear and position sensor. The receiver or MCU outputs a signal to the servomotor.
The motor has a built-in reference circuit that gives out reference signal, cycle of 20ms and width
of 1.5ms. The motor compares the acquired DC bias voltage to the voltage of the potentiometer
and outputs a voltage difference. The IC on the circuit board will decide the rotate direction
accordingly and drive the core-less motor. The gear then pass the force to the shaft. The sensor
will determine whether it has reached the commanded position according to the feedback signal.
Servomotors are used in control systems that require to have and maintain different angles. When
the motor speed is definite, the gear will drive the potentiometer to rotate. When the voltage
difference reduces to zero, the motor stops. Normally, the rotation angle range is among 0-180
degrees.
Servomotor comes with many specifications. But all of them have three connection wires,
distinguished by brown, red, orange (different brand may have different color). Brown one is for
GND, red one for power positive, orange one for signal line.
www.keyestudio.com 92
keyestudio
The rotate angle of the servo motor is controlled by regulating the duty cycle of the
PWM(Pulse-Width Modulation) signal. The standard cycle of the PWM signal is 20ms(50Hz).
Theoretically, the width is distributed between 1ms-2ms, but in fact, it's between 0.5ms-2.5ms.
The width corresponds the rotate angle from 0° to 180°. But note that for different brand motor,
the same signal may have different rotating angle.
With some basic knowledge, let's learn how to control a servomotor. In this experiment, you only
need a servomotor and several jumper wires.
Hardware Required
9G Servo Motor*1
Breadboard Jumper Wire*several
There are two ways to control a servomotor with Arduino. One is to use a common digital sensor
port of Arduino to produce square wave with different duty cycle to simulate PWM signal and use
that signal to control the positioning of the motor.
Another way is to directly use the Servo function of the Arduino to control the motor. In this way,
the program will be more easier but it can only control two-contact motor because of the servo
function, only digital pin 9 and 10 can be used. The Arduino drive capacity is limited. So if you
need to control more than one motor, you will need external power.
Method 1:
www.keyestudio.com 93
keyestudio
www.keyestudio.com 94
keyestudio
Compile a program to control the motor to rotate in the commanded angle, and display the angle
on the screen.
Sample Code A
//////////////////////////////////////////////////////////
int servopin=9;// select digital pin 9 for servomotor signal line
int myangle;// initialize angle variable
int pulsewidth;// initialize width variable
int val;
void servopulse(int servopin,int myangle)// define a servo pulse function
{
pulsewidth=(myangle*11)+500;// convert angle to 500-2480 pulse width
digitalWrite(servopin,HIGH);// set the level of servo pin as “high”
delayMicroseconds(pulsewidth);// delay microsecond of pulse width
digitalWrite(servopin,LOW);// set the level of servo pin as “low”
delay(20-pulsewidth/1000);
}
void setup()
{
pinMode(servopin,OUTPUT);// set servo pin as “output”
Serial.begin(9600);// connect to serial port, set baud rate at “9600”
Serial.println("servo=o_seral_simple ready" ) ;
}
void loop()// convert number 0 to 9 to corresponding 0-180 degree angle, LED blinks
corresponding number of time
{
val=Serial.read();// read serial port value
if(val>='0'&&val<='9')
{
val=val-'0';// convert characteristic quantity to numerical variable
val=val*(180/9);// convert number to angle
Serial.print("moving servo to ");
Serial.print(val,DEC);
Serial.println();
for(int i=0;i<=50;i++) // giving the servo time to rotate to commanded position
{
servopulse(servopin,val);// use the pulse function
}
}
}
//////////////////////////////////////////////////////////
www.keyestudio.com 95
keyestudio
Method 2:
Let's first take a look at the Arduino built-in servo function and some common statements.
1. attach(interface)——select pin for servo, can only use pin 9 or 10.
2. write(angle)——used to control the rotate angle of the servo, can set the angle among 0 degree
to 180 degree.
3. read ( ) ——used to read the angle of the servo, consider it a function to read the value in
the write() function.
4、attached()——determine whether the parameter of the servo is sent to the servo pin.
5、detach()—— disconnect the servo and the pin, and the pin(digital pin 9 or 10) can be used for
PWM port.
Note: the written form of the above statements are " servo variable name. specific statement ()",
e.g. myservo. Attach (9).
Still, connect the servo to pin 9.
Sample Code B:
//////////////////////////////////////////////////////////
#include <Servo.h>// define a header file. Special attention here, you can call the servo function
directly from Arduino's software menu
bar Sketch>Importlibrary>Servo, or input #include <Servo.h>. Make sure there is a space
between #include and <Servo.h>. Otherwise, it will cause compile error.
Servo myservo;// define servo variable name
void setup()
{
myservo.attach(9);// select servo pin(9 or 10)
}
void loop()
{
myservo.write(90);// set rotate angle of the motor
}
//////////////////////////////////////////////////////////
Above are the two methods to control the servo. You can choose either one according to your
liking or actual need.
www.keyestudio.com 96
keyestudio
Project 22: 5V Stepper Motor
Introduction
A stepper motor is an electromechanical device which can convert electrical pulses into discrete
mechanical movements. The shaft or spindle of a stepper motor rotates in discrete step increments
when electrical command pulses are applied to it in the proper sequence. The motors rotation has
several direct relationships to these applied input pulses. The sequence of the applied pulses is
directly related to the direction of motor shafts rotation. The speed of the motor shafts rotation is
directly related to the frequency of the input pulses and the length of rotation is directly related to
the number of input pulses applied.
One of the most significant advantages of a stepper motor is its ability to be accurately controlled
in an open loop system. Open loop control means no feedback information about position is
needed. This type of control eliminates the need for expensive sensing and feedback devices such
as optical encoders. Your position is known simply by keeping track of the input step pulses.
Features
• The rotation angle of the motor is proportional to the input pulse.
• The motor has full torque at standstill(if the windings are energized)
• Precise positioning and repeatability of movement since good stepper motors have an
accuracy of – 5% of a step and this error is non cumulative from one step to the next.
• Excellent response to starting/stopping/reversing.
• Very reliable since there are no contact brushes in the motor. Therefore the life of the motor is
simply dependant on the life of the bearing.
• The motors response to digital input pulses provides open-loop control, making the motor
simpler and less costly to control.
• It is possible to achieve very low speed synchronous rotation with a load that is directly
coupled to the shaft.
www.keyestudio.com 97
keyestudio
• A wide range of rotational speeds can be realized as the speed is proportional to the
frequency of the input pulses.
Circuit Connection
www.keyestudio.com 98
keyestudio
Connection for 2560 R3:
Sample Code
//////////////////////////////////////////////////////////
#include <Stepper.h>
#define STEPS 100
Stepper stepper(STEPS, 8, 9, 10, 11);
int previous = 0;
void setup()
{
stepper.setSpeed(90);
}
void loop()
{
int val = analogRead(0);
stepper.step(val - previous);
previous = val;
}
//////////////////////////////////////////////////////////
www.keyestudio.com 99
keyestudio
Project 23: PIR Motion Sensor
Introduction
Pyroelectric infrared motion sensor can detect infrared signals from a moving person or moving
animal, and output switching signals. It can be applied to a variety of occasions to detect the
movement of human body. Conventional pyroelectric infrared sensors require body pyroelectric
infrared detector, professional chip, complex peripheral circuit, so it is more bigger with complex
circuit, and lower reliability.
Now we launch this new pyroelectric infrared motion sensor, which is specially designed for
Arduino. It uses an integrated digital body pyroelectric infrared sensor, and has smaller size,
higher reliability, lower power consumption as well as simpler peripheral circuit.
Specification
Input Voltage: 3.3 ~ 5V (6V Maximum)
Working Current: 15uA
Working Temperature: -20 ~ 85 ℃
Output Voltage: High 3V, Low 0V
Output Delay Time (High Level): About 2.3 to 3 Seconds
Detection Angle: 100 °
Detection Distance: 7 meters
Output Indicator LED (When output HIGH, it will be ON)
Pin limit Current: 100mA
Size: 30*20mm
Weight: 4g
Circuit Connection
www.keyestudio.com 100
keyestudio
Connection for UNO R3:
Sample Code
//////////////////////////////////////////////////////////
byte sensorPin = 3;
byte indicator = 13;
void setup()
{
pinMode(sensorPin,INPUT);
pinMode(indicator,OUTPUT);
Serial.begin(9600);
www.keyestudio.com 101
keyestudio
}
void loop()
{
byte state = digitalRead(sensorPin);
digitalWrite(indicator,state);
if(state == 1)Serial.println("Somebody is in this area!");
else if(state == 0)Serial.println("No one!");
delay(500);
}
//////////////////////////////////////////////////////////
Introduction
This analog gas sensor - MQ2 is used in gas leakage detecting equipment in consumer electronics
and industrial markets. This sensor is suitable for LPG, I-butane, propane, methane, alcohol,
Hydrogen and smoke detection. It has high sensitivity and quick response. In addition, the
sensitivity can be adjusted by the potentiometer.
Specification
Power Supply: 5V
Interface Type: Analog
Wide detecting scope
Quick response and high sensitivity
Simple drive circuit
www.keyestudio.com 102
keyestudio
Stable and long lifespan
Size: 49.7*20mm
Weight: 8g
Circuit Connection
Sample Code
//////////////////////////////////////////////////////////
void setup()
{
Serial.begin(9600); //Set serial baud rate to 9600 bps
}
www.keyestudio.com 103
keyestudio
void loop()
{int val;
val=analogRead(0);//Read Gas value from analog 0
Serial.println(val,DEC);//Print the value to serial port
delay(100);
}
//////////////////////////////////////////////////////////
Introduction
The ADXL345 is a small, thin, low power, 3-axis MEMS accelerometer with high resolution
(13-bit) measurement at up to +-16 g. Digital output data is formatted as 16-bit twos complement
and is accessible through either a SPI (3- or 4-wire) or I2C digital interface.
The ADXL345 is well suited to measure the static acceleration of gravity in tilt-sensing
applications, as well as dynamic acceleration resulting from motion or shock. Its high resolution (4
mg/LSB) enables measurement of inclination change less than 1.0 degrees.
Specification
2.0-3.6V DC Supply Voltage
Ultra Low Power: 40uA in measurement mode, 0.1uA in standby@ 2.5V
Tap/Double Tap Detection
Free-Fall Detection
SPI and I2C interfaces
Size: 30*20mm
Weight: 3g
www.keyestudio.com 104
keyestudio
Circuit Connection
www.keyestudio.com 105
keyestudio
Sample Code
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/*
The circuit:
VCC: 5V
GND: ground
SCL: UNO SLC
SDA: UNO SDA
*/
#include <Wire.h>
// Registers for ADXL345
#define ADXL345_ADDRESS (0xA6 >> 1) // address for device is 8 bit but shift to the
// right by 1 bit to make it 7 bit because the
// wire library only takes in 7 bit addresses
#define ADXL345_REGISTER_XLSB (0x32)
int accelerometer_data[3];
// void because this only tells the cip to send data to its output register
// writes data to the slave's buffer
void i2c_write(int address, byte reg, byte data) {
// Send output register address
Wire.beginTransmission(address);
// Connect to device
Wire.write(reg);
// Send data
Wire.write(data); //low byte
Wire.endTransmission();
}
www.keyestudio.com 106
keyestudio
// Connect to device
Wire.beginTransmission(address);
// Request data from slave
// Count stands for number of bytes to request
Wire.requestFrom(address, count);
while(Wire.available()) // slave may send less than requested
{
char c = Wire.read(); // receive a byte as character
data[i] = c;
i++;
}
Wire.endTransmission();
}
void init_adxl345() {
byte data = 0;
void read_adxl345() {
byte bytes[6];
memset(bytes,0,6);
www.keyestudio.com 107
keyestudio
}
}
// initialise and start everything
void setup() {
Wire.begin();
Serial.begin(9600);
for(int i=0; i<3; ++i) {
accelerometer_data[i] = 0;
}
init_adxl345();
}
void loop() {
read_adxl345();
Serial.print("ACCEL: ");
Serial.print(float(accelerometer_data[0])*3.9/1000);//3.9mg/LSB scale factor in 13-bit mode
Serial.print("\t");
Serial.print(float(accelerometer_data[1])*3.9/1000);
Serial.print("\t");
Serial.print(float(accelerometer_data[2])*3.9/1000);
Serial.print("\n");
delay(100);
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
www.keyestudio.com 108
keyestudio
Project 26: HC-SR04 Ultrasonic Sensor
Introduction
The HC-SR04 Ultrasonic Sensor is a very affordable proximity/distance sensor that is mainly used
for object avoidance in various robotics projects. It essentially gives your Arduino eyes / spacial
awareness and can prevent your robot from crashing or falling off a table. It has also been used in
turret applications, water level sensing, and even as a parking sensor.
This simple project will use the HC-SR04 sensor with an Arduino and a Processing sketch to
provide a more interactive display on your computer screen.
Specification
Working Voltage: DC 5V
Working Current: 15mA
Working Frequency: 40KHz
Max Range: 4m
Min Range: 2cm
Measuring Angle: 15 degree
Trigger Input Signal: 10µS TTL pulse
Echo Output Signal Input TTL lever signal and the range in proportion
Size: 46*20.4mm
Weight: 9g
Circuit Connection
www.keyestudio.com 109
keyestudio
Sample Code
//////////////////////////////////////////////////////////
VCC to arduino 5v
GND to arduino GND
Echo to Arduino pin 7
Trig to Arduino pin 8
www.keyestudio.com 110
keyestudio
long duration, distance; // Duration used to calculate distance
void setup() {
Serial.begin (9600);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(LEDPin, OUTPUT); // Use LED indicator (if required)
}
void loop() {
/* The following trigPin/echoPin cycle is used to determine the
distance of the nearest object by bouncing soundwaves off of it. */
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
www.keyestudio.com 111
keyestudio
Project 27: Joystick Module
Introduction
Lots of robot projects need joystick. This module provides an affordable solution. By simply
connecting to two analog inputs, the robot is at your commands with X, Y control. It also has a
switch that is connected to a digital pin. This joystick module can be easily connected to Arduino
by IO Shield. This module is for Arduino(V5) with cable supplied.
Specification
Circuit Connection
www.keyestudio.com 112
keyestudio
Connection for MEGA 2560 R3:
Sample Code
//////////////////////////////////////////////////////////
int JoyStick_X = 0; //x
int JoyStick_Y = 1; //y
int JoyStick_Z = 3; //key
void setup()
{
pinMode(JoyStick_Z, INPUT);
Serial.begin(9600); // 9600 bps
}
void loop()
{
int x,y,z;
x=analogRead(JoyStick_X);
y=analogRead(JoyStick_Y);
z=digitalRead(JoyStick_Z);
Serial.print(x ,DEC);
Serial.print(",");
Serial.print(y ,DEC);
Serial.print(",");
Serial.println(z ,DEC);
delay(100);
}
//////////////////////////////////////////////////////////
www.keyestudio.com 113
keyestudio
Project 28: 5V Relay Module
Introduction
This single relay module can be used in interactive projects. This module uses SONGLE 5v
high-quality relay. It can also be used to control the lighting, electrical and other equipment. The
modular design makes it easy to expand with the Arduino Board (not included).
The Relay output is by a light-emitting diode. It can be controlled through digital IO port, such as
solenoid valves, lamps, motors and other high current or high voltage devices.
Specification
Type: Digital
Rated Current: 10A (NO) 5A (NC)
Maximum Switching Voltage: 150VAC 24VDC
Digital Interface
Control Signal: TTL level
Rated Load: 8A 150VAC (NO) 10A 24VDC (NO), 5A 250VAC (NO/NC) 5A 24VDC (NO/NC)
Maximum Switching Power: AC1200VA DC240W (NO) AC625VA DC120W (NC)
Contact Action Time: 10ms
Size: 40*28mm
Weight: 15g
Circuit Connection
www.keyestudio.com 114
keyestudio
Connection for UNO R3:
Sample Code
//////////////////////////////////////////////////////////
int Relay = 8;
void setup()
{
pinMode(13, OUTPUT); //Set Pin13 as output
digitalWrite(13, HIGH); //Set Pin13 High
www.keyestudio.com 115
keyestudio
pinMode(Relay, OUTPUT); //Set Pin3 as output
}
void loop()
{
digitalWrite(Relay, HIGH); //Turn off relay
delay(2000);
digitalWrite(Relay, LOW); //Turn on relay
delay(2000);
}
//////////////////////////////////////////////////////////
Introduction
DS3231 is equipped with integrated TCXO and crystal, which makes it a cost-effective I2C real
time clock with high precision. The device carries a battery input, so even if you disconnect the
main power supply, it can still maintain accurate timing. The integrated oscillator ensures the
long-term accuracy of the device and reduces the number of components.
DS3231 provides both commercial and industrial temperature range and supports 16 pins
small-outline package (300mil). The module itself can adapt to the system of 3.3V and 5V without
level switch, which is quite convenient!
www.keyestudio.com 116
keyestudio
Specification
Circuit Connection
This module adopts the IIC test method, so only need to connect ‘SDA’ to Arduino A4, ‘SCL’ to
A5, ‘+’ to VCC and ‘-’ to GND as follows:
www.keyestudio.com 117
keyestudio
Connection for MEGA 2560 R3:
Sample Code
//////////////////////////////////////////////////////////
#include <Wire.h>
#include "DS3231.h"
DS3231 RTC; //Create the DS3231 object
char weekDay[][4] = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
//year, month, date, hour, min, sec and week-day(starts from 0 and goes to 6)
//writing any non-existent time-data may interfere with normal operation of the RTC.
//Take care of week-day also.
DateTime dt(2011, 11, 10, 15, 18, 0, 5);//open the series port and you can check time here or make
a change to the time as needed.
void setup ()
{ Serial.begin(57600);//set baud rate to 57600
Wire.begin();
RTC.begin();
RTC.adjust(dt); //Adjust date-time as defined 'dt' above
}
void loop ()
{
DateTime now = RTC.now(); //get the current date-time
Serial.print(now.year(), DEC);
Serial.print('/');
Serial.print(now.month(), DEC);
Serial.print('/');
Serial.print(now.date(), DEC);
Serial.print(' ');
Serial.print(now.hour(), DEC);
Serial.print(':');
www.keyestudio.com 118
keyestudio
Serial.print(now.minute(), DEC);
Serial.print(':');
Serial.print(now.second(), DEC);
Serial.println();
Serial.print(weekDay[now.dayOfWeek()]);
Serial.println();
delay(1000);
}
//////////////////////////////////////////////////////////
Before compiling the code, you’d better put DS3231 library under file into Arduino catalogue.
Test Result
Done uploading the code to arduino, open the serial monitor and get the following results:
www.keyestudio.com 119
keyestudio
Project 30: DHT11 Temperature and Humidity Sensor
Introduction
This DHT11 Temperature and Humidity Sensor features calibrated digital signal output with the
temperature and humidity sensor complex. Its technology ensures high reliability and excellent
long-term stability. A high-performance 8-bit microcontroller is connected.
This sensor includes a resistive element and a sense of wet NTC temperature measuring devices. It
has the advantages of excellent quality, fast response, anti-interference ability and high cost
performance.
Each DHT11 sensor features extremely accurate calibration data of humidity calibration
chamber. The calibration coefficients stored in the OTP program memory, internal sensors detect
signals in the process, and we should call these calibration coefficients.
The single-wire serial interface system is integrated to make it quick and easy. Qualities of small
size, low power, and 20-meter signal transmission distance make it a widely applied application
and even the most demanding one. Convenient connection and special package can be provided
according to your need.
Specification
Supply Voltage: +5 V
Temperature Range: 0-50 °C error of ± 2 °C
Humidity: 20-90% RH ± 5% RH error
Interface: digital
Size: 30*20mm
Weight: 4g
www.keyestudio.com 120
keyestudio
Circuit Connection
Sample Code
void setup(){
Serial.begin(9600);
Serial.println("DHT TEST PROGRAM ");
Serial.print("LIBRARY VERSION: ");
Serial.println(DHT11LIB_VERSION);
Serial.println();
www.keyestudio.com 121
keyestudio
Serial.println("Type,\tstatus,\tHumidity (%),\tTemperature (C)");
}
void loop(){
int chk;
Serial.print("DHT11, \t");
chk = DHT.read(DHT11_PIN); // READ DATA
switch (chk){
case DHTLIB_OK:
Serial.print("OK,\t");
break;
case DHTLIB_ERROR_CHECKSUM:
Serial.print("Checksum error,\t");
break;
case DHTLIB_ERROR_TIMEOUT:
Serial.print("Time out error,\t");
break;
default:
Serial.print("Unknown error,\t");
break;
}
// DISPLAT DATA
Serial.print(DHT.humidity,1);
Serial.print(",\t");
Serial.println(DHT.temperature,1);
delay(1000);
}
//////////////////////////////////////////////////////////
www.keyestudio.com 122
keyestudio
Project 31: Soil Humidity Sensor
Introduction
This is a simple soil humidity sensor aims to detect the soil humidity. If the soil is lack of water,
the analog value output by the sensor will decrease; otherwise, it will increase. If you use this
sensor to make an automatic watering device, it can detect whether your botany is thirsty so as to
prevent it from withering when you go out. Using the sensor with Arduino controller makes your
plant more comfortable and your garden smarter.
The soil humidity sensor module is not as complicated as you might think, and if you need to
detect the soil in your project, it will be your best choice.
The sensor is set with two probes inserted into the soil, then with the current go through the soil,
the sensor will get resistance value by reading the current changes between the two probes and
convert such resistance value into moisture content. The higher the moisture (less resistance) is,
the higher conductivity the soil has.
The surface of the sensor have undergone metallization process to prolong its service life. Insert it
into the soil and then use the AD converter to read it. With the help of this sensor, the plant can
remind of you: I need water.
Specification
1. Power Supply Voltage: 3.3V or 5V
2. Working Current: ≤ 20mA
3. Output Voltage: 0-2.3V (When the sensor is totally immersed in water, the voltage will be
2.3V)
4. 5V power supply (the higher humidity, the higher the output voltage)
5. Packaging : Electrostatic bag sealing
6. Sensor Type: Analog output
7. Interface Definition: Pin1- signal, pin2- GND, pin3 - VCC
8. Service Life: about one year (gold-plated surface for enhancing conductivity and
corrosion resistance )
9. Module Size: 20*60mm
www.keyestudio.com 123
keyestudio
Circuit Connection
Sample Code
//////////////////////////////////////////////////////////
# 0 ~300 dry soil
# 300~700 humid soil
# 700~950 in water
*/
void setup(){
www.keyestudio.com 124
keyestudio
Serial.begin(57600);
}
void loop(){
Introduction
MF522-AN module adopts Philips MFRC522 original reader circuit chip design, easy to use, low
cost, suitable for equipment development, development of advanced applications, the need for the
user of RF card terminal design / production. It can be loaded directly into a variety of readers
molds. Module uses voltage of 3.3V, through the SPI interface using simple few lines, it can be
directly connected to any CPU board communication modules to guarantee stable and reliable
work and reader distance.
Electrical Parameters
1. Current :13-26mA / DC 3.3V
2. Idle Current :10-13mA / DC 3.3V
3. Sleep Current: <80uA
4. Peak Current: <30mA
5. Operating Frequency: 13.56MHz
www.keyestudio.com 125
keyestudio
6. Supported card types: mifare1 S50, mifare1 S70, mifare UltraLight, mifare Pro, mifare
Desfire
7. Dimension: 40mm * 60mm
8. Environmental Operating Temperature: -20-80 degrees Celsius
9. Environment Storage Temperature: -40-85 degrees Celsius
10. Relative Humidity: 5% -95%
Circuit Connection
www.keyestudio.com 126
keyestudio
Connection for 2560 R3:
Sample Code
//////////////////////////////////////////////////////////
#include <SPI.h>
#define uchar unsigned char
#define uint unsigned int
#define MAX_LEN 16
const int chipSelectPin = 10;//if the controller is UNO,328,168
const int NRSTPD = 5;
//MF522command word
#define PCD_IDLE 0x00 //NO action;concel current command
#define PCD_AUTHENT 0x0E //verify key
#define PCD_RECEIVE 0x08 //receive data
#define PCD_TRANSMIT 0x04 //send data
#define PCD_TRANSCEIVE 0x0C //receive and send data
#define PCD_RESETPHASE 0x0F //reset
#define PCD_CALCCRC 0x03 //CRC calculation
www.keyestudio.com 127
keyestudio
#define PICC_READ 0x30 // Reader Module
#define PICC_WRITE 0xA0 // letter block
#define PICC_DECREMENT 0xC0
#define PICC_INCREMENT 0xC1
#define PICC_RESTORE 0xC2 //Transfer data to buffer
#define PICC_TRANSFER 0xB0 //Save buffer data
#define PICC_HALT 0x50 //Dormancy
//------------------MFRC522 Register---------------
//Page 0:Command and Status
#define Reserved00 0x00
#define CommandReg 0x01
#define CommIEnReg 0x02
#define DivlEnReg 0x03
#define CommIrqReg 0x04
#define DivIrqReg 0x05
#define ErrorReg 0x06
#define Status1Reg 0x07
#define Status2Reg 0x08
#define FIFODataReg 0x09
#define FIFOLevelReg 0x0A
#define WaterLevelReg 0x0B
#define ControlReg 0x0C
#define BitFramingReg 0x0D
#define CollReg 0x0E
#define Reserved01 0x0F
//Page 1:Command
#define Reserved10 0x10
#define ModeReg 0x11
#define TxModeReg 0x12
#define RxModeReg 0x13
#define TxControlReg 0x14
#define TxAutoReg 0x15
#define TxSelReg 0x16
#define RxSelReg 0x17
www.keyestudio.com 128
keyestudio
#define RxThresholdReg 0x18
#define DemodReg 0x19
#define Reserved11 0x1A
#define Reserved12 0x1B
#define MifareReg 0x1C
#define Reserved13 0x1D
#define Reserved14 0x1E
#define SerialSpeedReg 0x1F
//Page 2:CFG
#define Reserved20 0x20
#define CRCResultRegM 0x21
#define CRCResultRegL 0x22
#define Reserved21 0x23
#define ModWidthReg 0x24
#define Reserved22 0x25
#define RFCfgReg 0x26
#define GsNReg 0x27
#define CWGsPReg 0x28
#define ModGsPReg 0x29
#define TModeReg 0x2A
#define TPrescalerReg 0x2B
#define TReloadRegH 0x2C
#define TReloadRegL 0x2D
#define TCounterValueRegH 0x2E
#define TCounterValueRegL 0x2F
//Page 3:TestRegister
#define Reserved30 0x30
#define TestSel1Reg 0x31
#define TestSel2Reg 0x32
#define TestPinEnReg 0x33
#define TestPinValueReg 0x34
#define TestBusReg 0x35
#define AutoTestReg 0x36
#define VersionReg 0x37
#define AnalogTestReg 0x38
#define TestDAC1Reg 0x39
#define TestDAC2Reg 0x3A
#define TestADCReg 0x3B
#define Reserved31 0x3C
#define Reserved32 0x3D
#define Reserved33 0x3E
#define Reserved34 0x3F
www.keyestudio.com 129
keyestudio
uchar serNum[5];
uchar writeDate[16] ={'T', 'e', 'n', 'g', ' ', 'B', 'o', 0, 0, 0, 0, 0, 0, 0, 0,0};
uchar sectorKeyA[16][16] = {{0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF},
{0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF},
{0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF},
};
uchar sectorNewKeyA[16][16] = {{0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF},
{0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xff,0x07,0x80,0x69, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF},
{0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xff,0x07,0x80,0x69, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF},
};
void setup() {
Serial.begin(9600); // RFID reader SOUT pin connected to Serial
RX pin at 2400bps
// start the SPI library:
SPI.begin();
MFRC522_Init();
}
void loop()
{
uchar i,tmp;
uchar status;
uchar str[MAX_LEN];
uchar RC_size;
uchar blockAddr; //Select the address of the operation 0~63
www.keyestudio.com 130
keyestudio
}
status = MFRC522_Anticoll(str);
memcpy(serNum, str, 5);
if (status == MI_OK)
{
Serial.println("The card's number is : ");
Serial.print(serNum[0],BIN);
Serial.print(serNum[1],BIN);
Serial.print(serNum[2],BIN);
Serial.print(serNum[3],BIN);
Serial.print(serNum[4],BIN);
Serial.println(" ");
}
// write data
blockAddr = blockAddr - 3 ;
status = MFRC522_Write(blockAddr, writeDate);
if(status == MI_OK)
{
Serial.println("OK!");
}
}
www.keyestudio.com 131
keyestudio
// read card
blockAddr = 7; // data block 7
status = MFRC522_Auth(PICC_AUTHENT1A, blockAddr,
sectorNewKeyA[blockAddr/4], serNum); // authentication
if (status == MI_OK)
{
// read data
blockAddr = blockAddr - 3 ;
status = MFRC522_Read(blockAddr, str);
if (status == MI_OK)
{
Serial.println("Read from the card ,the data is : ");
for (i=0; i<16; i++)
{
Serial.print(str[i]);
}
Serial.println(" ");
}
}
Serial.println(" ");
MFRC522_Halt(); // command card to enter standby mode
SPI.transfer((addr<<1)&0x7E);
SPI.transfer(val);
digitalWrite(chipSelectPin, HIGH);
}
digitalWrite(chipSelectPin, LOW);
www.keyestudio.com 132
keyestudio
SPI.transfer(((addr<<1)&0x7E) | 0x80);
val =SPI.transfer(0x00);
digitalWrite(chipSelectPin, HIGH);
return val;
}
void AntennaOn(void)
{
uchar temp;
temp = Read_MFRC522(TxControlReg);
if (!(temp & 0x03))
{
SetBitMask(TxControlReg, 0x03);
}
}
void AntennaOff(void)
{
ClearBitMask(TxControlReg, 0x03);
}
www.keyestudio.com 133
keyestudio
void MFRC522_Reset(void)
{
Write_MFRC522(CommandReg, PCD_RESETPHASE);
}
void MFRC522_Init(void)
{
digitalWrite(NRSTPD,HIGH);
MFRC522_Reset();
TagType[0] = reqMode;
status = MFRC522_ToCard(PCD_TRANSCEIVE, TagType, 1, TagType, &backBits);
return status;
}
www.keyestudio.com 134
keyestudio
uchar MFRC522_ToCard(uchar command, uchar *sendData, uchar sendLen, uchar *backData,
uint *backLen)
{
uchar status = MI_ERR;
uchar irqEn = 0x00;
uchar waitIRq = 0x00;
uchar lastBits;
uchar n;
uint i;
switch (command)
{
case PCD_AUTHENT: // card key authentication
{
irqEn = 0x12;
waitIRq = 0x10;
break;
}
case PCD_TRANSCEIVE: // send data in FIFO
{
irqEn = 0x77;
waitIRq = 0x30;
break;
}
default:
break;
}
// execute command
www.keyestudio.com 135
keyestudio
Write_MFRC522(CommandReg, command);
if (command == PCD_TRANSCEIVE)
{
SetBitMask(BitFramingReg, 0x80); //StartSend=1,transmission of data starts
}
if (i != 0)
{
if(!(Read_MFRC522(ErrorReg) & 0x1B)) //BufferOvfl Collerr CRCErr ProtecolErr
{
status = MI_OK;
if (n & irqEn & 0x01)
{
status = MI_NOTAGERR; //??
}
if (command == PCD_TRANSCEIVE)
{
n = Read_MFRC522(FIFOLevelReg);
lastBits = Read_MFRC522(ControlReg) & 0x07;
if (lastBits)
{
*backLen = (n-1)*8 + lastBits;
}
else
{
*backLen = n*8;
}
www.keyestudio.com 136
keyestudio
if (n == 0)
{
n = 1;
}
if (n > MAX_LEN)
{
n = MAX_LEN;
}
return status;
}
serNum[0] = PICC_ANTICOLL;
serNum[1] = 0x20;
status = MFRC522_ToCard(PCD_TRANSCEIVE, serNum, 2, serNum, &unLen);
www.keyestudio.com 137
keyestudio
if (status == MI_OK)
{
// verify card sequence number
for (i=0; i<4; i++)
{
serNumCheck ^= serNum[i];
}
if (serNumCheck != serNum[i])
{
status = MI_ERR;
}
}
return status;
}
www.keyestudio.com 138
keyestudio
// read CRC calculation result
pOutData[0] = Read_MFRC522(CRCResultRegL);
pOutData[1] = Read_MFRC522(CRCResultRegM);
}
buffer[0] = PICC_SElECTTAG;
buffer[1] = 0x70;
for (i=0; i<5; i++)
{
buffer[i+2] = *(serNum+i);
}
CalulateCRC(buffer, 7, &buffer[7]); //??
status = MFRC522_ToCard(PCD_TRANSCEIVE, buffer, 9, buffer, &recvBits);
return size;
}
www.keyestudio.com 139
keyestudio
uchar buff[12];
return status;
}
recvData[0] = PICC_READ;
recvData[1] = blockAddr;
CalulateCRC(recvData,2, &recvData[2]);
status = MFRC522_ToCard(PCD_TRANSCEIVE, recvData, 4, recvData, &unLen);
return status;
}
www.keyestudio.com 140
keyestudio
{
uchar status;
uint recvBits;
uchar i;
uchar buff[18];
buff[0] = PICC_WRITE;
buff[1] = blockAddr;
CalulateCRC(buff, 2, &buff[2]);
status = MFRC522_ToCard(PCD_TRANSCEIVE, buff, 4, buff, &recvBits);
if (status == MI_OK)
{
for (i=0; i<16; i++) // write 16Byte data into FIFO
{
buff[i] = *(writeData+i);
}
CalulateCRC(buff, 16, &buff[16]);
status = MFRC522_ToCard(PCD_TRANSCEIVE, buff, 18, buff, &recvBits);
return status;
}
void MFRC522_Halt(void)
{
uchar status;
uint unLen;
uchar buff[4];
buff[0] = PICC_HALT;
buff[1] = 0;
www.keyestudio.com 141
keyestudio
CalulateCRC(buff, 2, &buff[2]);
Note: if you want to use MEGA 2560 R3, please in the code change
const int chipSelectPin = 10;//if the controller is UNO,328,168
into
const int chipSelectPin = 53;//if the controller is UNO,328,168
Test Result
In this experiment, when the IC card approaches, RFID module will write data to the IC card and
read the card’s data, you can see the data on the monitor window. Shown below.
www.keyestudio.com 142