Download as pdf or txt
Download as pdf or txt
You are on page 1of 134

Ó Copyright 2017 by Dteam - All rights reserved.

This document is geared towards providing exact and reliable information in regards to the topic and issue
covered. The publication is sold with the idea that the publisher is not required to render accounting, officially
permitted, or otherwise, qualified services. If advice is necessary, legal or professional, a practiced individual in
the profession should be ordered.

- From a Declaration of Principles which was accepted and approved equally by a Committee of the American Bar
Association and a Committee of Publishers and Associations.

In no way is it legal to reproduce, duplicate, or transmit any part of this document in either electronic means or in
printed format. Recording of this publication is strictly prohibited and any storage of this document is not allowed
unless with written permission from the publisher. All rights reserved.

The information provided herein is stated to be truthful and consistent, in that any liability, in terms of inattention
or otherwise, by any usage or abuse of any policies, processes, or directions contained within is the solitary and
utter responsibility of the recipient reader. Under no circumstances will any legal responsibility or blame be held
against the publisher for any reparation, damages, or monetary loss due to the information herein, either directly
or indirectly.

Respective authors own all copyrights not held by the publisher.

The information herein is offered for informational purposes solely, and is universal as so. The presentation of the
information is without contract or any type of guarantee assurance.

The trademarks that are used are without any consent, and the publication of the trademark is without permission
or backing by the trademark owner. All trademarks and brands within this book are for clarifying purposes only
and are the owned by the owners themselves, not affiliated with this document.
Contents
BASICS OF ELECTRONICS
LED
Resistors
Capacitors
Transistor
Diode
Variable Resistor
Light Dependent Resistor
DC Motor
Push Button
Temperature Sensor
DHT11 Digital Temperature and Humidity Sensor
Piezo Buzzer
Servo Motor
16x2 LCD display
Sound Sensor
Connecting wires
Breadboard
GETTING STARTED
Basic Programming in Arduino IDE
Programming Multiple LEDs
Programming for a Push button and a LED
Using a Potentiometer (analog sensor)
PWM using Potentiometer and LED
Servo Motor with Arduino
Joystick
Flame Sensor
RGB LED
RGB SMD LED
Heartbeat sensor
LIGHT CUP SENSOR
Hall Magnetic Sensor
RELAY
7 color Flash LED
Mercury Tilt switch
DS18B20 Temperature Sensor
Analog Thermistor Temperature Sensor
TEMPERATURE AND HUMIDITY SENSOR MODULE
Sound Sensor
Metal Touch Sensor
Two Color LED Module
INFRARED RECEIVER MODULE
INFRARED TRANSMITTER MODULE
LASER TRANSMITTER MODULE
PHOTORESISTOR MODULE
MERCURY TILT SWITCH MODULE
PHOTO INTERRUPTER MODULE
VIBRATION SWITCH MODULE
KEY SWITCH MODULE
ACTIVE BUZZER MODULE
PASSIVE BUZZER MODULE
Ball Switch
Magnetic Reed Switch
Line Tracking Sensor
Rotary Encoder Sensor
Resources
BASICS OF ELECTRONICS

LED
An LED is acronym for Light Emitting Diode, it is a type of diode that illuminates when
electricity passes through it. Their voltage drop is higher than a normal diode, from1.2v for an
infrared LED, up to 3.5v for blue and ultraviolet LED. These LED’s comes in different size and
different colours. If you take closer look to that LED picture, one lead (leg) of the LED’s shorter
and another one is longer. Shorter one is known as cathode (negative (-) symbol) and the longer
one is known as anode (positive (+) symbol). If the current passing through the LED is too high,
you will lose LED. A LED can withstand up to 3.5v, output voltage from the Arduino pins are
5V to step down this voltage, a resistor in series with LED should use to prevent the LED from
hurt.
Resistors
Resist the flow of electrical current in circuit, in other words they limit the flow of electrons. The
SI unit of resistance is Ohms, written as the Greek letter omega (Ω). They are often used with the
unit prefixes kilo (k) and mega (M). The value of resistor indicated by 4 or 5 colour band bands,
using the resistor color code:
The first 2 bands are the first digits of the value, and the 3rd band is the power of ten that comes
after those 2 digits. This is also called the multiplier, and is just the number of zeros you have to
add. The last band is the tolerance and mostly it will be silver or gold color.
“BB ROY Great Britain Very Good Wife”, try to memorise this sentence which allows you to
remember 9 color bands in the resistor. First b represents black, second b represents brown, R
represents Red, O represents Orange, Y represents yellow, first word in Great G represents
Green, first word in Britain B represents Blue, first word in Very V represents violet, first letter
in G represents Grey and, first letter in Wife W represents White.

Color 1st Band 2nd Band 3rd Band 4th Band


(1st digit) (2nd digit) (Multiplier) (tolerance)
Black 0 0 1Ω
Brown 1 1 10Ω ±1%
Red 2 2 100Ω ±2%
Orange 3 3 1000 or 1kΩ
Yellow 4 4 10kΩ
Green 5 5 100kΩ ±0.5%
Blue 6 6 1MΩ ±0.25%
Violet 7 7 10MΩ ±0.1%
Grey 8 8 ±0.05%
White 9 9
Gold 0.1Ω ±5%
Silver 0.01Ω ±10%

Eg: The first resistor toward right, in the above picture shows Brown RED RED color, First band
is Brown look up the table to find 1st digital value for this color, value for the brown color in the
first digit is ‘1’, second color is Red, if you look up the table for the 2nd digit value color for the
Red is 2 and the third color is also red, if you look up the table for 3rd Band it is multiplier and
the value is 100 ohms
If we join all the value together, 1 2 * 100
And the final value will be 1200, the resistance value is 1200 Ω.
Capacitors
These components store and release electrical energy in a circuit. It behaves like a small
rechargeable battery. Capacitors are used in filters. The SI unit of capacitance is farad, of F. This
is a very large unit and most often, you will see prefixes like pico(p), nano (n) or micro (µ).
Often placed across power and ground close to a sensor or motor to help fluctuation in voltage.
Transistor
A transistor is a semiconductor device, which is used to switch or amplify a signal. You can
think of it as a switch that can be operated by using a very weak signal, a current controlled
switch.
A transistor has three terminals: they are called the base (B), the emitter (E) and the collector (C).
The emitter 'emits' electrons, and they are 'collected' by the collector. The base is used to control
this flow of electrons. If a small current flows from the base to the emitter, a much larger current
will flow from the collector to the emitter. How much larger this C-E current is, depends on a
constant, specific to the type of transistor. This constant is called the DC current gain, and has
the symbol of the Greek letter bèta (β) or Hfe.
E.g. if you have a transistor with β = 100, and your B-E current = 10mA, your C-E current will
be 1A. This principle is used in amplifiers.
However, a transistor cannot keep on amplifying forever: at a certain point, the transistor will
just act like a switch.
Diode
Just like a transistor, a diode is a semiconductor device. One of the interesting properties of a
diode, is that they only conduct electricity in one direction.
For example, Arduino boards have a diode in series with their power input jack, to prevent you
from reversing the power, and damaging the chip.
Diodes have a forward voltage drop ranging from 0.5v to 0.7v. This means that if you measure
the voltage before the diode, it will be about 600mV higher than after the Diode, a diode has its
limits: if the reverse voltage is too high, it will break, causing it to let current pass in the wrong
direction. In some diodes, this is done in a controlled way. These diodes are called zener diodes.
They will only conduct if the voltage is higher than a certain value, specific to the zener. This
value is constant, so zener diodes are used as a reference in voltage regulators.
Variable Resistor
We have seen about Resistors previously, and the resistor value in those resistors cannot be
changed, but in this resistor it is possible to change the resistance value. These resistors comes
with three pins. Two pins are connected to the ends of a fixed resistor. The middle pin or wiper
moves across the resistor dividing it into two halves. When the external sides of the
potentiometer are connected to voltage and ground the middle leg will give the difference in
voltage as you turn the knob. This type of resistor also called as potentiometer or Pot. For
example if you have a 10k ohms variable resistor, you can vary the resistance from 0 to 10k by
rotating the knob. Mostly these type of resistors used with Arduino to control PWM pins
available in the Arduino.
Light Dependent Resistor
As the name suggests these are type of resistor where the resistance change depends on the
amount of light falls on the resistor head. This is also known as photo sensor or light sensor,
most of the yester years smart products use this simple sensor to do some magic. If you want to
make an automatic light controller system it is possible with this sensor. Resistance increase or
decrease depends on type of sensor.
DC Motor
A simple motor allow us to experiment with Arduino and work with fun projects. This a simple
DC motor which cannot be used for making movable objects, this motor cannot produce
necessary torque to move objects that’s the reason these motor coupled with gears to increase
torque and do some useful work. A motor converts electrical energy into mechanical energy
when electricity is applied to its leads.
Push Button
Push button or momentary switch used for giving inputs to Arduino. You can use this device
know how signal goes high or low based on the switch state.
Temperature Sensor
Lm35 is an Analog temperature sensor. This sensor can be used with any Arduino analog pins
A0 to A5. You have to do an analog read and do some mathematical calculation to change the
analog value to Temperature in Celsius or Fahrenheit. You can use any analog type sensor to get
a temperature value.
DHT11 Digital Temperature and Humidity Sensor

The DHT11 is a basic, ultra low-cost digital temperature and humidity


sensor. It uses a capacitive humidity sensor and a thermistor to measure the surrounding air, and
spits out a digital signal on the data pin (no analog input pins needed).
Piezo Buzzer
Piezo buzzer is an electronic device commonly used to produce sound.
Servo Motor
These are special type of motor, these motor are capable of rotating to a precise degree, but these
motor can move only from 0 to 180 degree. It is controlled by sending electrical pulses from
Arduino.
16x2 LCD display
Liquid display crystal are type of alphanumeric or graphic display based on liquid crystals. These
displays are available in many shapes and sizes, most popular are the 16x2 type displays which
has 2 rows and capable of display 16 characters on each row.
Sound Sensor
These sensor receive sound and covets to electrical pulses. With help of these sensor we can find
noise or sound level in a room.
Connecting wires
These wires are very useful connecting different components with Arduino. There are different
types of wires available male to male, male to female, female to female. You should have 5 wires
from each type for ease of connecting different components with Arduino.
Breadboard
Most important component in any project. This boards allows user to build circuits. It’s like a
patch panel, with rows of holes that allow you to connect wires and components together. This
eliminates the need for soldering of components.
Arduino is an open-source electronics prototyping platform based on flexible, easy-to-use
hardware and software. It's intended for artists, designers, hobbyists, and anyone interested in
creating interactive objects or environments.

Introduction: The Arduino environment has been designed to be easy to use for beginners who
have no software or electronics experience. With Arduino you can build objects that can respond
to and/or control light, sound, touch, and movement. Arduino has been used to create an amazing
variety of things, including musical instruments, robots, light sculptures, games, interactive
furniture, and even interactive clothing. Arduino is used in many educational programs around
the world, particularly by designers and artists who want to easily create prototypes but do not
need a deep understanding of the technical details behind their creations. Because it is designed
to be used by nontechnical people, the software includes plenty of example code to demonstrate
how to use the Arduino board‘s various facilities.
Though it is easy to use, Arduino‘s underlying hardware works at the same level of
sophistication that engineers employ to build embedded devices. People already working with
microcontrollers are also attracted to Arduino because of its agile development capabilities and
its facility for quick implementation of ideas. Arduino is best known for its hardware, but you
also need software to program that hardware. Both the hardware and software are called
―Arduinoǁ. The combination enables you to create projects that sense and control the physical
world. The software is free, open source, and cross-platform. The boards are inexpensive to buy,
or you can build your own (the hardware designs are also open source). In addition, there is an
active and supportive Arduino community that is accessible worldwide through the Arduino
forums and the wiki (known as the Arduino Playground). The forums and the wiki offer project
development examples and solutions to problems that can provide inspiration and assistance as
you pursue your own projects.
There is a large variety of Arduino boards and shields. Arduino boards are Microcontroller based
boards or you can say the brains of the robot. All the coding and programming is stored in this
microcontroller of the Arduino board. And Arduino shield is the attachment for doing a
particular task, like if you want to control the motors you will need a Motor shield with Arduino
board, or else you want to display anything you would need a display shield like Seven Segment
or LCD Shield. So there are many types of shields that are also available in market.
Arduino Boards

Arduino Shields

In this book we will use Arduino Uno which is widely used board in the Arduino family.

Arduino Uno Hardware


The Arduino Uno board is a small microcontroller board, which is a small circuit (the board)
that contains a whole computer on a small chip (the micro-controller). The Arduino board is
where the code you write is executed. The board can only control and respond to electricity, so
specific components are attached to it to enable it to interact with the real world. These
components can be sensors, which convert some aspect of the physical world to electricity so
that the board can sense it, or actuators, which get electricity from the board and convert it into
something that changes the world. Examples of sensors include switches, accelerometers, and
ultrasound distance sensors. Actuators are things like lights and LEDs, speakers, motors, and
displays. A brief explanation of what every element of the board does:

14 Digital IO pins (pins 0-13)


These can be inputs or outputs, which is specified by the sketch you create in the IDE.

6 Analogue In pins (pins 0-5)


These dedicated analogue input pins take analogue values (i.e., voltage readings from a sensor)
and convert them into a number between 0 and 1023.

6 Analogue Out pins (pins 3, 5, 6, 9, 10, and 11)


These are actually six of the digital pins that can be reprogrammed for analogue output using the
sketch you create in the IDE. The board can be powered from your computer‘s USB port, most
USB chargers, or an AC adapter (9 volts recommended, 2.1mm barrel tip, center positive).
GETTING STARTED
Arduino Software Software programs, called sketches, are created on a computer using the
Arduino Integrated Development Environment (IDE). The IDE enables you to write and edit
code and convert this code into instructions that Arduino understands. The IDE also transfers
those instructions to the Arduino board by a process called uploading.
The programming cycle on Arduino is basically as follows:
Plug your board into a USB port on your computer.
Write a sketch that will bring the board to life.
Upload this sketch to the board through the USB connection and wait a couple of
seconds for the board to restart.
The board executes the sketch that you wrote.

Follow the steps to program your Arduino for the first time.
Step 1: Open the Arduino IDE This is a program window where you write your code. As you
can see it is divided into three sections. First section consists of 5 Tabs File, Edit, Sketch, Tools,
and Help. Open one by one each tab and just study different options inside it. Below it you can
see few buttons like Tick Mark, Side Arrow, New File Button, Up Arrow, and Down Arrow.
And on the Right most corner side in the same line you will see a button for Serial Monitor; this
tab is used when serial communication is needed with computer.
Second section comprises of a large empty white space. This space is used to write your program
or sketch. Program is written in C language which is the most widely used language in computer
programming and is also very easy to understand. Third Section comprises of a Black window
where the status is shown, if there is an error on compiling the program then the error message is
shown in this window, if program gets uploaded successfully then that message is shown here.
Step 2: Board Selection
Go to the tools tab, in the drop down menu select ―Board, another window by its side will be
opened showing different type of boards.
Choose the Arduino Uno development board you are using currently
Step 3: Port Selection You need to select the port on which the board is connected. To do that
first you need to identify on which port the Arduino Uno development board is connected.
Port Identification: Windows On windows, the process is a bit more complicated. Open the
device manager by clicking the Start menu, right-clicking on Computer (Vista,) or My Computer
(XP, Win 7, Win 8 and Win 10), and choosing Properties. On Windows XP, Win 7, Win 8 and
Win 10, click Hardware and choose Device Manager. On other windows, click Device Manager
(it appears in the list of tasks on the left of the window).Look for the COM port device in the list
under ―Ports (COM & LPT) you will see Serial driver Manufacturer name or as USB Serial
Port. Check the port number which is written.
Port Identification: Macintosh Select the serial device of the Arduino board from the Tools >
Serial Port menu. On the Mac, this should be something with /dev/tty.usbmodem (for the Uno
or Mega 2560) or /dev/tty.usbserial (for older boards) in it.
Getting Started With Hello World
The LED blinking sketch is the first program that you should run to test whether your Arduino
board is working and is configured correctly. It is also usually the very first programming
exercise someone does when learning to program a microcontroller.

LED as you see is round or dome shaped from top with two legs coming out at the bottom. One
of the leg is longer than the other; it is because to identify the anode and cathode terminal. As
said before LED is a form of diode thus will conduct electricity or glow only when it is
connected properly i.e. positive terminal or anode of LED is connected to positive terminal of
battery and negative terminal or cathode of LED is connected to negative terminal of the battery.
When a LED is forward-biased (switched on), electrons are able to recombine with electron
holes within the device, releasing energy in the form of photons. This effect is called
electroluminescence and the color of the light (corresponding to the energy of the photon) is
determined by the energy gap of the semiconductor. LEDs present many advantages over
incandescent light sources including lower energy consumption, longer lifetime, improved
physical robustness, smaller size, and faster switching. LEDs powerful enough for room lighting
are relatively expensive and require more precise current and heat management than compact
fluorescent lamp sources of comparable output.
For blinking an external LED you need to use an external resistor for it too as by directly
connecting the LED to other pins may harm your Arduino board. Once the LED is connected,
you need to tell Arduino, what to do. This is done through the code, that is, a list of instructions
that we give the microcontroller to make it do what we want.

To write a sketch or a program first you need to open the Arduino IDE or Arduino software
where you installed it. After that select File>New and you will be asked to choose a sketch folder
name: this is where your Arduino sketch will be stored. Name it Blinking_LED and click OK.
Then type the following text (Program 1) into the Arduino Sketch editor (The main window of
the Arduino IDE).

// the setup function runs once when you press reset or power the board
void setup() {
// initialize digital pin 13 as an output.
pinMode(13, OUTPUT);
}
// the loop function runs over and over again forever
void loop() {
digitalWrite(13, HIGH); // turn the LED on (HIGH is the voltage level)
delay(1000); // wait for a second
digitalWrite(13, LOW); // turn the LED off by making the voltage LOW
delay(1000); // wait for a second
}
Please do not copy paste the code until you become familiar with different instructions, as you
may find there are Capital letter in between an instruction for example digitalWrite ; in this
instruction W is the capital letter, type the instructions in the Arduino IDE code editor and check
whether you are typing the instructions correctly.
Now type the code is in your IDE, you need to verify it. Press the Verify button; if everything is
correct, you will see the message ―Done compiling appear at the bottom of the Arduino IDE in
the black area. This message means that Arduino IDE has translated your sketch into an
executable program that can be run by the board, a bit like an .exe file in Windows or an .app file
on a Mac.
At this point, you can upload it into the board: press the Upload to I/O Board button. This will
reset the board, forcing it to stop what it‘s doing and listen for instructions coming from the USB
port. The Arduino IDE sends the current sketch to the board, which will store it in its memory
and eventually run it.
You will see a few messages appear in the black area at the bottom of the window, and just
above that area, you will see the message “Done uploading” appear to let you know the process
has completed correctly. The inbuilt LED, on the board; will flash every time a byte is sent or
received by the board. During the upload process, it keep flickering.
If you don‘t see the LEDs flicker, or if you get an error message instead of “Done uploading”,
then there is a communication problem between your computer and Arduino. Make sure you
have selected the right serial port in the Tools>Serial Port menu. Also check the Tools>Board
menu to confirm that Arduino Uno or the particular board you are using for this project is
selected in the development board.
Once the code is uploaded to your Arduino Board, it will stay there until you put another sketch
on it. The sketch will survive if the board is reset or turned off, a bit like the data on your
computer‘s hard drive.
Assuming that the sketch has been uploaded correctly, you will see the LED turn On for a second
and then turn Off for a second.
What you have just written and run is a “computer program”, or a sketch, as Arduino programs
are called. Arduino board, as I have mentioned before, is a small computer, and it can be
programmed to do what you want. This is done using a programming language to type a series of
instructions in the Arduino IDE, which turns it into an executable for your Arduino board.
I will next show you to understand the sketch. First of all, the Arduino executes the code from
top to bottom, so the first line at the top is the first one read; then it moves down, a bit like how
the play head of a video player like QuickTime Player or Windows Media Player moves from
left to right showing where in the move you are.
Arduino IDE expects two functions to exist- one called setup() and one called loop(). setup() is
where you put all the code that you want to execute once at the beginning of your program and
loop() contains the core of your program, which is executed over and over again. This is done
because Arduino is not like your regular computer- it cannot run multiple programs at the same
time and programs can‘t quit. When you power up the board, the code runs; when you want to
stop, you just turn it off.
Any text beginning with // is ignored by Arduino. These lines are comments, which are notes that
you leave in the program for yourself, so that you can remember what you did when you wrote it,
or somebody else, so that they can understand your code.
// the setup function runs once when you press reset or power the board
It is very common to write a piece of code, upload it onto the board, and say ―Okay-I‘m never
going to have to touch this again! Only to realize six months later that you need to update the
code or fix a bug. At this point, you open up the program, and if you haven‘t included any
comments in the original program, you will think, ―What a mess! Where do I start? As we
move along, you will see some tricks for how to make your programs more readable and easier
to maintain.
Basic Programming in Arduino IDE
Programming in Arduino is very simple and easy to understand. Basically it is derived from C
language which is the most commonly used software language globally. Also because it is easy
to understand you can right away start with few basic programs without going into much details.
Also you can go for small projects and can interface various components like motors, sensors,
actuators very easily to Arduino .
Basic Structure of Program
The basic structure of the Arduino programming language is fairly simple and runs in at least
two parts. These two required parts, or functions, enclose blocks of statements.
void setup()
{
statements;
}
void loop()
{
statements;
}
Where setup() is the preparation, loop() is the execution. Both functions are required for the
program to work. The setup function should follow the declaration of any variables at the very
beginning of the program. It is the first function to run in the program, it runs only once, and is
used to set pinMode or initialize serial communication. pinMode is a command used in Arduino
programming to declare whether the I/O pin will be as an Input or as Output. There are 13
Digital I/O pins on your Arduino board so out of these you can use any of the 13 pins as an Input
or an Output but you have to first declare how you intend to use it. Means it will be used as an
Output pin when you need to give some current to an output device like an LED or Buzzer, and
will be used as a Input pin when you need to read the value from an input device such as a IR
Sensor or a Push Button(whether its pressed or not) or LDR.
Syntax for declaring 13 pin as Input and 12 pin as Output (you can use any pin):
pinMode(13,INPUT); // pin 13 of Arduino is declared as an Input pin pinMode(12,OUTPUT); //
pin 12 of Arduino is declared as an Output pin The loop function follows next and includes the
code to be executed continuously reading inputs, triggering outputs, etc. This function is the core
of all Arduino programs and does the bulk of the work.
setup()
The setup() function is called once when your program starts. Use it to initialize pin modes, or
begin serial. It must be included in a program even if there are no statements to run.
void setup()
{
pinMode(pin, OUTPUT); // sets the 'pin' as output
}
loop()
After calling the setup() function, the loop() function does precisely what its name suggests, and
loops consecutively, allowing the program to change, respond, and control the Arduino board.
The statements written inside the loop runs over and over again, following the order from top to
bottom and again starting from top.
void loop()
{
digitalWrite(pin, HIGH); // turns 'pin' on
delay(1000); // pauses for one second
digitalWrite(pin, LOW); // turns 'pin' off
delay(1000); // pauses for one second
}
For reading or writing on any digital pin of Arduino board digitalRead and digitalWrite are used
respectively.
pinMode(pin, mode)
Used in void setup() to configure a specified pin to behave either as an INPUT or an OUTPUT.
pinMode(pin, OUTPUT); // sets ‗pin‘ to output
pinMode(pin, INPUT); // set ‗pin‘ to input
Pins configured as OUTPUT can provide 40 mA (milliamps) of current to other devices/circuits.
This is enough current to brightly light up an LED (don't forget the series resistor), but not
enough current to run most relays, solenoids, or motors.
Short circuits on Arduino pins and excessive current can damage or destroy the output pin, or
damage the entire chip. It is often a good idea to connect an OUTPUT pin to an external device
in series with a 470Ω or 1KΩ resistor.
digitalRead(pin)
Reads the value from a specified digital pin with the result either HIGH or LOW. The pin can be
specified as either a variable or constant
value = digitalRead(Pin); // sets 'value' equal to the input pin
digitalWrite(pin, value)
Outputs either logic level HIGH or LOW at (turns on or off) a specified digital pin. The pin can
be specified as either a variable or constant.
digitalWrite(pin, HIGH); // sets 'pin' to high
HIGH/LOW
These constants define pin levels as HIGH or LOW and are used when reading or writing to
digital pins. HIGH is defined as logic level 1, ON, or 3.3 volts while LOW is logic level 0, OFF,
or 0 volts.
digitalWrite(13, HIGH);
digitalWrite(8, LOW);
input/output
Constants used with the pinMode() function to define the mode of a digital pin as either INPUT
or OUTPUT.
pinMode(13, OUTPUT);
pinMode(8, INPUT);
PWM
Pulse Width Modulation, or PWM, is a technique for getting analog results with digital means.
Digital control is used to create a square wave, a signal switched between on and off. This on-off
pattern can simulate voltages in between full on (3.3 Volts) and off (0 Volts) by changing the
portion of the time the signal spends on versus the time that the signal spends off. The duration
of "on time" is called the pulse width. To get varying analog values, you change, or modulate,
that pulse width. If you repeat this on-off pattern fast enough with an LED for example, the
result is as if the signal is a steady voltage between 0 and 3.3v controlling the brightness of the
LED.
analogWrite(pin, value)
Writes an analog value (PWM wave) to a pin. Can be used to light an LED at varying
brightnesses or drive a motor at various speeds. After a call to analogWrite(), the pin will
generate a steady square wave of the specified duty cycle until the next call to analogWrite() (or
a call to digitalRead() or digitalWrite() on the same pin). The frequency of the PWM signal is
approximately 490 Hz.
analogWrite(pin, value); // writes 'value' to analog 'pin'

A value of 0 generates a steady 0 volts output at the specified pin; a value of 255 generates a
steady 3.3 volts output at the specified pin. For values in between 0 and 255, the pin rapidly
alternates between 0 and 3.3 volts - the higher the value, the more often the pin is HIGH (3.3
volts). For example, a value of 64 will be 0 volts three-quarters of the time, and 3.3 volts one
quarter of the time; a value of 128 will be at 0 half the time and 255 half the time; and a value of
192 will be 0 volts one quarter of the time and 3.3 volts three-quarters of the time.
Note: Analog pins unlike digital ones, do not need to be first declared as INPUT nor OUTPUT.
analogRead(pin)
Reads the value from the specified analog pin with a 10-bit resolution. The Arduino board
contains a 1 channel 10-bit analog to digital converter. This means that it will map input voltages
between 0 and 3.3 volts into integer values between 0 and 1023. This yields a resolution between
readings of: 3.3 volts / 1024 units.
It takes about 100 microseconds (0.0001 s) to read an analog input, so the maximum reading rate
is about 10,000 times a second.
value = analogRead(pin); // sets 'value' equal to 'pin'
Difference between and analog signal and digital signals is that digital signal only works with 2
values that is High (5v) and Low (0v) whereas analog signal has a range of values.
Range of analog input values is from 0-1023 and analog output values is 0-255. So when we use
an analog input then the values we get are in the range of 0- 1023 and we can convert it into the
range of 0-255 by just dividing it by 4. Whereas when we write on analog output pin it has a
range of 0-255 through which we can write the values.
Functions
A function is a block of code that has a name and a block of statements that are executed when
the function is called. The functions void setup() and void loop() have already been discussed
and other built-in functions will be discussed later. Custom functions can be written to perform
repetitive tasks and reduce clutter in a program. Functions are declared by first declaring the
function type. This is the type of value to be returned by the function such as 'int' for an integer
type function. If no value is to be returned the function type would be void. After type, declare
the name given to the function and in parenthesis any parameters being passed to the function.
type functionName(parameters)
{
statements;
}
The following integer type function delayVal() is used to set a delay value in a program by
reading the value of a potentiometer. It first declares a local variable v, sets v to the value of the
potentiometer which gives a number between 0- 1023, then divides that value by 4 for a final
value between 0-255, and finally returns that value back to the main program.
int delayVal()
{
int v; // create temporary variable 'v'
v = analogRead(pot); // read potentiometer value
v /= 4; // converts 0-1023 to 0-255
return v; // return final value
}
{} curly braces
Curly braces (also referred to as just "braces" or "curly brackets") define the beginning and end
of function blocks and statement blocks such as the void loop() function and the for and if
statements.
type function()
{
statements;
}
An opening curly brace {must always be followed by a closing curly brace}. This is often
referred to as the braces being balanced. Unbalanced braces can often lead to cryptic,
impenetrable compiler errors that can sometimes be hard to track down in a large program. The
Arduino environment includes a convenient feature to check the balance of curly braces. Just
select a brace, or even click the insertion point immediately following a brace, and its logical
companion will be highlighted.
; Semicolon
A semicolon must be used to end a statement and separate elements of the program. A semicolon
is also used to separate elements in a( for loop ).
int x = 13; // declares variable 'x' as the integer 13
Note: Forgetting to end a line in a semicolon will result in a compiler error. The error text may
be obvious, and refer to a missing semicolon, or it may not. If an impenetrable or seemingly
illogical compiler error comes up, one of the first things to check is a missing semicolon, near
the line where the compiler complained.
/*… */ block comments
Block comments, or multi-line comments, are areas of text ignored by the program and are used
for large text descriptions of code or comments that help others understand parts of the program.
They begin with /* and end with */ and can span multiple lines.
/* this is an enclosed block comment don‘t forget the closing comment –
They have to be balanced! */
Because comments are ignored by the program and take no memory space they should be used
generously and can also be used to “comment out” blocks of code for debugging purposes.
// line comments
Single line comments begin with // and end with the next line of code. Like block comments,
they are ignored by the program and take no memory space.
// this is a single line comment
Single line comments are often used after a valid statement to provide more information about
what the statement accomplishes or to provide a future reminder.
Variables
A variable is a way of naming and storing a numerical value for later use by the program. As
their name suggests, variables are numbers that can be continually changed as opposed to
constants whose value never changes. A variable needs to be declared and optionally assigned to
the value needing to be stored.
int inputVariable = 0; // declares a variable and assigns value of 0
inputVariable = analogRead(0); // set variable to value of analog pin 0
“inputVariable” is the variable itself. The first line declares that it will contain an int, short for
integer. The second line sets the variable to the value at analog pin 0. This makes the value of pin
0 accessible elsewhere in the code. Once a variable has been assigned, or re-assigned, you can
test its value to see if it meets certain conditions, or you can use its value directly.
Note: Variables should be given descriptive names, to make the code more readable. Variable
names like tiltSensor or pushButton help the programmer and anyone else reading the code to
understand what the variable represents. Variable names like var or value, on the other hand, do
little to make the code readable and are only used here as examples. A variable can be named any
word that is not already one of the keywords in the Arduino language.
Variable declaration
All variables have to be declared before they can be used. Declaring a variable means defining its
value type, as in int, long, float, etc., setting a specified name, and optionally assigning an initial
value. This only needs to be done once in a program but the value can be changed at any time
using arithmetic and various assignments.
The following example declares that inputVariable is an int, or integer type, and that its initial
value equals zero. This is called a simple assignment.
int inputVariable = 0;
A variable can be declared in a number of locations throughout the program and where this
definition takes place determines what parts of the program can use the variable.
Variable scope
A variable can be declared at the beginning of the program before void setup(), locally inside of
functions, and sometimes within a statement block such as for loops. Where the variable is
declared determines the variable scope, or the ability of certain parts of a program to make use of
the variable. A global variable is one that can be seen and used by every function and statement
in a program. This variable is declared at the beginning of the program, before the setup()
function. A local variable is one that is defined inside a function or as part of a (for loop). It is
only visible and can only be used inside the function in which it was declared. It is therefore
possible to have two or more variables of the same name in different parts of the same program
that contain different values. Ensuring that only one function has access to its variables
simplifies the program and reduces the potential for programming errors.
The following example shows how to declare a few different types of variables and demonstrates
each variable‘s visibility:
int value; // 'value' is visible to any function
void setup()
{
// no setup needed
}
void loop()
{
for (int i=0; i<20;) // 'i' is only visible
{ // inside the for-loop
i++;
}
float f; // 'f' is only visible inside loop
}
byte
Byte stores an 8-bit numerical value without decimal points. They have a range of 0-255.
byte someVariable = 180; // declares 'someVariable' as a byte type
int
Integers are the primary datatype for storage of numbers without decimal points and store a 16-
bit value with a range of 32,767 to -32,768.
int someVariable = 1500; // declares 'someVariable' as an integer type
long
Extended size datatype for long integers, without decimal points, stored in a 32- bit value with a
range of 2,147,483,647 to -2,147,483,648.
long someVariable = 90000; // declares 'someVariable' as a long type
float
A datatype for floating-point numbers, or numbers that have a decimal point. Floating-point
numbers have greater resolution than integers and are stored as a 32-bit value with a range of
3.4028235E+38 to -3.4028235E+38.
float someVariable = 3.14; // declares 'someVariable' as a floating-point type
Arithmetic
Arithmetic operators include addition, subtraction, multiplication, and division. They return the
sum, difference, product, or quotient (respectively) of two operands.
y = y + 3;
x = x - 7;
j = j * 6;
r = r / 5;
The operation is conducted using the data type of the operands, so, for example, 9 / 4 results in 2
instead of 2.25 since 9 and 4 are ints and are incapable of using decimal points. This also means
that the operation can overflow if the result is larger than what can be stored in the data type.
If the operands are of different types, the larger type is used for the calculation. For example, if
one of the numbers (operands) are of the type float and the other of type integer, floating point
math will be used for the calculation. Choose variable sizes that are large enough to hold the
largest results from your calculations. Know at what point your variable will rollover and also
what happens in the other direction e.g. (0 - 1) OR (0 - - 32768). For math that requires fractions,
use float variables, but be aware of their drawbacks: large size and slow computation speeds.
Comparison operators
Comparisons of one variable or constant against another are often used in if statements to test if a
specified condition is true. Different types of condition used are:
x == y // x is equal to y
x != y // x is not equal to y
x < y // x is less than y
x > y // x is greater than y
x <= y // x is less than or equal to y
x >= y // x is greater than or equal to y
Logical operators
Logical operators are usually a way to compare two expressions and return a TRUE or FALSE
depending on the operator. There are three logical operators, AND, OR, and NOT, that are often
used in if statements:
Logical AND:
if (x > 0 && x < 5) // true only if both expressions are true
Logical OR:
if (x > 0 || y > 0) // true if either expression is true
Logical NOT:
if (!x > 0) // true only if expression is false
Constants
The Arduino language has a few predefined values, which are called constants. They are used to
make the programs easier to read. Constants are classified in groups.
True/False These are Boolean constants that define logic levels. FALSE is easily defined as 0
(zero) while TRUE is often defined as 1, but can also be anything else except zero. So in a
Boolean sense, -1, 2, and -200 are all also defined as TRUE.
if (b == TRUE);
{ doSomething; }
If
if statements test whether a certain condition has been reached, such as an analog value being
above a certain number, and executes any statements inside the brackets if the statement is true.
If false the program skips over the statement. The format for an if test is:

if (someVariable == value)
{
doSomething;
}
The above example compares someVariable to another value, which can be either a variable or
constant. If the comparison, or condition in parentheses is true, the statements inside the brackets
are run. If not, the program skips over them and continues on after the brackets. Note: Beware of
accidentally using ‗=‘, as in if(x=10), while technically valid, defines the variable x to the value
of 10 and is as a result always true. Instead use “==”, as in if(x==10), which only tests whether x
happens to equal the value 10 or not. Think of “=” as “equals” opposed to “= =” being “is equal
to”.
if… else
if… else allows for ‗either-or‘ decisions to be made. For example, if you wanted to test a digital
input, and do one thing if the input went HIGH or instead do another thing if the input was
LOW, you would write that this way:
if (inputPin == HIGH)
{ doThingA;
} else
{ doThingB;
}
else can also precede another if test, so that multiple, mutually exclusive tests can be run at the
same time. It is even possible to have an unlimited number of these else branches. Remember
though, only one set of statements will be run depending on the condition tests:

if (inputPin < 500)


{
doThingA;
}
else if (inputPin >= 1000)
{
doThingB;
}
else
{
doThingC;
}
Note: An if statement simply tests whether the condition inside the parenthesis is true or false.
for
The for statement is used to repeat a block of statements enclosed in curly braces a specified
number of times. An increment counter is often used to increment and terminate the loop. There
are three parts, separated by semicolons (;), to the for loop header:
for (initialization; condition; expression)
{
doSomething;
}
The initialization of a local variable, or increment counter, happens first and only once. Each
time through the loop, the following condition is tested. If the condition remains true, the
following statements and expression are executed and the condition is tested again. When the
condition becomes false, the loop ends.
The following example starts the integer i at 0, tests to see if i is still less than 20 and if true,
increments i by 1 and executes the enclosed statements:

for (int i=0; i<20; i++) // declares i, tests if less // than 20, increments i by 1
{
digitalWrite(13, HIGH); // turns pin 13 on
delay(250); // pauses for 1/4 second
digitalWrite(13, LOW); // turns pin 13 off
delay(250); // pauses for 1/4 second
}
while
While loops will loop continuously, and infinitely, until the expression inside the parenthesis
becomes false. Something must change the tested variable, or the while loop will never exit. This
could be in your code, such as an incremented variable, or an external condition, such as testing a
sensor.
While (someVariable ?? value)
{
doSomething;
}
The following example tests whether “someVariable” is less than 200 and if true executes the
statements inside the brackets and will continue looping until “someVariable” is no longer less
than 200.
while (someVariable < 200) // tests if less than 200
{
doSomething; // executes enclosed statements s
omeVariable++; // increments variable by 1
}
do… while The do loop is a bottom driven loop that works in the same manner as the while loop,
with the exception that the condition is tested at the end of the loop, so the do loop will always
run at least once.
do
{
doSomething;
}
while (someVariable ?? value);
The following example assigns readSensors() to the variable ‘x‘, pauses for 50 milliseconds, then
loops indefinitely until ‘x‘ is no longer less than 100:
do
{
x = readSensors(); // assigns the value of readSensors() to x
delay (50); // pauses 50 milliseconds
}
while (x < 100); // loops if x is less than 100
delay(ms)
Pauses a program for the amount of time as specified in milliseconds, where 1000 equals 1
second.
delay(1000); // waits for one second
millis()
Returns the number of milliseconds since the Arduino board began running the current program
as an unsigned long value.
value = millis(); // sets ‘value‘ equal to millis()
min(x, y)
Calculates the minimum of two numbers of any data type and returns the smaller number.
value = min(value, 100); // sets 'value' to the smaller of . 'value' or 100, ensuring that it never gets
above 100.
max(x, y) Calculates the maximum of two numbers of any data type and returns the larger
number.
value = max(value, 100); // sets 'value' to the larger of 'value' or 100, ensuring that it is at least
100.
Serial.begin(rate) Opens serial port and sets the baud rate for serial data transmission. The
typical baud rate for communicating with the computer is 9600 although other speeds are
supported.
void setup()
{
Serial.begin(9600); // opens serial port sets data rate to 9600 bps
}
Serial.println(data) Prints data to the serial port, followed by an automatic carriage return and
line feed. This command takes the same form as Serial.print(), but is easier for reading data on
the Serial Monitor.
Serial.println(analogValue); // sends the value of 'analogValue'
Note: For more information on the various permutations of the Serial.println() and Serial.print()
functions please refer to the Arduino website.
The following simple example takes a reading from analog pin0 and sends this data to the
computer every 1 second.
void setup()
{
Serial.begin(9600); // sets serial to 9600bps
}
void loop()
{
Serial.println(analogRead(0)); // sends analog value
delay(1000); // pauses for 1 second
}
Programming Multiple LEDs

Connect LEDs to digital pin 11,12, and 13, don’t forget to connect a resistor to the LED cathode
and ground.
Arduino Program for Blinking 3 LEDs
void setup() {
pinMode(11, OUTPUT);
pinMode(12,OUTPUT);
pinMode(13,OUTPUT);
}
void loop() {
digitalWrite(11,HIGH);
digitalWrite(12,HIGH);
digitalWrite(13,HIGH);
delay(1000);
digitalWrite(11,LOW);
digitalWrite(12, LOW);
digitalWrite(13,LOW);
delay(1000);
}
Arduino program for blinking One after another.
void setup() {
pinMode(11, OUTPUT);
pinMode(12,OUTPUT);
pinMode(13,OUTPUT);
}
void loop() {
digitalWrite(11,HIGH);
digitalWrite(12,LOW);
digitalWrite(13,LOW);
delay(1000);
digitalWrite(11,LOW);
digitalWrite(12, HIGH);
digitalWrite(13,LOW);
delay(1000);
digitalWrite(11,LOW);
digitalWrite(12,LOW);
digitalWrite(13,HIGH);
delay(1000);
}

Find the difference between these two programs and upload the sketch to your Arduino board
and check what’s happening to your LEDs connected to your board. This is a very simple
program to do and allow you to be familiarise on Arduino sketch.
Task: Write a program for Blinking 5 LEDs and connect 5 LEDs to your hardware and upload
the sketch and check the working.
Programming for a Push button and a LED

Arduino IDE program for turn on and off a LED using a pushbutton
const int pinButton = 5; // digital pin 5 is named as PinButton
const int pinLed = 13; //digital pin 13 is named as pinLed
void setup()
{
// Configure the button's pin for input signals.
pinMode(pinButton, INPUT);

// Configure the LED's pin for output.


pinMode(pinLed, OUTPUT);
}

void loop()
{
if(digitalRead(pinButton))
{
// When the button is pressed, turn the LED on.
digitalWrite(pinLed, HIGH);
}
else
{
// Otherwise, turn the LED off.
digitalWrite(pinLed, LOW);
}
delay(10);
}
Note: change the logic of the program to the condition, when you press a button led should turn
off and when you release the button led should go on.
Using a Potentiometer (analog sensor)

Arduino Program for Reading a Potentiometer value.

// Define the pin to which the angle sensor is connected.


const int potentiometer = A0;

void setup()
{
// Configure the serial communication line at 9600 baud (bits per second.)
Serial.begin(9600);

// Configure the angle sensor's pin for input.


pinMode(potentiometer, INPUT);
}
void loop()
{
// Read the value of the sensor and print it to the serial console.
int value = analogRead(potentiometer);
Serial.println(value);

// Wait 0.1 seconds between readings.


delay(100);
}
Open the serial monitor and change the knob of the potentiometer and observer the potentiometer
reading on your serial monitor.
PWM using Potentiometer and LED

Arduino IDE program for controlling a brightness of an LED using Potentiometer


There are a variety of purposes for PWM. Some are output data encoders. One commonly seen
purpose is to control the brightness of an LED. If we apply maximum voltage to an LED, it is
maximally bright. If we apply 1/2 the voltage, it is about 1/2 the brightness. By applying a fast
period PWM signal to the input of an LED, the duty cycle becomes the brightness of the LED.
The way this works is that either full voltage or no voltage is applied to the LED but because the
period is so short, the "average" voltage over time follows the duty cycle and even though the
LED is flickering on or off, it is so fast that our eyes can't detect it and all we see is the apparent
brightness change.
// These constants won't change. They're used to give names
// to the pins used:
const int analogInPin = A0; // Analog input pin that the potentiometer is attached to
const int analogOutPin = 5; // Analog output pin that the LED is attached to

int sensorValue = 0; // value read from the pot


int outputValue = 0; // value output to the PWM (analog out)
void setup() {
// initialize serial communications at 9600 bps:
Serial.begin(9600);
}

void loop() {
// read the analog in value:
sensorValue = analogRead(analogInPin);
// map it to the range of the analog out:
outputValue = map(sensorValue, 0, 1023, 0, 255);
// change the analog out value:
analogWrite(analogOutPin, outputValue);

// print the results to the serial monitor:


Serial.print("sensor = ");
Serial.print(sensorValue);
Serial.print("\t output = ");
Serial.println(outputValue);
// wait 2 milliseconds before the next loop
// for the analog-to-digital converter to settle
// after the last reading:
delay(2);
The idea behind pulse width modulation is that we can think of regular pulses of output signals
encoding information as a function of how long the signal is kept high. Let us imagine that we
have a period of 1HZ (one thing per second). Now let us assume that we raise the output voltage
to a level of 1 for 1/2 of a second at the start of the period. This would give us a square wave
which starts high, lasts for 500 milliseconds and then drops low for the next 500 milliseconds.
This repeats on into the future. The duration that the pulse is high relative to the period allows us
to encode an analog value onto digital signals. If the pulse is 100% high for the period then the
encoded value would be 1.0. If the pulse is 100% low for the period, then the encoded value
would be 0.0. If the pulse is on for "n" milliseconds (where n is less than 1000), then the encoded
value would be n/1000. Typically, the length of a period is not a second but much, much smaller
allowing us to output many differing values very quickly. The ratio of the on signal to the period
is called the "duty cycle". This encoding technique is called "Pulse Width Modulation" or
"PWM".
For the Arduino, the period of the PWM can range from 1 millisecond to 10 milliseconds. This is
a frequency of 1KHz to 100Hz. The resolution of the duty cycle is down to 45 nanoseconds
which is 14 bits of resolution data. The device provides support for up to 8 PWM channels where
each channel can be associated with its own pin and duty cycle. The period is the same for all
PWM channels.
Servo Motor with Arduino

A servomotor is a rotary actuator or linear actuator that allows for precise control of angular or
linear position, velocity and acceleration. It consists of a suitable motor coupled to a sensor for
position feedback.
Connect the servo motor as shown in the figure, provide an external power supply for servo
motor it is not safety to use a servo motor without any external power as it may draw more
current from the Arduino and cause damage to the board.
Connect the output of the servo motor to the 2nd pin of Arduino Uno, note the fritzing circuit
carefully I have connected a common ground to the Servo and Arduino, it is essential to connect
a common ground between these device even though the servo motor uses external power, if you
don’t connect common ground then your servo motor will not respond.

Servo Motor sweep code for Arduino


#include <Servo.h>

Servo myservo; // create servo object to control a servo


// twelve servo objects can be created on most boards

void setup()
{
myservo.attach(2); // attaches the servo on the second pin of arduino
}

void loop()
{
int pos;

for(pos = 0; pos <= 180; pos += 1) // goes from 0 degrees to 180 degrees
{ // in steps of 1 degree
myservo.write(pos); // tell servo to go to position in variable 'pos'
delay(15); // waits 15ms for the servo to reach the position
}
for(pos = 180; pos>=0; pos-=1) // goes from 180 degrees to 0 degrees
{
myservo.write(pos); // tell servo to go to position in variable 'pos'
delay(15); // waits 15ms for the servo to reach the position
}
}
Starting With 37 Sensors
Joystick

The JoyStick is an analog sensor that can be used to control your arduino.Analog JoySticks are basically
potentiometers, so they return values which can be made visible using the provided code in this step. By clicking
the serial monitor you will see the values. Once you move the JoyStick the values will change.

Connect Gnd of Joystick to Gnd of Arduino


Connect +5v of Joystick to 5v of Arduino
Connect VRx of Joystick to A0 pin of Arduino
Connect VRy of Joystick to A1 pin of Arduino
Connect the Arduino to your Computer and upload the following program and check the result in
your serial monitor.

int joyPin1 = A1; // First analog input for Jostick


int joyPin2 = A2; // Second analog input for Jostick
int Xvalue = 0; // variable to read the value from the analog pin 0
int Yvalue = 0; // variable to read the value from the analog pin 1

void setup() {
pinMode(joyPin1, INPUT);
pinMode(joyPin2, INPUT);
Serial.begin(9600);
}

void loop() {
Xvalue = analogRead(joyPin1);
delay(100);
Yvalue = analogRead(joyPin2);
delay(100);

Open the magnifying glass like icon on the right side of Arduino IDE, This will open the serial
monitor, move the joystick to know all the analog value return by the joystick.

In the last programming we have left out the switch button on the Joystick for this program
connect the switch button to the 3rd pin of the Arduino and upload the program.
int JoyStick_X = A0; // x
int JoyStick_Y = A1; // y
int JoyStick_Z = 3; // key
void setup ()
{
pinMode (JoyStick_X, INPUT);
pinMode (JoyStick_Y, INPUT);
pinMode (JoyStick_Z, INPUT_PULLUP);
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);
}
Open the serial monitor and check the values in the monitor and press the joystick to know
whether the key is pressed or not in the serial monitor.

Connect LED’s the way it shown in the below diagram and turn on and turn off Led’s based on
Joystick movement.

Use 220 ohms


resistor in order to protect the LED’s from high current flowing from Arduino.
int UD = 0;
int LR = 0;
/* Arduino Micro output pins*/
int LED1 = 13; // connect led to 13th pin
int LED2 = 12; // connect led to 12th pin
int LED3 = 11; // connect led to 11th pin
int LED4 = 10; // connect led to 10th pin
/* Arduino Micro Input Pins */
int Vrx=A0; // connect vrx of joystick to A0
int Vry=A1; // connect vry of joystick to A1

int MID = 10; //


int LRMID = 0;
int UPMID = 0;
void setup(){

//making the LEDs as OUTPUT

pinMode(LED1, OUTPUT);
pinMode(LED2, OUTPUT);
pinMode(LED3, OUTPUT);
pinMode(LED4, OUTPUT);

//calibrate the sensor in center position


LRMID = analogRead(Vry);
UPMID = analogRead(Vrx);
}

void loop(){

UD = analogRead(Vrx); // reading A0 pin value and storing in UD variable


LR = analogRead(Vry); // reading A1 pin value and storing in LR variable
// UP-DOWN
if(UD < UPMID - MID){ // checking the value with if condition
digitalWrite(LED1, LOW);
}else{
digitalWrite(LED1, HIGH); // if the joystick is down led1 will turn on
// else it will turn off
}

if(UD > UPMID + MID){


digitalWrite(LED2, LOW);// if the joystick is up led2 will turn on
}else{
digitalWrite(LED2, HIGH);
}
// LEFT-RIGHT
if(LR < LRMID - MID){
digitalWrite(LED3, LOW); // if the joystick is left Led3 will turn on
}else{
digitalWrite(LED3, HIGH);
}

if(LR > LRMID + MID){


digitalWrite(LED4, LOW); // if the joystick is right led4 will turn on
}else{
digitalWrite(LED4, HIGH);
}

delay(400);
// based on condition each led will turn on and off

}
Flame Sensor

This sensor is able to detect a flame by sensing light wavelength between 760 –
1100 nanometers. The test distance depends on the flame size and sensitivity settings – during
my tests a reliable maximum was around 1 meter. The detection angle is 60 degrees, so the flame
does not have to be right in front of the sensor.
The sensitivity is adjustable with the blue digital potentiometer – if it is too high, then you will
get false positives because of ordinary light. The working voltage is compatible with Arduino
(3.3 – 5 V), so the connection is straightforward using just three wires.
There are two sensor outputs:
Digital – sending either zero for nothing detected or one for a positive detection
Analog – sending values in a range representing the flame probability/size/distance; must be
connected to a PWM capable input
These sensors are used for short range fire detection. They can be used for safety or to monitor
projects.
Usage:
These types of sensors are used for short range fire detection and can be used to monitor projects
or as a safety precaution to cut devices off / on.
Range:
It has found this unit is mostly accurate up to about 3 feet.
How it works:
The flame sensor is very sensitive to IR wavelength at 760 nm ~ 1100 nm light.
Analog output (A0): Real-time output voltage signal on the thermal resistance.
Digital output (D0): When the temperature reaches a certain threshold, the output high and low
signal threshold adjustable via potentiometer.
Pins:
VCC...... Positive voltage input: 5v for analog 3.3v for Digital.
A0.......... Analog output
D0......... Digital output
GND..... Ground

Connect the Vcc pin of the sensor to 5v pin of Arduino


Connect the Gnd pin of the sensor to Gnd pin of Arduino
Connect the A0 pin of the sensor to the A0 pin of Arduino

Upload the following code and check the value in the serial monitor, use flame to know the
range, make sure you are under right guidance to do this task, if you are not sure about testing
with fire, please don’t proceed with this task.

int Led = 13 ;// define LED Interface


int analoog = A0; // define the flame sensor interface
float sensor; //read analoog value

void setup ()
{
pinMode (Led, OUTPUT) ;// define LED as output interface
pinMode (analoog, INPUT) ;// output interface defines the flame sensor
Serial.begin(9600);
}

void loop ()
{
sensor = analogRead(analoog);
Serial.println(sensor); // display tempature

if (sensor > 500) // When the flame sensor detects a signal, LED flashes
{
digitalWrite (Led, HIGH);
}
else
{
digitalWrite (Led, LOW);
}
delay(1000);
}

Fire Detection alarm using Flame sensor and buzzer with Arduino
Connect the flame sensor as follows
Gnd of the flame sensor pin to the Gnd pin of Arduino
Vcc of the flame sensor pin to the 5v pin of Arduino
D0 pin of the flame sensor to the 2nd pin of Arduino

Connect the buzzer as follows


Red color wire or the long pin of the buzzer to the 13th pin of Arduino
Black color wire or the short pin of the buzzer to the Gnd pin of the Arduino.

int buzzer = 13 ;// define LED Interface


int buttonpin = 2; // define the flame sensor interface

int val ;// define numeric variables val


float sensor; //read analoog value

void setup ()
{
pinMode (buzzer, OUTPUT) ;// define LED as output interface
pinMode (buttonpin, INPUT) ;// output interface defines the flame sensor
}

void loop ()
{

val = digitalRead (buttonpin) ;// digital interface will be assigned a value of 2 to read val
if (val == HIGH) // When the flame sensor detects a signal, buzzer flashes
{
digitalWrite (buzzer, HIGH);
}
else
{
digitalWrite (buzzer, LOW);
}
delay(1000);
}
RGB LED

A full color LED


module is a circuit in which an LED can be lit to any color. This is why it is called a full color
LED module. By programming the module with a microcontroller, we can program the LED to
turn to any color that we want.
How the module works is it has 3 PWM (pulse width modulation) pins which stand for the color
red, green, and blue (RGB). The idea is that any color can be created with a combination of red,
green, and blue.
By blending red, green, and blue, we can showcase all color (full color) with the LED on the
module board.
The RGB full color module is actually a very useful circuit. Using a single LED, we can lit up
any color that we want. We can show orange, green, red, anything. It's really good if you want a
wide variety of color and you only want to use a single LED.
In this circuit, we will build a circuit in which all the possible color are showcased. We will show
a blend of all the color’swhich the LED can show in rapid succession with a for loop.
Connect the LED as follows
Red pin to the 11th pin of Arduino
Blue pin to the 10th pin of Arduino
Green pin to the 9th pin of Arduino
The reason for choosing above pin number is those pins are capable of doing PWM.
int RedPin = 11; //the Red pin connects to digital pin 11 on the arduino
int BluePin = 10; //the Blue pin connects to digital pin 10 on the arduino
int GreenPin = 9 ;//the Green pin connects to digital pin 11 on the arduino
int value; //this will hold the value of a for loop we will create

void setup() { pinMode(RedPin, OUTPUT);


pinMode(BluePin, OUTPUT);
pinMode(GreenPin, OUTPUT);
Serial.begin (9600);
}
void loop()
{
for (value = 255; value>0; value--){//counts down
analogWrite(11, value); //val will be 255 initially
analogWrite(10, 255-value); //val will be initially 0 initially
analogWrite(9, 128-value);//val will be initially 127
delay(1);
}
for (value = 0; value <255; value++)//counts up
{ analogWrite(11, value);//val will be 0 initially
analogWrite(10, 255-value);//val will be 255 initially
analogWrite(9, 128-value);//val will be 255 initially
delay (1);
}
Serial.println(value, DEC);
}
This code will show the full spectrum of colors.
The first block of code shows the pin connections to the arduino board and creates an integer
named value.
The second block of code, the setup() function, makes all the digital pins (R, G, and B) output
pins. Serial.begin(9600) allows us to open up a Serial Monitor so that we can see the value that
the for loop is currently running.
The next block of code, the loop() function is run repeatedly over and over again. It contains 2
for loops. The first for loop counts down from 255. The second for loop counts up from 0.
Between each new value is a 1ms delay. If you want you can change this delay to faster or
slower to suit your preferences. If you want to see it go slower, then you increase the delay. If
you want to see it go even faster, which you probably wouldn't want since it's going fast already,
you can use DelayMicroseconds() function to make it faster.
This circuit creates really cool lighting effects.
But probably the best use for it is that it can show any color once you know the correct values.
RGB SMD LED

Upload the same program for this SMD type LED and everything works same as the previous
project.
Heartbeat sensor

This project uses bright infrared (IR) LED and a phototransistor to detect the pulse of the finger,
a red LED flashes with each pulse. Pulse monitor works as follows: The LED is the light side of
the finger, and phototransistor on the other side of the finger, phototransistor used to obtain the
flux emitted, when the blood pressure pulse by the finger when the resistance of the photo
transistor will be slightly changed. The project's schematic circuit as shown, we chose a very
high resistance resistor R1, because most of the light through the finger is absorbed, it is
desirable that the phototransistor is sensitive enough. Resistance can be selected by experiment
to get the best results. The most important is to keep the shield stray light into the
phototransistor. For home lighting that is particularly important because the lights at home
mostly based 50HZ or 60HZ fluctuate, so faint heartbeat will add considerable noise.
When running the program the measured values are printed. To get a real heartbeat from this
could be challenging.

Note: Sometime this sensor throws value which might be not even closer 50 and sometimes it
even goes beyond 500, as this sensor is only for learning purpose don’t try to use this sensor for
real life scenario.

int sensorPin = 0;
double alpha = 0.75;
int period = 100;
double change = 0.0;
double minval = 0.0;
void setup ()
{
Serial.begin (9600);
}
void loop ()
{
static double oldValue = 0;
static double oldChange = 0;

int rawValue = analogRead (sensorPin);


double value = alpha * oldValue + (1 - alpha) * rawValue;

Serial.print (rawValue);
Serial.print (",");
Serial.println (value);
oldValue = value;

delay (period);
}
LIGHT CUP SENSOR

Two modules are used to perform a Magic Light Cup trick, where light is "poured" from one cup
to another, and the brightness changes to show how much light has been poured. PWM (pulse
width modulation) is used to change the brightness of the light in each cup. Mercury switches
provide a digital signal that triggers the PWM regulator on the Arduino, which changes the
brightness of the attached LED. Light is poured back and forth between two cups. This requires
two modules. Magic Light Cup modules are easy to Interactive Technology Division developed a
can and ARDUINO interactive modules, PWM dimming principle is to use the principle of two
modules brightness changes. Mercury switches provide a digital signal that triggers the PWM
regulator, through the program design, we can see the light like two cups filled with the effect of
shuffling back and forth.
Pin Specification of the sensor
S is the signal for the mercury switch
G is GND
+ is +5V
L is the pin for the LED
int LedPinA = 5; // connect a LED to pin 5
int LedPinB = 6; // connect another LED to pin 6
int ButtonPinA = 7; // S signal from the mercury switch
int ButtonPinB = 4; // S singal from the mercury switch
int buttonStateA = 0;
int buttonStateB = 0;
int brightness = 0;

void setup () {
pinMode (LedPinA, OUTPUT);
pinMode (LedPinB, OUTPUT);
pinMode (ButtonPinA, INPUT);
pinMode (ButtonPinB, INPUT);
}

void loop () {
buttonStateA = digitalRead (ButtonPinA);
if (buttonStateA == HIGH && brightness != 255) { brightness++; }

buttonStateB = digitalRead (ButtonPinB);


if (buttonStateB == HIGH && brightness != 0) { brightness--; }

analogWrite (LedPinA, brightness); // A changes in brightness


analogWrite (LedPinB, 255 - brightness); // B changes in brightness, but opposite to A
delay (25);
}
You require Two Light CUP sensor to execute this project.

First sensor connection as follows.


Connect the Gnd pin of the sensor to the Gnd pin of Arduino
Connect the + pin of the sensor to the 5v pin of Arduino
Connect the signal pin or the (S) pin to the 4th pin of Arduino
Connect the (L) pin of the sensor to the 5th pin of Arduino.

Second sensor connection as follows.


Connect the Gnd pin of the sensor to the Gnd pin of Arduino
Connect the + pin of the sensor to the 5v pin of Arduino
Connect the signal pin or the (S) pin to the 7th pin of Arduino
Connect the (L) pin of the sensor to the 6th pin of Arduino.

Upload the program and verify the result.


Hall Magnetic Sensor

TheHall Magnetic Sensor consists of a 3144EUA-S sensitive Hall-effect switch for high-
temperature operation, a 680Ω resistor and a LED. The Hall Magnetic Sensor is a magnetic
switch. If no magnetic field is present, the signal line of the sensor is HIGH. If a magnetic field is
presented to the sensor, the signal line goes LOW, at the same time the LED on the sensor lights up. The
polarity of the magnetic field is of influence to the switching action. The front side of the sensor needs the
opposite polarity as the back of the sensor to switch on.
Connecting to the Arduino
Pin - = GND, connect to GND of the Arduino
Pin (middle pin) +5 v, connect to Arduino +5
Pin S signal, connect to Arduino pin 10
Power consumption, 3 mA in rest, 8 mA when switched on
int led = 13;//LED pin
int sensor = 3; //sensor pin
int val; //numeric variable

void setup()
{
pinMode(led, OUTPUT); //set LED pin as output
pinMode(sensor, INPUT); //set sensor pin as input
}

void loop()
{
val = digitalRead(sensor); //Read the sensor
if(val == HIGH) //when magnetic field is detected, turn led on
{
digitalWrite(Led, HIGH);
}
else
{
digitalWrite(Led, LOW);
}
}
Use a Magnet to test this sensor, when you place a magnet near the sensor the LED on the
Arduino board will turn ON, This sensor produces output when it comes near a magnetic field.
Linear Hall Sensor

This sensor produces


a voltage when placed into a magnetic field. The voltage can be used to control your Arduino.
It is an analog sensor which means it can read out the value of the magnetic field.
RELAY
Relay is an electromagnetic switch, which is controlled by small current, and used to switch ON
and OFF relatively much larger current. Means by applying small current we can switch ON the
relay which allow much larger current to flow. Relay is the good example of controlling the AC
(alternate current) devices, using a much smaller DC current. Commonly used Relay is Single
Pole Double Throw (SPDT) Relay, it has five terminals as below:

When there is no voltage applied to the coil, COM (common) is connected to NC (normally
closed contact). When there is some voltage applied to the coil, the electromagnetic field
produced. Which attract the Armature (lever connected to spring), and COM and NO (normally
open contact) gets connected, which allow larger current to flow. Relays are available in many
ratings, here we used 6V operating voltage relay, which allow 7A-250VAC current to flow.

Relay is configured by using a small Driver circuit which consist a Transistor, Diode and a
resistor. Transistor is used to amplify the current so that full current (from the DC source – 9v
battery) can flow through coil to fully energies it. Resistor is used to provide biasing to transistor.
And Diode is used to prevent reverse current flow, when the transistor is switched OFF. Every
Inductor coil produces equal and opposite EMF when switched OFF suddenly, this may cause
permanent damage to components, so Diode must be used to prevent reverse current. A Relay
module is easily available in the market with all its Driver circuit on the board or you can create
it by using above components. Here we have used 6V Relay module.

Relay Module is used to control AC circuits, the relay acts as a switch that responds to a signal
received from the Arduino, it has an integrated LED that indicates if the signal is high or low.
Commonly used in Electrical projects to control lights and other electronic appliances.
The relay consist of a 1MΩ resistor, a LED, a 1N4007 rectifier diode and a 5VDC relay capable
of handling up to 250VAC and 10A.
On the DC side of the board there are 3 pins for signal, power and ground. On the AC side there
are 3 contacts, NC (Normally Closed), Common and NO (Normally Open).
For the DC part of the circuit connect S (signal) to pin 10 on the Arduino, also connect the Power
line (+) and ground (-) to +5 and GND respectively.
On the AC side connect your feed to Common (middle contact) and use NC or NO according to
your needs.
NO (Normally Open) will get power when (S) is high, NC (Normally Closed) gets disconnected
when (S) is high.
Always be very careful when experimenting with AC, electrical shock can result in serious
injuries.
The following Arduino sketch will turn the relay on/off every second. We'll connect a desk lamp
to the relay using the NO (Normally Open) connection so the lamp is off when the relay is off.
Running the sketch will cause the lamp to light up intermittently.
int relay = 10; //Pin 10

void setup()
{
pinMode(relay,OUTPUT); // Define the port attribute as output
}

void loop()
{
digitalWrite(relay,HIGH); // turn the relay ON
// [NO] is connected to feed
// [NC] is not connected to feed
delay(1000);

digitalWrite(relay,LOW); // turn the relay OFF


// [NO] is not connected to feed
// [NC] is connected to feed
delay(1000);
}
7 color Flash LED

This LED automatically switches between 7 colours. The LED has an integrated IC. If you disconnect the
LED the colours will reset and the animation will start over.
Connect the 5v to the 13th pin of Arduino and Gnd to the Gnd pin of Arduino.
void setup () {
// Initialize the digital pin as an output.
// Pin 13 has an LED connected on most Arduino boards:
pinMode (13, OUTPUT);
}
void loop () {
digitalWrite (13, HIGH); // set the LED on
delay (2000); // wait for a second
digitalWrite (13, LOW); // set the LED off
delay (2000); // wait for a second
}
Mercury Tilt switch
Mercury tilt switch module, it uses a small mercury ball that completes the circuit when you tilt
the module.
This module consists of a mercury switch, a 680Ω resistor and a LED that will light up when tilt
is detected. The mercury ball will open/close the circuit when the module is rotated.
Connect the Power line (middle) and ground (-) to +5 and GND respectively. Connect signal (S)
to pin 3 on the Arduino.

int led_pin = 13; // Define the LED interface


int switch_pin = 3; // Definition of mercury tilt switch sensor interface
int val; // Defines a numeric variable

void setup()
{
pinMode(led_pin, OUTPUT);
pinMode(switch_pin, INPUT);
}

void loop()
{
val = digitalRead(switch_pin); // check mercury switch state
if(val == HIGH)
{
digitalWrite(led_pin, HIGH);
}
else
{
digitalWrite(led_pin, LOW);
}
}
Temperature Sensor
DS18B20 Temperature Sensor

DS18B20 is 1-Wire digital temperature sensor from Maxim IC. Reports degrees in Celsius with
9 to 12-bit precision, from -55 to 125 (+/-0.5). Each sensor has a unique 64-Bit Serial number
etched into it - allows for a huge number of sensors to be used on one data bus.
To use this sensor you required two library files added to Arduino library, these files are added
into your Code files which you can download from the last page of this book by clicking the
resource link.
Alternatively the files can be downloaded from the following links.
http://www.pjrc.com/teensy/arduino_libraries/OneWire.zip
https://github.com/milesburton/Arduino-Temperature-Control-Library
Click on the sketch on Arduino IDE and then select Include Library and click on Add .ZIP
Library…
Navigate to the library files that is placed inside the folder named DS18B20 You need to include
two files namely, one wire and Arduino Temperature control library.
Once the file is added you will get a message saying “library added to your libraries at the
bottom of your Arduino IDE.
Connect the circuit as follows:
Upload the following program into your Arduino Uno board.
// First we include the libraries
#include <OneWire.h>
#include <DallasTemperature.h>
// Data wire is plugged into pin 2 on the Arduino
#define ONE_WIRE_BUS 2
// Setup a oneWire instance to communicate with any OneWire devices
// (not just Maxim/Dallas temperature ICs)
OneWire oneWire(ONE_WIRE_BUS);
// Pass our oneWire reference to Dallas Temperature.
DallasTemperature sensors(&oneWire);
void setup(void)
{
// start serial port
Serial.begin(9600);
Serial.println("Dallas Temperature IC Control Library Demo");
// Start up the library
sensors.begin();
}
void loop(void)
{
// call sensors.requestTemperatures() to issue a global temperature
// request to all devices on the bus
Serial.print(" Requesting temperatures...");
sensors.requestTemperatures(); // Send the command to get temperature readings
Serial.println("DONE");
Serial.print("Temperature is: ");
Serial.print(sensors.getTempCByIndex(0)); // Why "byIndex"?
// You can have more than one DS18B20 on the same bus.
// 0 refers to the first IC on the wire
delay(1000);
}

Open the Serial Monitor to check the current Temperature reading of your room.
Analog Thermistor Temperature Sensor

Analog Temperature Sensor, measures ambient temperature based on resistance of the


thermistor. Analog Temperature Sensor module consist of a NTC thermistor and a 10 kΩ
resistor. The resistance of the thermistor varies with surrounding temperature, we'll use
the Steinhart–Hart equation to derive precise temperature of the thermistor.

Connect board's power line (middle) and ground (-) to 5V and GND respectively. Connect signal
(S) to pin A0 on the Arduino.
The following Arduino Sketch will derive the temperature of the thermistor using the Steinhart-
Hart equation implemented in the function Thermistor.
#include <math.h>

double Thermister(int RawADC) {


double Temp;
Temp = log(((10240000/RawADC) - 10000));
Temp = 1 / (0.001129148 + (0.000234125 + (0.0000000876741 * Temp * Temp ))* Temp );
Temp = Temp - 273.15; // Convert Kelvin to Celcius
return Temp;
}

void setup() {
Serial.begin(9600);
}

void loop() {
Serial.print(Thermister(analogRead(0))); //read pin A0
Serial.println("c");
delay(500);
}

Open the serial monitor to know the temperature reading from the sensor.
TEMPERATURE AND HUMIDITY SENSOR
MODULE

Temperature and humidity sensor module, provides a digital serial interface to measure
humidity and temperature. This module consist of a DHT11 digital humidity and temperature
sensor and a 1 kΩ resistor. The DHT11 uses an internal thermistor and a capacitive humidity
sensor to determine environment conditions, an internal chip is responsible for converting
readings to a serial digital signal.
This sensor Requires DHT Sensor library which can be downloaded from the Arduino IDE

Goto sketch and click on the Manage Libraries..


Type DHT on the search bar
Click on the DHT sensor library by Adafruit and install it.
To Make the DHT library we need to include another library called adafruit unified sensor
drivers. If you get any error during compiling the DHT sensor this may be the reason for it.
Download the file from the given link or you can find the file from the resources link that has
given at the end of this book.
https://github.com/adafruit/Adafruit_Sensor
Connect the DHT sensor module to the Arduino Uno board as shown in the below figure.
The following sketch uses pin 8 on the Arduino to serially send and receive data from the KY-
015 sensor. Serial communication is archived by sending specific high/low signals to the sensor
and waiting for a response. Temperature and humidity data is read bit by bit and returned as an
array of bytes.
#include "DHT.h"

#define DHTPIN 8 // what digital pin we're connected to

#define DHTTYPE DHT11 // DHT 11

DHT dht(DHTPIN, DHTTYPE);

void setup() {
Serial.begin(9600);
Serial.println("DHTxx test!");

dht.begin();
}

void loop() {
// Wait a few seconds between measurements.
delay(2000);

// Reading temperature or humidity takes about 250 milliseconds!


// Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
float h = dht.readHumidity();
// Read temperature as Celsius (the default)
float t = dht.readTemperature();
// Read temperature as Fahrenheit (isFahrenheit = true)
float f = dht.readTemperature(true);

// Check if any reads failed and exit early (to try again).
if (isnan(h) || isnan(t) || isnan(f)) {
Serial.println("Failed to read from DHT sensor!");
return;
}

// Compute heat index in Fahrenheit (the default)


float hif = dht.computeHeatIndex(f, h);
// Compute heat index in Celsius (isFahreheit = false)
float hic = dht.computeHeatIndex(t, h, false);

Serial.print("Humidity: ");
Serial.print(h);
Serial.print(" %\t");
Serial.print("Temperature: ");
Serial.print(t);
Serial.print(" *C ");
Serial.print(f);
Serial.print(" *F\t");
Serial.print("Heat index: ");
Serial.print(hic);
Serial.print(" *C ");
Serial.print(hif);
Serial.println(" *F");
}
Sound Sensor

Sound Sensor is a small board with a microphone which allows you to detect the sound in an
environment.
NOTE:
The real sensor can be different from the fritzing image.
The Sound Sensor usaully has four pins. Connect the Ground pin to the GND of board, the Vcc
to pin 5V of the board and the Analogic pin to pin A0 of board.
Also connect the anode of the LED (usually the longer pin) in series to a resistor of 220Ω and
connect it to pin 13 of board.
Finally connect the cathode of led to GND of board.

Initially the led is switched off. If you clap, the led switch goes on and it will remain until you
clap again. Now we'll explain the sketch in detail. In the first part of sketch we define the
variables used, like the threshold of sensor. You can change the sensibility of the sensor by
changing the value of threshold or turning the trimmer placed on it. In the setup function we
define the led pin as output and we set it to LOW. In the loop block we read the detected value
from the sensor and it is placed in the sound variable, after we compare this value with the
threshold value. If the sound detected is higher we'll change the LED status, by changing the
variable led value. The led value variable is finally used with the digitalWrite to change the LED
status.

int led = 13;


int threshold = 500; //Change this value if you want change the sensibility of sensor
int sound;
int led_value;
void setup() {
pinMode(led, OUTPUT);
digitalWrite(led,LOW);
led_value=0;
}
void loop() {
sound = analogRead(A0); // Reads the value from the Analog PIN A0
if(sound>=threshold){
led_value=!led_value;}
digitalWrite(led, led_value);
delay(100);
}
Metal Touch Sensor

This sensor will provide a signal when a finger (or any other body part) touches the bent pin of the
transistor.
It can be used as a switch.
A metal touch sensor is a type of switch that only operates when it's touched by a charged body.
It has a high-frequency transistor which can conduct electricity when receiving electromagnetic
signals.
In this experiment, touch the base electrode of a transistor with fingers to make it conduct
electricity, for human body itself is a kind of conductor and an antenna that can receive
electromagnetic waves in the air. These electromagnetic wave signals collected by human body
are amplified by the transistor and processed by the comparator on the module to output steady
signals.

With the LED attached to pin 13 of Uno, connect pin D0 of the sensor to D7 of the Uno board.
When the metal touch sensor detects touch signals, the LED will be on. Otherwise, it will be off.
int Led = 13 ; // define LED Interface
int buttonpin = 3; // define Metal Touch Sensor Interface
int val ; // define numeric variables val
void setup ()
{
pinMode (Led, OUTPUT) ; // define LED as output interface
pinMode (buttonpin, INPUT) ; // define metal touch sensor output interface
}
void loop ()
{
val = digitalRead (buttonpin) ; // digital interface will be assigned a value of 3 to read val
if (val == HIGH) // When the metal touch sensor detects a signal, LED flashes
{
digitalWrite (Led, HIGH);
}
else
{
digitalWrite (Led, LOW);
}
}
Two Color LED Module

3mm two color LED module, emits red and green light. You can adjust the amount of each color
using PWM.
This module consist of a common cathode 3mm red/green LED and a 0Ω resistor, since
operating voltage is 2.0v ~2.5v you'll need to use limiting resistors to prevent burnout when
connecting to the Arduino.

We'll use a couple of 330Ω resistors to limit the current from the Arduino and prevent burning the LED.
int redpin = 11; // pin for red signal
int greenpin = 10; // pin for green signal
int val;

void setup() {
pinMode(redpin, OUTPUT);
pinMode(greenpin, OUTPUT);
}
void loop() {
for(val = 255; val > 0; val--) {
analogWrite(redpin, val); //dim red
analogWrite(greenpin, 255 - val); // brighten green
delay(15);
}
for(val = 0; val < 255; val++) {
analogWrite(redpin, val); //brighten red
analogWrite(greenpin, 255 - val); //dim green
delay(15);
}
}
INFRARED RECEIVER MODULE

This module consists of an 1838 IR receiver, a 1kΩ resistor and a LED. It works together with
the IR transmitter module.

Connect the Power line (middle) and ground (-) to +5 and GND respectively. Connect signal (S)
to pin 11 on the Arduino. Line to IR receiver and transmitter
The following Arduino sketch uses the IRremote library to receive and process infra-red signals.
The library is available in the resource folder. You can navigate to end of this page to download
the resource folder.
#include <IRremote.h>

int RECV_PIN = 11; // define input pin on Arduino


IRrecv irrecv(RECV_PIN);
decode_results results; // decode_results class is defined in IRremote.h

void setup() {
Serial.begin(9600);
irrecv.enableIRIn(); // Start the receiver
}

void loop() {
if (irrecv.decode(&results)) {
Serial.println(results.value, HEX);
irrecv.resume(); // Receive the next value
}
delay (100); // small delay to prevent reading errors
}
INFRARED TRANSMITTER MODULE

IR Transmitter Module, emits infrared light at 38kHz. The KY-005 Infrared Transmitter Module
consists of just a 5mm IR LED. It works together with the IR receiver module.

Connect the Power line (middle) and ground (-) to +5 and GND respectively. Connect signal (S)
to pin 3 on the Arduino UNO or pin 9 on the Arduino Mega. The pin number for the infrared
transmitter is determined by the IRremote library. The following Arduino sketch uses the
IRremote library to serially send infra-red signals. The output pin is determined by the library
and it depends on the board you are using, check the IRremote library documentation for
supported boards.
#include <IRremote.h>
IRsend irsend;

void setup()
{
Serial.begin(9600);
}

void loop()
{
for (int i = 0; i < 50; i++) {
irsend.sendSony(0xa90, 12); // Sony TV power code
delay(40);
}
}
LASER TRANSMITTER MODULE

The Laser transmitter module consists of a 650nm red laser diode head and a resistor. Handle
with caution, do not look directly into the laser head.

Connect signal (S) to pin 13 on the Arduino and ground (-) to GND. Middle pin is not used.
int laserPin = 13;

void setup() {
pinMode(laserPin, OUTPUT); // Define the digital output interface pin 13
}

void loop() {
digitalWrite(laserPin, HIGH); // Open the laser head
delay(1000); // Delay one second
digitalWrite(laserPin, LOW); // Close the laser head
delay(1000);
}
This Arduino sketch will repeatedly turn on and off the laser head every second.
PHOTORESISTOR MODULE
Photoresistor module, used to measure light intensity. It can determine the presence or absence
of light.

This module consists of a photoresistor and a 10 kΩ in-line resistor. The photoresistor's


resistance will decrease in the presence of light and increase in the absence of it. The output is
analog and determines the intensity of light.

The following Arduino sketch will output readings from the photoresistor, cover the module with
your hand to prevent light on it and the output values will be low, point a light to the sensor and
the values will be high.

int sensorPin = 2; //define analog pin 2


int value = 0;

void setup() {
Serial.begin(9600);
}

void loop() {
value = analogRead(sensorPin);
Serial.println(value, DEC); // light intensity
// high values for bright environment
// low values for dark environment
delay(100);
}
MERCURY TILT SWITCH MODULE

Mercury tilt switch module, it uses a small mercury ball that completes the circuit when you tilt
the module. This module consists of a mercury switch, a 680Ω resistor and a LED that will light
up when tilt is detected. The mercury ball will open/close the circuit when the module is rotated.

Connect the Power line (middle) and ground (-) to +5 and GND respectively. Connect signal (S)
to pin 3 on the Arduino.
int led_pin = 13; // Define the LED interface
int switch_pin = 3; // Definition of mercury tilt switch sensor interface
int val; // Defines a numeric variable

void setup()
{
pinMode(led_pin, OUTPUT);
pinMode(switch_pin, INPUT);
}

void loop()
{
val = digitalRead(switch_pin); // check mercury switch state
if(val == HIGH)
{
digitalWrite(led_pin, HIGH);
}
else
{
digitalWrite(led_pin, LOW);
}
}
PHOTO INTERRUPTER MODULE

Photo Interrupter Module will trigger a signal when light between the sensor's gap is blocked.
The KY-010 Photo Interrupter module consists of an optical emitter/detector in the front and two
resistors (1 kΩ and 33 Ω) in the back. The sensor uses a beam of light between de emitter and
detector to check if the path between both is being blocked by an opaque object.

Connect the power line (middle) and ground (left) to +5V and GND respectively. Connect signal
(S) to pin 3 on the Arduino.
int Led = 13; // define LED pin
int buttonpin = 3; // define photo interrupter signal pin
int val; //define a numeric variable

void setup()
{
pinMode(Led, OUTPUT); // LED pin as output
pinMode(buttonpin, INPUT); //photo interrupter pin as input
}

void loop()
{
val=digitalRead(buttonpin); //read the value of the sensor
if(val == HIGH) // turn on LED when sensor is blocked
{
digitalWrite(Led,HIGH);
}
else
{
digitalWrite(Led,LOW);
}
}
VIBRATION SWITCH MODULE

Vibration Switch Module is used for detection of shock and vibration. Vibration Switch Module
consists of a conductive vibration spring and a 10k resistor, it will react to shock and vibration by
closing the circuit.

Connect the Power line (middle) and ground (-) to +5 and GND respectively. Connect signal (S)
to pin 3 on the Arduino.
int Led = 13; // define the LED Pin
int shock = 3 // define the sensor Pin
int val; // define a numeric variable val

void setup () {
pinMode (Led, OUTPUT); // LED pin as output
pinMode (shock, INPUT); // input from KY-002 sensor
}
void loop () {
val = digitalRead (shock); // read the value from KY-002
if (val == HIGH ) {// when sensor detects shock, LED flashes
digitalWrite(Led, LOW);
} else {
digitalWrite (Led, HIGH);
}
}
KEY SWITCH MODULE

Key Switch Module is a push button that will output a high signal when pressed. The module
consists of a FZ1713 tactile push button switch and a resistor.

Connect the power line (middle) and ground to +5V and GND respectively. Connect signal (S) to
pin 3 on the arduino.
int led = 13; //Define the LED pin
int buttonpin = 3; //Define the push button pin
int val; //Define a numeric variable

void setup()
{
pinMode(led,OUTPUT);
pinMode(buttonpin,INPUT);
}
void loop()
{
val = digitalRead(buttonpin); // check the state of the button
if(val==HIGH) // if button is pressed, turn LED on
{
digitalWrite(led,HIGH);
}
else
{
digitalWrite(led,LOW);
}
}
ACTIVE BUZZER MODULE

Active Buzzer Module, it produces a single-tone sound when signal is high. The Active Buzzer
module consists of an active piezoelectric buzzer, it generates a sound of aproximately 2.5kHz
when signal is high.

Connect signal (S) to pin 8 on the Arduino and Ground (-) to GND. Be aware that some boards
are wrongly labelled, try inverting the cables if you can't hear any sound when running the
sketch.
int buzzerPin = 8;

void setup ()
{
pinMode (buzzerPin, OUTPUT);
}

void loop ()
{
digitalWrite (buzzerPin, HIGH);
delay (500);
digitalWrite (buzzerPin, LOW);
delay (500);
}
PASSIVE BUZZER MODULE

Passive Piezoelectric Buzzer Module, it can produce a range of sound tones depending on the
input frequency. The passive Buzzer Module consists of a passive piezoelectric buzzer, it can
generate tones between 1.5 to 2.5 kHz by switching it on and off at different frequencies either
using delays or PWM.
Connect signal (S) to pin 8 on the Arduino and ground (-) to GND. The middle pin is not used.

int buzzer = 8; // set the buzzer control digital IO pin


void setup() {
pinMode(buzzer, OUTPUT); // set pin 8 as output
}
void loop() {
for (int i = 0; i < 80; i++) { // make a sound
digitalWrite(buzzer, HIGH); // send high signal to buzzer
delay(1); // delay 1ms
digitalWrite(buzzer, LOW); // send low signal to buzzer
delay(1);
}
delay(50);
for (int j = 0; j < 100; j++) { //make another sound
digitalWrite(buzzer, HIGH);
delay(2); // delay 2ms
digitalWrite(buzzer, LOW);
delay(2);
}
delay(100);
}
Ball Switch

This sensor contains a small metal ball which will complete a circuit depending on the position
in the sensor. Because the sensor is very basic, it can only detect large changes when its tilt, and
cannot measure the angle of its tilt. Tilt switch module and a digital interface, built-in LED build
a simple circuit to produce tilt warning lamp comes with digital interfaces of the LED, the tilt
switch sensor interface to access digital 3, when the tilt open Off sensor senses a key signal, LED
lights, otherwise off.
int Led = 13 ;// define LED Interface
int buttonpin = 3; // define the tilt switch sensor interfaces
int val ;// define numeric variables val
void setup ()
{
pinMode (Led, OUTPUT) ;// define LED as output interface
pinMode (buttonpin, INPUT) ;//define the output interface tilt switch sensor
}
void loop ()
{
val = digitalRead (buttonpin) ;// digital interface will be assigned a value of 3 to read val
if (val == HIGH) //When the tilt sensor detects a signal when the switch, LED flashes
{
digitalWrite (Led, HIGH);
}
else
{
digitalWrite (Led, LOW);
}
}
Magnetic Reed Switch

This switch provides


us an analog as well as a digital interface. You can see that the reed switch module has a
potentiometer that is used as a pull up resistor. The module also has an on board led which
indicates that the reed switch has detected a magnet field or not. These are just used for the
switching mechanism using electromagnetism. The reed switch module has both analog and
digital output. So, we can use it in both ways.
The connections are very easier. We have connected the +5V and ground pin of the module with
the +5v and the ground pin of the Arduino. Then we connected the digital of the module with the
pin 2 of the Arduino. A led is attached at the pin 12 of the Arduino which will light up when the
module will sense a magnetic field. While using the digital pin, we can change the threshold
value by changing the resistance of potentiometer (rotating the top of potentiometer).
int Led_pin = 12 ; // initializing the pin 12 as led pin
int Sensor_pin = 2 ; // initializing the pin 2 sensor pin
int Value ; // initializing a variable to store sensor output

void setup ()
{
pinMode (Led_pin, OUTPUT) ; // declaring pin 12 as output pin
pinMode (Sensor_pin, INPUT) ; // declaring pin 2 as input pin
}

void loop (){

Value = digitalRead (Sensor_pin) ; // reading the sensor state

if (Value == HIGH) // If sensor pin is high then high the pin 12

{
digitalWrite (Led_pin, HIGH) ;
}
else
{
digitalWrite (Led_pin, LOW) ; // Otherwise turn off or LOW
}
}
Line Tracking Sensor

This sensor can detect lines in black and white. You could use this sensor for making a robot/car
follow a line. The Line Tracking Sensor for Arduino can detect the white lines in black and black
lines in white. The single line-tracking signals can provide a stable output signals TTL, so look
for more accurate and more stable line. Optional multi-channel mix is easy to install with the
necessary line-tracking robot sensors. Use the button Arduino program to know the status of this
sensor in the serial monitor.
Rotary Encoder Sensor

A rotary encoder has a fixed number of positions per revolution. These positions are easily felt
as small “clicks” you turn the encoder. On one side of the switch there are three pins. They are
normally referred to as A, B and C. Inside the encoder there are two switches. Once switch
connects pin A to pin C and the other switch connects pin B to C. In each encoder position, both
switches are either opened or closed. Each click causes these switches to change states as
follows:
If both switches are closed, turning the encoder either clockwise or counterclockwise one
position will cause both switches to open
If both switches are open, turning the encoder either clockwise or counterclockwise one
position will cause both switches to close.
int pinA = 3; // Connected to CLK on KY-040
int pinB = 4; // Connected to DT on KY-040
int encoderPosCount = 0;
int pinALast;
int aVal;
boolean bCW;

void setup() {
pinMode (pinA,INPUT);
pinMode (pinB,INPUT);
/* Read Pin A
Whatever state it's in will reflect the last position
*/
pinALast = digitalRead(pinA);
Serial.begin (9600);
}

void loop() {
aVal = digitalRead(pinA);
if (aVal != pinALast){ // Means the knob is rotating
// if the knob is rotating, we need to determine direction
// We do that by reading pin B.
if (digitalRead(pinB) != aVal) { // Means pin A Changed first - We're Rotating Clockwise
encoderPosCount ++;
bCW = true;
} else {// Otherwise B changed first and we're moving CCW
bCW = false;
encoderPosCount--;
}
Serial.print ("Rotated: ");
if (bCW){
Serial.println ("clockwise");
}else{
Serial.println("counterclockwise");
}
Serial.print("Encoder Position: ");
Serial.println(encoderPosCount);

}
pinALast = aVal;
}
Resources
Download the book pdf and other materials from this link

https://goo.gl/Yq7r5r

You might also like