Elegoo Mega2560 User Manual

THE MOST COMPLETE STARTER KIT
TUTORIAL FOR MEGA2560
V1.0.17.7.9
2
/
223
Preface
Our Company
Established in 2011, Elegoo Inc. is a thriving technology company dedicated to open­source hardware research & development, production and marketing. Located in Shenzhen, the Silicon Valley of China, we have grown to over 150+ employees with a 10,763+ square ft. factory. Our product lines rang from DuPont wires, 2560 R3 boards to complete starter kits designed for customers of any level to learn Arduino knowledge. In addition, we also sell products of Raspberry Pi accessories like 2.8’’ TFT touch and STM32. In the future we would devote more energy and investment to 3D printer products and so on. All of our products comply with international quality standards and are greatly appreciated in a variety of different markets throughout the world.
Official website: http://www.elegoo.com US Amazon storefront: http://www.amazon.com/shops/A2WWHQ25ENKVJ1 CA Amazon storefront: http://www.amazon.ca/shops/A2WWHQ25ENKVJ1 UK Amazon storefront: http://www.amazon.co.uk/shops/A1780XYQ9DFQM6 DE Amazon storefront: http://www.amazon.de/shops/A1780XYQ9DFQM6 FR Amazon storefront: http://www.amazon.de/shops/A1780XYQ9DFQM6 ES Amazon storefront: http://www.amazon.de/shops/A1780XYQ9DFQM6 IT Amazon storefront: http://www.amazon.de/shops/A1780XYQ9DFQM6
Our Tutorial
This tutorial is designed for beginners. You will learn all the basic information about how to use Arduino controller board, sensors and components. If you want to study Arduino in more depth, we recommend that you read the Arduino Cookbook written by Michael Margolis. Some codes in this tutorial is edited by Simon Monk. Simon Monk is author of a number of books relating to Open Source Hardware. They are available in Amazon: Programming Arduino, 30 Arduino Projects for the Evil Genius and Programming the Raspberry Pi.
Customer Service
As a continuous and fast growing technology company we keep striving our best to
3
/
223
offer you excellent products and quality service as to meet your expectation and you can reach out to us by simply drop a line at service@elegoo.com or
EUservice@elegoo.com. We look forward to hearing from you and any of your critical
comment or suggestion would be much valuable to us. And any of problems and questions you have with our products will be promptly replied by our experienced engineers within 12 hours (24hrs during holiday)
4 / 223
5 / 223
6 / 223
7 / 223
8 / 223
9 / 223
10
/
223
Content
Lesson 0 Installing IDE ............................................................................................................. 12
Lesson 1 Add Libraries and Open Serial Monitor ................................................................... 23
Lesson 2 Blink ........................................................................................................................... 32
Lesson 3 LED ............................................................................................................................. 43
Lesson 4 RGB LED ..................................................................................................................... 50
Lesson 5 Digital Inputs ............................................................................................................. 59
Lesson 6 Active buzzer ............................................................................................................. 64
Lesson 7 Passive Buzzer ........................................................................................................... 68
Lesson 8 Tilt Ball Switch ........................................................................................................... 72
Lesson 9 Servo .......................................................................................................................... 76
Lesson 10 Ultrasonic Sensor Module ...................................................................................... 80
Lesson 11 Membrane Switch Module ..................................................................................... 85
Lesson 12 DHT11 Temperature and Humidity Sensor ............................................................ 91
Lesson 13 Analog Joystick Module .......................................................................................... 97
Lesson 14 IR Receiver Module ............................................................................................... 102
Lesson 15 MAX7219 LED Dot Matrix Module ....................................................................... 108
Lesson 16 GY-521 Module ..................................................................................................... 112
Lesson 17 HC-SR501 PIR Sensor ............................................................................................ 121
Lesson 18 Water Level Detection Sensor Module ................................................................ 131
Lesson 19 Real Time Clock Module ....................................................................................... 136
Lesson 20 Sound Sensor Module ........................................................................................... 141
Lesson 21 RC522 RFID Module .............................................................................................. 147
Lesson 22 LCD Display ............................................................................................................ 152
Lesson 23 Thermometer ........................................................................................................ 157
Lesson 24 Eight LED with 74HC595 ........................................................................................ 162
Lesson 25 The Serial Monitor ................................................................................................ 169
Lesson 26 Photocell ............................................................................................................... 175
Lesson 27 74HC595 And Segment Display ............................................................................ 180
11
/
223
Lesson 28 Four Digital Seven Segment Display ..................................................................... 186
Lesson 29 DC Motors ............................................................................................................. 191
Lesson 30 Relay ...................................................................................................................... 201
Lesson 31 Stepper Motor ...................................................................................................... 206
Lesson 32 Controlling Stepper Motor With Remote ............................................................ 214
Lesson 33 Controlling Stepper Motor With Rotary Encoder ................................................ 218
12
/
223
Lesson 0 Installing IDE
Introduction
The Arduino Integrated Development Environment (IDE) is the software side of the Arduino platform. In this lesson, you will learn how to setup your computer to use Arduino and how to set about the lessons that follow.
The Arduino software that you will use to program your Arduino is available for Windows, Mac and Linux. The installation process is different for all three platforms and unfortunately there is a certain amount of manual work to install the software.
STEP 1: Go to https://www.arduino.cc/en/Main/Software and find below page.
The version available at this website is usually the latest version, and the actual
version may be newer than the version in the picture.
13
/
223
STEP2Download the development software that is compatible with the operating system of your computer. Take Windows as an example here.
Click Windows Installer.
Click JUST DOWNLOAD.
14
/
223
Also version 1.8.0 is available in the material we provided, and the versions of our materials are the latest versions when this course was made.
Installing Arduino (Windows)
Install Arduino with the exe. Installation package.
Click I Agree to see the following interface
Click Next
You can press Browse… to choose an installation path or directly type in the
directory you want.
15 / 223
16
/
223
Click Install to initiate installation
Finally, the following interface appears, click Install to finish the installation.
Next, the following icon appears on the desktop
17
/
223
Double-click to enter the desired development environment
You may directly choose the installation package for installation and skip the
contents below and jump to the next section. But if you want to learn some methods
other than the installation package, please continue to read the section.
Unzip the zip file downloaded, Double-click to open the program and enter the
desired development environment
18
/
223
19
/
223
However, this installation method needs separate installation of driver.
The Arduino folder contains both the Arduino program itself and the drivers that
allow the Arduino to be connected to your computer by a USB cable. Before we
launch the Arduino software, you are going to install the USB drivers.
Plug one end of your USB cable into the Arduino and the other into a USB socket on
your computer. The power light on the LED will light up and you may get a 'Found
New Hardware' message from Windows. Ignore this message and cancel any
attempts that Windows makes to try and install drivers automatically for you.
The most reliable method of installing the USB drivers is to use the Device Manager.
This is accessed in different ways depending on your version of Windows. In
Windows 7, you first have to open the Control Panel, then select the option to view
Icons, and you should find the Device Manager in the list.
Under ‘Other Devices’, you should see an icon for ‘unknown device’ with a little
yellow warning triangle next to it. This is your Arduino.
20
/
223
Right-click on the device and select the top menu option (Update Driver Software...).
You will then be prompted to either ‘Search Automatically for updated driver
software’ or ‘Browse my computer for driver software’. Select the option to browse
and navigate to the X\arduino1.8.0\drivers.
21
/
223
Click 'Next' and you may get a security warning, if so, allow the software to be
installed. Once the software has been installed, you will get a confirmation message.
Windows users may skip the installation directions for Mac and Linux systems and
jump to Lesson 1. Mac and Linux users may continue to read this section.
Installing Arduino (Mac OS X)
Download and Unzip the zip file, double click the Arduino.app to enter Arduino IDE;
the system will ask you to install Java runtime library if you don’t have it in your
computer. Once the installation is complete you can run the Arduino IDE.
22
/
223
Installing Arduino (Linux)
You will have to use the make install command. If you are using the Ubuntu system, it is
recommended to install Arduino IDE from the software center of Ubuntu.
TIPS: If you have problems in installing the drivers, please refer to the UNO R3,
MEGA, NANO DRIVER FAQ.
23
/
223
Lesson 1 Add Libraries and Open Serial Monitor
Installing Additional Arduino Libraries
Once you are comfortable with the Arduino software and using the built-in functions,
you may want to extend the ability of your Arduino with additional libraries.
What are Libraries?
Libraries are a collection of code that makes it easy for you to connect to a sensor,
display, module, etc. For example, the built-in LiquidCrystal library makes it easy to
talk to character LCD displays. There are hundreds of additional libraries available
on the Internet for download. The built-in libraries and some of these additional
libraries are listed in the reference. To use the additional libraries, you will need to
install them.
How to Install a Library
Using the Library Manager
To install a new library into your Arduino IDE you can use the Library Manager
(available from IDE version 1.8.0). Open the IDE and click to the "Sketch" menu and
then Include Library > Manage Libraries.
24
/
223
Then the library manager will open and you will find a list of libraries that are already
and wait.
installed or ready for installation. In this example we will install the Bridge library.
Scroll the list to find it, then select the version of the library you want to install.
Sometimes only one version of the library is available. If the version selection menu
does not appear, don't worry: it is normal.
There are times you have to be patient with it, just as shown in the figure. Please refresh it
25
/
223
Finally click on install and wait for the IDE to install the new library. Downloading
may take time depending on your connection speed. Once it has finished,
an Installed tag should appear next to the Bridge library. You can close the library
manager.
You can now find the new library available in the Include Library menu. If you want
to add your own library open a new issue on Github.
Importing a .zip Library
Libraries are often distributed as a ZIP file or folder. The name of the folder is the
name of the library. Inside the folder will be a .cpp file, a .h file and often a
keywords.txt file, examples folder, and other files required by the library. Starting
with version 1.0.5, you can install 3rd party libraries in the IDE. Do not unzip the
downloaded library, leave it as is.
In the Arduino IDE, navigate to Sketch > Include Library. At the top of the drop down
list, select the option to "Add .ZIP Library''.
3
26
/ 22
You will be prompted to select the library you would like to add. Navigate to the .zip
file's location and open it.
27
/
223
Return to the Sketch > Import Library menu. You should now see the library at the
bottom of the drop-down menu. It is ready to be used in your sketch. The zip file
will have been expanded in the libraries folder in your Arduino sketches directory.
NB: the Library will be available to use in sketches, but examples for the library will
not be exposed in the File > Examples until after the IDE has restarted.
Those two are the most common approaches. MAC and Linux systems can be
handled likewise. The manual installation to be introduced below as an alternative
may be seldom used and users with no needs may skip it.
Manual installation
To install the library, first quit the Arduino application. Then uncompress the ZIP file
containing the library. For example, if you're installing a library called
28
/
223
"ArduinoParty", uncompress ArduinoParty.zip. It should contain a folder
calledArduinoParty, with files like ArduinoParty.cpp and ArduinoParty.h inside. (If
the .cpp and .h files aren't in a folder, you'll need to create one. In this case, you'd
make a folder called "ArduinoParty" and move into it all the files that were in the
ZIP file, like ArduinoParty.cpp and ArduinoParty.h.)
Drag the ArduinoParty folder into this folder (your libraries folder). Under Windows,
it will likely be called "My Documents\Arduino\libraries". For Mac users, it will likely
be called "Documents/Arduino/libraries". On Linux, it will be the "libraries" folder
in your sketchbook.
Your Arduino library folder should now look like this (on Windows):
My Documents\Arduino\libraries\ArduinoParty\ArduinoParty.cpp My Documents\Arduino\libraries\ArduinoParty\ArduinoParty.h My Documents\Arduino\libraries\ArduinoParty\examples
or like this (on Mac and Linux):
Documents/Arduino/libraries/ArduinoParty/ArduinoParty.cpp Documents/Arduino/libraries/ArduinoParty/ArduinoParty.h Documents/Arduino/libraries/ArduinoParty/examples
....
There may be more files than just the .cpp and .h files, just make sure they're all
there. (The library won't work if you put the .cpp and .h files directly into the
libraries folder or if they're nested in an extra folder. For example:
Documents\Arduino\libraries\ArduinoParty.cpp and
Documents\Arduino\libraries\ArduinoParty\ArduinoParty\ArduinoParty.cpp won't
work.)
Restart the Arduino application. Make sure the new library appears in the Sketch-
>Import Library menu item of the software. That's it! You've installed a library!
Arduino Serial Monitor (Windows, Mac, Linux)
The Arduino Integrated Development Environment (IDE) is the software side of the
Arduino platform. And, because using a terminal is such a big part of working with
29
/
223
Arduinos and other microcontrollers, they decided to include a serial terminal with
the software. Within the Arduino environment, this is called the Serial Monitor.
Making a Connection
Serial monitor comes with any and all version of the Arduino IDE. To open it, simply
click the Serial Monitor icon.
Selecting which port to open in the Serial Monitor is the same as selecting a port for
uploading Arduino code. Go to Tools -> Serial Port, and select the correct port.
Tips: Choose the same COM port that you have in Device Manager.
30
/
223
Once open, you should see something like this:
31
/
223
Settings
The Serial Monitor has limited settings, but enough to handle most of your serial
communication needs. The first setting you can alter is the baud rate. Click on the
baud rate drop-down menu to select the correct baud rate. (9600 baud)
Last, you can set the terminal to Autoscroll or not by checking the box in the bottom
left corner.
Pros
The Serial Monitor is a great quick and easy way to establish a serial connection with
your Arduino. If you’re already working in the Arduino IDE, there’s really no need to
open up a separate terminal to display data.
Cons
The lack of settings leaves much to be desired in the Serial Monitor, and, for
advanced serial communications, it may not do the trick.
32
/
223
Lesson 2 Blink
Principle
The ME
GA2560 R3
board has rows of con
nector
s along both sides that are used to
c
onnect to s
ever
al el
ectr
onic devices and plug-in 'shields' that extends its capability.
It
also has a single LED th
at y
ou can con
tro
l from your s
ketche
s. This LED is buil
t
onto
the
ME
GA2560 R3
board and is often
referred t
o as the 'L' LED as this is how i
t
is labeled on the board.
Overview
In this lesson, you will learn how to program your MEGA2560 R3 controller board to
blink the Arduino’s built-in LED, and how to download programs by basic steps.
Component Required:
(1) x Elegoo Mega2560 R3
33
/
223
You may find that your MEGA2560 R3 board's 'L' LED already blinks when you
connect it to a USB plug. This is because the boards are generally shipped with the
'Blink' sketch pre-installed.
In this lesson, we will reprogram the MEGA2560 R3 board with our own Blink sketch
and then change the rate at which it blinks.
In Lesson 0, you set up your Arduino IDE and made sure that you could find the right
serial port for it to connect to your MEGA2560 R3 board. The time has now come to
put that connection to the test and program your MEGA2560 R3 board.
The Arduino IDE includes a large collection of example sketches that you can load
up and use. This includes an example sketch for making the 'L' LED blink.
Load the 'Blink' sketch that you will find in the IDE's menu system under File >
Examples > 01.Basics
34
/
223
When the sketch window opens, enlarge it so that you can see the entire sketch in
the window.
The example sketches included with the Arduino IDE are 'read-only'. That is, you can
upload them to an MEGA2560 R3 board, but if you change them, you cannot save
them as the same file.
Since we are going to change this sketch, the first thing you need to do is save your
own copy.
From the File menu on the Arduino IDE, select 'Save As..' and then save the sketch
with the name 'MyBlink'.
35
/
223
36
/
223
You have saved your copy of 'Blink' in your sketchbook. This means that if you ever
want to find it again, you can just open it using the File > Sketchbook menu option.
37
/
223
Attach your Arduino board to your computer with the USB cable and check that the
'Board Type' and 'Serial Port' are set correctly.
38
/
223
39
/
223
Note: The Board Type and Serial Port here are not necessarily the same as shown
in picture. If you are using 2560, then you will have to choose Mega 2560 as the
Board Type, other choices can be made in the same manner. And the Serial Port
displayed for everyone is different, despite COM 26 chosen here, it could be COM3
or COM4 on your computer. A right COM port is supposed to be COMX (arduino
XXX), which is by the certification criteria.
The Arduino IDE will show you the current settings for board at the bottom of the
window.
Click on the 'Upload' button. The second button from the left on the toolbar.
If you watch the status area of the IDE, you will see a progress bar and a series of
messages. At first, it will say 'Compiling Sketch...'. This converts the sketch into a
format suitable for uploading to the board.
Next, the status will change to 'Uploading'. At this point, the LEDs on the Arduino
should start to flicker as the sketch is transferred.
40
/
223
Finally, the staus will change to 'Done'.
The other message tells us that the sketch is using 928 bytes of the 32,256 bytes
available.After the 'Compiling Sketch..' stage you could get the following error
message:
It can mean that your board is not connected at all, or the drivers have not been
installed (if necessary) or that the wrong serial port is selected.
If you encounter this, go back to Lesson 0 and check your installation.
Once the upload has completed, the board should restart and start blinking.
Open the code
Note that a huge part of this sketch is composed of comments. These are not actual
program instructions; rather, they just explain how the program works. They are
there for your benefit.
Everything between /* and */ at the top of the sketch is a block comment; it explains
what the sketch is for.
41
/
223
Single line comments start with // and everything up until the end of that line is
considered a comment.
The first line of code is:
int led = 13;
As the comment above it explains, this is giving a name to the pin that the LED is
attached to. This is 13 on most Arduinos, including the MEGA2560 and Leonardo.
Next, we have the 'setup' function. Again, as the comment says, this is executed
when the reset button is pressed. It is also executed whenever the board resets for
any reason, such as power first being applied to it, or after a sketch has been
uploaded.
void setup() {
// initialize the digital pin as an output.
pinMode(led, OUTPUT);
}
Every Arduino sketch must have a 'setup' function, and the place where you might
want to add instructions of your own is between the { and the }.
In this case, there is just one command there, which, as the comment states tells
the Arduino board that we are going to use the LED pin as an output.
It is also mandatory for a sketch to have a 'loop' function. Unlike the 'setup' function
that only runs once, after a reset, the 'loop' function will, after it has finished running
its commands, immediately start again.
void loop() {
digitalWrite(led, HIGH); // turn the LED on (HIGH is the voltage level) delay(1000); // wait for a second digitalWrite(led, LOW); // turn the LED off by making the voltage LOW delay(1000); // wait for a second
}
Inside the loop function, the commands first of all turn the LED pin on (HIGH), then
'delay' for 1000 milliseconds (1 second), then turn the LED pin off and pause for
another second.
You are now going to make your LED blink faster. As you might have guessed, the
key to this lies in changing the parameter in () for the 'delay' command.
42
/
223
This delay period is in milliseconds, so if you want the LED to blink twice as fast,
change the value from 1000 to 500. This would then pause for half a second each
delay rather than a whole second.
Upload the sketch again and you should see the LED start to blink more quickly.
43
/
223
Lesson 3 LED
Overview
In this lesson, you will learn how to change the brightness of an LED by using
different values of resistor.
Component Required:
(1) x Elegoo Mega2560 R3
(1) x 5mm red LED
(1) x 220 ohm resistor
(1) x 1k ohm resistor
(1) x 10k ohm resistor
(2) x M-M wires (Male to Male jumper wires)
Component Introduction
BREADBOARD MB-102
A breadboard enables you to prototype circuits quickly, without having to solder
the connections. Below is an example.
44
/
223
Breadboards come in various sizes and configurations. The simplest kind is just a
grid of holes in a plastic block. Inside are strips of metal that provide electrical
connection between holes in the shorter rows. Pushing the legs of two different
components into the same row joins them together electrically. A deep channel
running down the middle indicates that there is a break in connections there,
meaning, you can push a chip in with the legs at either side of the channel without
connecting them together. Some breadboards have two strips of holes running
along the long edges of the board that are separated from the main grid. These have
strips running down the length of the board inside and provide a way to connect a
common voltage. They are usually in pairs for +5 volts and ground. These strips are
referred to as rails and they enable you to connect power to many components or
points in the board.
While breadboards are great for prototyping, they have some limitations. Because
the connections are push-fit and temporary, they are not as reliable as soldered
connections. If you are having intermittent problems with a circuit, it could be due
to a poor connection on a breadboard.
LED:
LEDs make great indicator lights. They use very little electricity and they pretty much
last forever.
In this lesson, you will use perhaps the most common of all LEDs: a 5mm red LED.
5mm refers to the diameter of the LED. Other common sizes are 3mm and 10mm.
You cannot directly connect an LED to a battery or voltage source because 1) the
LED has a positive and a negative lead and will not light if placed the wrong way and
2) an LED must be used with a resistor to limit or 'choke' the amount of current
flowing through it; otherwise, it will burn out!
45
/
223
If you do not use a resistor with an LED, then it may well be destroyed almost
immediately, as too much current will flow through, heating it and destroying the
'junction' where the light is produced.
There are two ways to tell which is the positive lead of the LED and which the
negative.
Firstly, the positive lead is longer.
Secondly, where the negative lead enters the body of the LED, there is a flat edge
to the case of the LED.
If you happen to have an LED that has a flat side next to the longer lead, you should
assume that the longer lead is positive.
RESISTORS:
As the name suggests, resistors resist the flow of electricity. The higher the value of
the resistor, the more it resists and the less electrical current will flow through it.
We are going to use this to control how much electricity flows through the LED and
therefore, how brightly it shines.
But first, more about resistors...
The unit of resistance is called the Ohm, which is usually shortened to Ω the Greek
letter Omega. Because an Ohm is a low value of resistance (it doesn't resist much at
all), we also denote the values of resistors in (1,000 Ω) and (1,000,000 Ω).
These are called kilo-ohms and mega-ohms.
In this lesson, we are going to use three different values of resistor: 220Ω, 1kΩ and
10kΩ. These resistors all look the same, except that they have different colored
stripes on them. These stripes tell you the value of the resistor.
The resistor color code has three colored stripes and then a gold stripe at one end.
46
/
223
Unlike LEDs, resistors do not have a positive and negative lead. They can be
connected either way around.
If you find this approach method too complicated, you can read the color ring flag
on our resistors directly to determine its resistance value. Or you may use a digital
multimeter instead.
47
/
223
Connection
Schematic
48
/
223
Wiring diagram
49
/
223
The MEGA2560 is a convenient source of 5 volts, which we will use to provide power
to the LED and the resistor. You do not need to do anything with your MEGA2560,
except to plug it into a USB cable.
With the 220 Ω resistor in place, the LED should be quite bright. If you swap out the
220 Ω resistor for the 1kΩ resistor, then the LED will appear a little dimmer. Finally,
with the 10 kΩ resistor in place, the LED will be just about visible. Pull the red jumper
lead out of the breadboard and touch it into the hole and remove it, so that it acts
like a switch. You should just be able to notice the difference.
At the moment, you have 5V going to one leg of the resistor, the other leg of the
resistor going to the positive side of the LED and the other side of the LED going to
GND. However, if we moved the resistor so that it came after the LED, as shown
below, the LED will still light.
You will probably want to put the 220Ω resistor back in place.
It does not matter which side of the LED we put the resistor, as long as it is there
somewhere
Example picture
50
/
223
Overview
Lesson 4 RGB LED
RGB LEDs are a fun and easy way to add some color to your projects. Since they are
like 3 regular LEDs in one, how to use and connect them is not much different.
They come mostly in 2 versions: Common Anode or Common Cathode.
Common Anode uses 5V on the common pin, while Common Cathode connects to
ground.
As with any LED, we need to connect some resistors inline (3 total) so we can limit
the current being drawn.
In our sketch, we will start with the LED in the Red color state, then fade to Green,
then fade to Blue and finally back to the Red color. By doing this we will cycle
through most of the color that can be achieved.
Component Required:
(1) x Elegoo Mega2560 R3
(1) x 830 Tie Points Breadboard
(4) x M-M wires (Male to Male jumper wires)
(1) x RGB LED
(3) x 220 ohm resistors
51
/
223
Component Introduction
RGB:
At first glance, RGB (Red, Green and Blue) LEDs look just like regular LEDs. However,
inside the usual LED package, there are actually three LEDs, one red, one green and
yes, one blue. By controlling the brightness of each of the individual LEDs you can
mix pretty much any color you want.
We mix colors the same way you would mix paint on a palette - by adjusting the
brightness of each of the three LEDs. The hard way to do this would be to use
different value resistors (or variable resistors) as we did with in Lesson 2, but that's
a lot of work! Fortunately for us, MEGA2560 R3 board has an analogWrite function
that you can use with pins marked with a ~ to output a variable amount of power to
the appropriate LEDs.
The RGB LED has four leads. There is one lead going to the positive connection of
each of the single LEDs within the package and a single lead that is connected to all
three negative sides of the LEDs.
52
/
223
Here on the photographs you can see 4 electrode LED. Every separate pin for Green
or Blue or Red color is called Anode. You will always connect “+” to it. Cathode goes
to “-“ (ground). If you connect it other way round the LED will not light.
The common negative connection of the LED package is the second pin from the flat
side. It is also the longest of the four leads and will be connected to the ground.
Each LED inside the package requires its own 220Ω resistor to prevent too much
current flowing through it. The three positive leads of the LEDs (one red, one green
and one blue) are connected to MEGA2560 output pins using these resistors.
53
/
223
COLOR:
The reason that you can mix any color you like by varying the quantities of red, green
and blue light is that your eye has three types of light receptor in it (red, green and
blue). Your eye and brain process the amounts of red, green and blue and convert
it into a color of the spectrum.
In a way, by using the three LEDs, we are playing a trick on the eye. This same idea
is used in TVs, where the LCD has red, green and blue color dots next to each other
making up each pixel.
If we set the brightness of all three LEDs to be the same, then the overall color of
the light will be white. If we turn off the blue LED, so that just the red and green
LEDs are the same brightness, then the light will appear yellow.
We can control the brightness of each of the red, green and blue parts of the LED
separately, making it possible to mix any color we like.
Black is not so much a color as an absence of light. Therefore, the closest we can
come to black with our LED is to turn off all three colors.
54
/
223
Theory (PWM)
Pulse Width Modulation (PWM) is a technique for controlling power.
We also use it here to control the brightness of each of the LEDs.
The diagram below shows the signal from one of the PWM pins on the MEGA2560.
Roughly every 1/500 of a second, the PWM output will produce a pulse. The length
of this pulse is controlled by the 'analogWrite' function. So 'analogWrite(0)' will not
produce any pulse at all and 'analogWrite(255)' will produce a pulse that lasts all the
way until the next pulse is due, so that the output is actually on all the time.
If we specify a value in the analogWrite that is somewhere in between 0 and 255,
then we will produce a pulse. If the output pulse is only high for 5% of the time, then
whatever we are driving will only receive 5% of full power.
If, however, the output is at 5V for 90% of the time, then the load will get 90% of
the power delivered to it. We cannot see the LEDs turning on and off at that speed,
so to us, it just looks like the brightness is changing.
55
/
223
Connection
Schematic
56
/
223
Wiring diagram
57
/
223
Code
After wiring, please open the program in the code folder- Lesson 4 RGB LED, and
click UPLOAD to upload the program. See Lesson 2 for details about program
uploading if there are any errors.
Our code will use FOR loops to cycle through the colors.
The first FOR loop will go from RED to GREEN.
The second FOR loop will go from GREEN to BLUE.
The last FOR loop will go from BLUE to RED.
Try the sketch out and then we will dissect it in some detail......
The sketch starts by specifying which pins are going to be used for each of the colors:
// Define Pins
#define BLUE 3
#define GREEN 5
#define RED 6
The next step is to write the 'setup' function. As we have learnt in earlier lessons,
the setup function runs just once after the Arduino has reset. In this case, all it has
to do is define the three pins we are using as being outputs.
void setup()
{
pinMode(RED, OUTPUT);
pinMode(GREEN, OUTPUT);
pinMode(BLUE, OUTPUT);
digitalWrite(RED, HIGH);
digitalWrite(GREEN, LOW);
digitalWrite(BLUE, LOW);
}
Before we take a look at the 'loop' function, let’s look at the last function in the
sketch.
The define variables
redValue = 255; // choose a value between 1 and 255 to change the color.
greenValue = 0;
58
/
223
blueValue = 0;
This function takes three arguments, one for the brightness of the red, green and
blue LEDs. In each case the number will be in the range 0 to 255, where 0 means off
and 255 means maximum brightness. The function then calls 'analogWrite' to set
the brightness of each LED.
If you look at the 'loop' function you can see that we are setting the amount of red,
green and blue light that we want to display and then pausing for a second before
moving on to the next color.
#define delayTime 10 // fading time between colors
delay(delayTime);
Try adding a few colors of your own to the sketch and watch the effect on your LED.
Example picture
59
/
223
Lesson 5 Digital Inputs
Overview
In this lesson, you will learn to use push buttons with digital inputs to turn an LED
on and off.
Pressing the button will turn the LED on; pressing the other button will turn the LED
off.
Component Required:
(1) x Elegoo Mega2560 R3
(1) x 830 Tie-points Breadboard
(1) x 5mm red LED
(1) x 220 ohm resistor
(2) x push switches
(7) x M-M wires (Male to Male jumper wires)
Component Introduction
PUSH SWITCHES:
Switches are really simple components. When you press a button or flip a lever, they
connect two contacts together so that electricity can flow through them.
The little tactile switches that are used in this lesson have four connections, which
can be a little confusing.
Actually, there are only really two electrical connections. Inside the switch package,
pins B and C are connected together, as are A and D.
60
/
223
Connection
Schematic
61
/
Wiring diagram
223
Although the bodies of the switches are square, the pins protrude from opposite
sides of the switch. This means that the pins will only be far enough apart when they
are placed correctly on the breadboard.
Remember that the LED has to have the shorter negative lead to the left.
Code
After wiringplease open program in the code folder- Lesson 5 Digital Inputs, and
press UPLOAD to upload the program. If errors are prompted, see Lesson 2 for
details about the tutorial on program upload.
Load the sketch onto your MEGA2560 board. Pressing the left button will turn the
LED on while pressing the right button will turn it off.
The first part of the sketch defines three variables for the three pins that are to be
used. The 'ledPin' is the output pin and 'buttonApin' will refer to the switch nearer
the top of the breadboard and 'buttonBpin' to the other switch.
The 'setup' function defines the ledPin as being an OUTPUT as normal, but now we
have the two inputs to deal with. In this case, we use the set the pinMode to be
'INPUT_PULLUP' like this:
pinMode(buttonApin, INPUT_PULLUP);
pinMode(buttonBpin, INPUT_PULLUP);
The pin mode of INPUT_PULLUP means that the pin is to be used as an input, but that if nothing else is connected to the input, it should be 'pulled up' to HIGH. In other words, the default value for the input is HIGH, unless it is pulled LOW by the action of pressing the button. This is why the switches are connected to GND. When a switch is pressed, it connects the input pin to GND, so that it is no longer HIGH. Since the input is normally HIGH and only goes LOW when the button is pressed, the logic is a little upside down. We will handle this in the 'loop' function.
void loop() {
if (digitalRead(buttonApin) == LOW)
{
digitalWrite(ledPin, HIGH); } if (digitalRead(buttonBpin) == LOW)
62 / 223 63
/
223
{
digitalWrite(ledPin, LOW); }
}
In the 'loop' function there are two 'if' statements. One for each button. Each does an 'digitalRead' on the appropriate input. Remember that if the button is pressed, the corresponding input will be LOW, if button A is low, then a 'digitalWrite' on the ledPin turns it on. Similarly, if button B is pressed, a LOW is written to the ledPin.
Example picture
Lesson 6 Active buzzer
T
he
diff
erence
be
twee
n the two is that an active bu
zzer
has a built-in oscillating
sour
ce,
so it will
generate
a sound
when electr
ified. A passive bu
zzer
does not ha
ve
such a source so it will not
tweet
if DC signals are us
ed;
instead, you need to us
e
square waves whose
fre
quency is be
tween 2K
and 5K to drive it. T
he active
buz
zer
is often more expensive than
the
passive o
ne bec
ause of multiple built-in oscillating
circ
uits.
64
/
223
Overview
In this lesson, you will learn how to generate a sound with an active buzzer.
Component Required:
(1) x Elegoo Mega2560 R3
(1) x Active buzzer (2) x F-M wires (Female to Male DuPont wires)
Component Introduction
BUZZER:
Electronic buzzers are DC-powered and equipped with an integrated circuit. They are widely used in computers, printers, photocopiers, alarms, electronic toys, automotive electronic devices, telephones, timers and other electronic products for voice devices. Buzzers can be categorized as active and passive ones. Turn the pins of two buzzers face up. The one with a green circuit board is a passive buzzer, while the other enclosed with a black tape is an active one.
65
/
223
Connection
Schematic
Wiring diagram
66 / 223
67
/
223
Code
After wiring, please open the program in the code folder- Lesson 6 Making Sounds and click UPLOAD to upload the program. See Lesson 2 for details about program uploading if there are any errors.
Example picture
Lesson 7 Passive Buzzer
midrange Mi. By the buzz
er, y
ou can play a song.
We
should be careful not to use the ME
GA2560 R3
board analog Write () function
to
generate
a pulse to
the
bu
zzer,
because the pulse output of analog Write () is
fixed (500Hz).
68
/
223
Overview
In this lesson, you will learn how to use a passive buzzer. The purpose of the experiment is to generate eight different sounds, each sound lasting 0.5 seconds: from Alto Do (523Hz), Re (587Hz), Mi (659Hz), Fa (698Hz), So (784Hz), La (880Hz), Si (988Hz) to Treble Do (1047Hz).
Component Required:
(1) x Elegoo Mega2560 R3
(1) x Passive buzzer (2) x F-M wires (Female to Male DuPont wires)
Component Introduction
Passive Buzzer:
The working principle of passive buzzer is using PWM generating audio to make the air to vibrate. Appropriately changed as long as the vibration frequency, it can generate different sounds. For example, sending a pulse of 523Hz, it can generate Alto Do, pulse of 587Hz, it can generate midrange Re, pulse of 659Hz, it can produce
69
/
223
Connection
Schematic
70
/
223
Wiring diagram
71
/
223
Wiring the buzzer connected to the MEGA2560 R3 board, the red (positive) to the pin8, black wire (negative) to the GND.
Code
After wiring, please open the program in the code folder- Lesson 7 Passive Buzzer and click UPLOAD to upload the program. See Lesson 2 for details about program uploading if there are any errors. Before you can run this, make sure that you have installed the <pitches> library or re-install it, if necessary. Otherwise, your code won't work. For details about loading the library file, see Lesson 1.
Example picture
72
/
223
Lesson 8 Tilt Ball Switch
Overview
In this lesson, you will learn how to use a tilt ball switch in order to detect small angle of inclination.
Component Required:
(1) x Elegoo Mega2560 R3
(1) x Tilt Ball switch (2) x F-M wires (Female to Male DuPont wires)
Component Introduction
Tilt sensor:
Tilt sensors (tilt ball switch) allow you to detect orientation or inclination. They are small, inexpensive, low-power and easy-to-use. If used properly, they will not wear out. Their simplicity makes them popular for toys, gadgets and appliances. Sometimes, they are referred to as "mercury switches", "tilt switches" or "rolling ball sensors" for obvious reasons. They are usually made up of a cavity of some sort (cylindrical is popular, although not always) with a conductive free mass inside, such as a blob of mercury or rolling ball. One end of the cavity has two conductive elements (poles). When the sensor is oriented so that that end is downwards, the mass rolls onto the poles and shorts them, acting as a switch throw. While not as precise or flexible as a full accelerometer, tilt switches can detect motion or orientation. Another benefit is that the big ones can switch power on their own. Accelerometers, on the other hand, output digital or analog voltage that must then be analyzed using extra circuitry.
73
/
223
Connection
Schematic
74
/
223
Wiring diagram
75
/
223
Code
After wiring, please open the program in the code folder- Lesson 8 Ball Switch and click UPLOAD to upload the program. See Lesson 2 for details about program uploading if there are any errors.
Example picture
D
ime
nsion : 1.26 in x 1.18 in x 0.47 in (3.2 cm x 3 cm x 1.2 cm)
We
ight : 4.73 oz (
134 g
)
76
/
223
Overview
Lesson 9 Servo
Servo is a type of geared motor that can only rotate 180 degrees. It is controlled by sending electrical pulses from your 2560 R3 board. These pulses tell the servo what position it should move to. The Servo has three wires, of which the brown one is the ground wire and should be connected to the GND port of 2560, the red one is the power wire and should be connected to the 5v port, and the orange one is the signal wire and should be connected to the Dig #9 port.
Component Required:
(1) x Elegoo Mega2560 R3 (1) x Servo (SG90) (3) x M-M wires (Male to Male jumper wires)
Component Introduction
SG90
Universal for JR and FP connector
Cable length : 25cm
No load; Operating speed: 0.12 sec / 60 degree (4.8V), 0.10 sec / 60 degree (6.0V)
Stall torque (4.8V): 1.6kg/cm
Temperature : -30~60'C
Dead band width: 5us
Working voltage: 3.5~6V
77
/
223
Connection
Schematic
78
/
223
Wiring diagram
79
/
223
Code
After wiring, please open the program in the code folder- Lesson 9 Servo and click UPLOAD to upload the program. See Lesson 2 for details about program uploading if there are any errors. Before you can run this, make sure that you have installed the < Servo> library or re-install it, if necessary. Otherwise, your code won't work.
For details about loading the library file, see Lesson 1.
Example picture
In the picture, the brown wire of servo is adapted via the black M-M wires, the red one is adapted via the red M-M wires, and the orange one is adapted via the yellow M-M wires.
80
/
223
Overview
Lesson 10 Ultrasonic Sensor Module
Ultrasonic sensor is great for all kind of projects that need distance measurements, avoiding obstacles as examples. The HC-SR04 is inexpensive and easy to use since we will be using a Library specifically designed for these sensor.
Component Required:
(1) x Elegoo Mega2560 R3 (1) x Ultrasonic sensor module (4) x F-M wires (Female to Male DuPont wires)
Component Introduction
Ultrasonic sensor
Ultrasonic sensor module HC-SR04 provides 2cm-400cm non-contact measurement function, the ranging accuracy can reach to 3mm. The modules includes ultrasonic transmitters, receiver and control circuit. The basic principle of work:
(1) Using IO trigger for at least 10us high level signal, (2) The Module automatically sends eight 40 kHz and detect whether there is a pulse
signal back.
(3) IF the signal back, through high level , time of high output IO duration is the time
from sending ultrasonic tore turning. Test distance = (high level time × velocity of sound (340m/s) /2 The Timing diagram is shown below. You only need to supply a short 10us pulse to the trigger input to start the ranging, and then the module will send out an 8 cycle burst of ultrasound at 40 kHz and raise its echo. The Echo is a distance object that is pulse width and the range in proportion .You can calculate the range through the time interval between sending trigger signal and receiving echo signal. Formula: us / 58 = centimeters or us / 148 =inch; or: the range = high level time * velocity (340M/S) / 2; we suggest to use over 60ms measurement cycle, in order to prevent trigger signal to the echo signal.
81
/
223
Connection
Schematic
Wiring diagram
82 / 223
83
/
223
Code
Using a Library designed for these sensors will make our code short and simple. We include the library at the beginning of our code, and then by using simple commands we can control the behavior of the sensor.
After wiring, please open the program in the code folder- Lesson 10 Ultrasonic Sensor Module and click UPLOAD to upload the program. See Lesson 2 for details about program uploading if there are any errors. Before you can run this, make sure that you have installed the < HC-SR04> library or re-install it, if necessary. Otherwise, your code won't work.
For details about loading the library file, see Lesson 1.
Example picture
Open the monitor then you can see the data as blow:
Click the Serial Monitor button to turn on the serial monitor. The basics about the serial monitor are introduced in details in Lesson 1.
84 / 223
Overview
Lesson 11 Membrane Switch Module
In this project, we will go over how to integrate a keyboard with an MEGA2560 R3 board so that the MEGA2560 R3 can read the keys being pressed by a user. Keypads are used in all types of devices, including cell phones, fax machines, microwaves, ovens, door locks, etc. They're practically everywhere. Tons of electronic devices use them for user input. So knowing how to connect a keypad to a microcontroller such as an MEGA2560 R3 board is very valuable for building many different types of commercial products. At the end when all is connected properly and programmed, when a key is pressed, it shows up at the Serial Monitor on your computer. Whenever you press a key, it shows up on the Serial Monitor. For simplicity purposes, we start at simply showing the key pressed on the computer. For this project, the type of keypad we will use is a matrix keypad. This is a keypad that follows an encoding scheme that allows it to have much less output pins than there are keys. For example, the matrix keypad we are using has 16 keys (0-9, A-D, *, #), yet only 8 output pins. With a linear keypad, there would have to be 17 output pins (one for each key and a ground pin) in order to work. The matrix encoding scheme allows for less output pins and thus much less connections that have to make for the keypad to work. In this way, they are more efficient than linear keypads, being that they have less wiring.
Component Required:
(1) x Elegoo Mega2560 R3 (1) x Membrane switch module (8) x M-M wires (Male to Male jumper wires)
85 / 223
86
/
223
Connection
Schematic
87
/
223
Wiring diagram
88
/
223
When connecting the pins to the MEGA2560 R3 board, we connect them to the digital output pins, D9-D2. We connect the first pin of the keypad to D9, the second pin to D8, the third pin to D7, the fourth pin to D6, the fifth pin to D5, the sixth pin to D4, the seventh pin to D3, and the eighth pin to D2. These are the connections in a table:
Code
After wiring, please open the program in the code folder- Lesson 11 Membrane Switch Module and click UPLOAD to upload the program. See Lesson 2 for details about program uploading if there are any errors. Before you can run this, make sure that you have installed the < Keypad> library or re-install it, if necessary. Otherwise, your code won't work. For details about loading the library file, see Lesson 1.
89
/
223
Example picture
90
/
223
With this code, once we press a key on the keypad, it should show up on the serial monitor of the Arduino software once the code is compiled and uploaded to the MEGA2560 R3 board.
Click the Serial Monitor button to turn on the serial monitor. The basics about the serial monitor are introduced in details in Lesson 1.
91
/
223
Lesson 12 DHT11 Temperature and Humidity Sensor
Overview
In this tutorial we will learn how to use a DHT11 Temperature and Humidity Sensor. It’s accurate enough for most projects that need to keep track of humidity and temperature readings. Again we will be using a Library specifically designed for these sensors that will make our code short and easy to write.
Component Required:
(1) x Elegoo Mega2560 R3 (1) x DHT11 Temperature and Humidity module (3) x F-M wires (Female to Male DuPont wires)
Component Introduction
Temp and humidity sensor:
DHT11 digital temperature and humidity sensor is a composite Sensor which contains a calibrated digital signal output of the temperature and humidity. The dedicated digital modules collection technology and the temperature and humidity sensing technology are applied to ensure that the product has high reliability and
92
/
223
excellent long-term stability. The sensor includes a resistive sense of wet components and a NTC temperature measurement devices, and connects with a high-performance 8-bit microcontroller. Applications: HVAC, dehumidifier, testing and inspection equipment, consumer goods, automotive, automatic control, data loggers, weather stations, home appliances, humidity regulator, medical and other humidity measurement and control.
Product parameters
Relative humidity: Resolution: 16Bit Repeatability: ±1% RH
Accuracy: At 25±5% RH
Interchangeability: fully interchangeable Response time: 1 / e (63%) of 256s
1m / s air 6s Hysteresis: <± 0.3% RH Long-term stability: <± 0.5% RH / yr in Temperature: Resolution: 16Bit
Repeatability: ±0.2
Range: At 25±2
Response time: 1 / e (63%) 10S Electrical Characteristics Power supply: DC 3.55.5V
Supply Current: measurement 0.3mA standby 60μA Sampling period: more than 2 seconds Pin Description: 1, the VDD power supply 3.55.5V DC 2 DATA serial data, a single bus 3, NC, empty pin 4, GND ground, the negative power
93
/
223
Connection
Schematic
Wiring diagram
94 / 223
95
/
223
As you can see we only need 3 connections to the sensor, since one of the pin is not used. The connections are: Voltage, Ground and Signal which can be connected to any Pin on our MEGA2560.
Code
After wiring, please open the program in the code folder- Lesson 12 DHT11 Temperature and Humidity Sensor and click UPLOAD to upload the program. See Lesson 2 for details about program uploading if there are any errors. Before you can run this, make sure that you have installed the < SimpleDHT> library or re-install it, if necessary. Otherwise, your code won't work.
For details about the tutorial on the loading of library file, see Lesson 1.
Example picture
Upload the program then open the monitor, we can see the data as below: (It shows the temperature of the environment, we can see it is 22 degree)
Click the Serial Monitor button to turn on the serial monitor. The basics about the serial monitor are introduced in details in Lesson 1.
96 / 223
Lesson 13 Analog Joystick Module
Overview
Analog joysticks are a great way to add some control in your projects. In this tutorial we will learn how to use the analog joystick module.
Component Required:
(1) x Elegoo Mega2560 R3 (1) x Joystick module (5) x F-M wires (Female to Male DuPont wires)
Component Introduction
Joystick
The module has 5 pins: VCC, Ground, X, Y, Key. Note that the labels on yours may be slightly different, depending on where you got the module from. The thumb stick is analog and should provide more accurate readings than simple ‘directional’ joysticks tact use some forms of buttons, or mechanical switches. Additionally, you can press the joystick down (rather hard on mine) to activate a ‘press to select’ push- button. We have to use analog Arduino pins to read the data from the X/Y pins, and a digital pin to read the button. The Key pin is connected to ground, when the joystick is pressed down, and is floating otherwise. To get stable readings from the Key /Select pin, it needs to be connected to VCC via a pull-up resistor. The built in resistors on the Arduino digital pins can be used. For a tutorial on how to activate the pull-up resistors for Arduino pins, configured as inputs
97 / 223
Connection
Schematic
98 / 223
Wiring diagram
99 / 223
100
/
223
We need 5 connections to the joystick. The connections are: Key, Y, X, Voltage and Ground. “Y and X” are Analog and “Key” is Digital. If you don’t need the switch then you can use only 4 pins.
Code
After wiring, please open the program in the code folder- Lesson 13 Analog Joystick Module and click UPLOAD to upload the program. See Lesson 2 for details about program uploading if there are any errors.
Analog joysticks are basically potentiometers so they return analog values. When the joystick is in the resting position or middle, it should return a value of about 512. The range of values goes from 0 to 1024.
Example picture
Loading...