You are on page 1of 83

SRM Institute of Science and Technology

Department of Electronics and Communication Engineering

ECV0704J – Arduino for Engineers: From Basics to Advanced Applications

Open source Hardware and Software (OSHS)

Open source hardware is hardware whose design is made publicly available so that anyone can
study, modify, distribute, make, and sell the design or hardware based on that design. The
hardware's source, the design from which it is made, is available in the preferred format for
making modifications to it. Open source software is code that is designed to be publicly
accessible—anyone can see, modify, and distribute the code as they see fit. Open source software
is developed in a decentralized and collaborative way, relying on peer review and community
production.

"Open hardware," or "open source hardware," refers to the design specifications of a physical
object which are licensed in such a way that said object can be studied, modified, created, and
distributed by anyone. "Open hardware" is a set of design principles and legal practices, not a
specific type of object.

Today open source has changed the face of technology – it allows customers to know how the
code works, facilitating the development of the most innovative software. It allows reuse and
recycling of code, making it easier to collaborate and achieve goals, rather than trying to do
everything yourself.

Open source is generally much more cost-effective than a proprietary solution. Not only are open
source solutions typically much more inexpensive in an enterprise environment for equivalent or
superior capability, but they also give enterprises the ability to start small and scale (more on that
coming up). Open-source software (OSS) advantages include lower starting costs, faster project
starts, faster iteration, more-flexible software development processes, robust community-driven
support, and easier license management, without being contractually locked into work with a
single vendor...to name just a few.

Course Objectives

 Know what an Arduino is and why they can be useful


 Build a circuit and program the Arduino
 Be empowered to create your own electronics projects that will improve your
environment

1
Course Outcome

On successful completion of this workshop the participants can able to:

 Understand what an Arduino is and how it works


 Learn how to use an Arduino safely
 Program your Arduino using code that you've written in the Arduino IDE
 Understand best practice concepts for programming and prototyping
 Use a wide variety of hardware and components and prototype your projects
 Build your own innovative project with Arduino

Requirements
 Personal Computer
 Arduino UNO Development Board
 Arduino IDE Software
 Sensors and Interfaces
 Breadboard and Connecting Wires

Who are eligible for this course

 Anyone whom would like to get started with digital electronics and build their own
projects

2
TABLE OF CONTENTS
Sl. No Description Page No
1 Introduction to open-source hardware and software 4-6
2 Introducing the Arduino, Arduino IDE 7-14
Part 1 Digital Interfaces - Digital I/O
3 Blinking LED 15-18
4 Blinking various LEDs using Arrays 19-21
5 LED Fading using Arduino PWM 22-25
Part-2 Analog Interface A/D Converter
6 LED Brightness Control Using a Potentiometer 26-28
7 LED Brightness Control Using an LDR 29-32
8 Arduino Accelerometer 33-37
Part-3 Arduino Communication Protocol
9 Introduction to Arduino Communication Protocol 38-42
10 UART- Serial UART Communication between Two Arduino Boards 43-50
11 I2C - I2C Communication between Two Arduino Boards 51-56
12 SPI - SPI Communication Between Two Arduinos 57-60
Part-4 Arduino Based Simple Projects
13 Project 1 - Traffic Lights 61-65
14 Project 2 - LED Brightness on a 16x2 LCD 66-70
15 Project 3 - Parking Sensor 71-74
16 Project 4 - Control LEDs with IR Remote Control 75-83

3
1.Introduction to Open-Source
Hardware and Software

What is open-source hardware (OSH)?


A hardware whose design is made publicly available to study, modify, distribute, make and sell
the design or hardware based on that design is called an Open-source hardware. The term
―open-source‖ first appeared with the early open software movement in the 1970s, which aimed
to spread the concept of freely-sharing source codes for software development. The movement
grew and has had much success. A wide variety of software is freely licensed to grant users the
right to use, change, and study the source code without restrictions. The idea of OSH emerged
from the concept of open-source software.

Example for OSH


A good example of OSH is the Arduino electronic prototyping platform. It‘s an easy-to-learn
microcontroller that allows you to take information from the Arduino platform and act on that
environment. In the old days, learning to program a microcontroller was very difficult. Now,
Arduino is an open-source project. There are codes and designs published open access, but also
many researchers contributed to build up libraries with new ideas and schematics. Therefore, it‘s
currently much easier to automate processes of many tasks.

How is open hardware licensed?


Open-source hardware licenses generally permit recipients of the designs and documentations to
study them, redistribute and modify them, and then to distribute any modifications. Additionally,
open hardware licenses don't prevent someone from giving away or even selling the project's
documentation. Like software, hardware designs and inventions are subject to copyright and
patent law. And like open-source software, open-source hardware uses these intellectual property
laws creatively to make hardware designs publicly accessible. Because of their similarity to
open-source software projects, many open hardware projects simply use existing free and open-
source software licenses when licensing their works.

4
What is open-source software (OSS)?
Open-source software (OSS) is software that is distributed with its source code, making it
available for use, modification, and distribution with its original rights. Source code is the part of
software that most computer users don‘t ever see; it‘s the code computer programmers
manipulate to control how a program or application behaves. Programmers who have access to
source code can change a program by adding to it, changing it, or fixing parts of it that aren‘t
working properly. OSS typically includes a license that allows programmers to modify the
software to best fit their needs and control how the software can be distributed.

The idea of making source code freely available originated in 1983 from an ideological
movement informally founded by Richard Stallman, a programmer at MIT. Stallman believed
that software should be accessible to programmers so they could modify it as they wished, with
the goal of understanding it, learning about it, and improving it. Stallman began releasing free
code under his own license, called the GNU Public License. This new approach and ideology
surrounding software creation took hold and eventually led to the formation of the Open-Source
Initiative in 1998.

The Open-Source Initiative (OSI) was created to promote and protect open-source software and
communities. In short, the OSI acts as a central informational and governing repository of open-
source software. It provides rules and guidelines for how to use and interact with OSS, as well as
providing code licensing information, support, definitions, and general community collaboration
to help make the use and treatment of open source understandable and ethical. Some of the OSS
applications or software are given below:
o GNU/Linux
o Mozilla Firefox
o VLC media player
o SugarCRM
o GIMP
o VNC
o Apache web server
o LibreOffice
o jQuery

5
Pros of open-source software
o Open-source software is free.
o Open-source is flexible; developers can examine how the code works and freely make
changes to dysfunctional or problematic aspects of the application to better fit their
unique needs.
o Open-source is stable; the source code is publicly distributed, so users can depend on it
for their long-term projects since they know that the code‘s creators cannot simply
discontinue the project or let it fall into disrepair.
o Open-source fosters ingenuity; programmers can use pre-existing code to improve the
software and even come up with their own innovations.
o Open-source comes with a built-in community that continuously modifies and improves
the source code.
o Open-source provides great learning opportunities for new programmers.

Cons of open-source software:


o Open-source can be harder to use and adopt due to difficulty setting it up and the lack of
friendly user interfaces.
o Open-source can pose compatibility issues. When attempting to program proprietary
hardware with OSS, there is often a need for specialized drivers that are typically only
available from the hardware manufacturer.
o Open-source software can pose liability issues. Unlike commercial software, which is
fully controlled by the vendor, open source rarely contains any warranty, liability, or
infringement indemnity protection. This leaves the consumer of the OSS responsible for
maintaining compliance with legal obligations.
o Open-source can incur unexpected costs in training users, importing data, and setting up
required hardware.

6
2.Introducing the Arduino

What is an Arduino?
The Arduino is a microcontroller-based development board that you can program to read
information from the world around you and send commands to the outside world. All of this is
possible because you can connect several devices and components to the Arduino to do what
you want.

You can do amazing projects with it, there is no limit for what you can do, and using your
imagination everything is possible! Since the development of Arduino, various models and many
derivative controllers have been introduced, including Arduino Uno, Arduino Nano, Arduino
Yún, etc. Our course uses the Arduino Uno R3 development board. As shown below:

Arduino UNO R3 board with ATmega328P

Basically, it is a small development board with a brain (also known as a microcontroller) that
you can connect to electrical circuits. This makes it easy to read inputs – read data from the
outside – and control outputs - send a command to the outside. The brain of this board
(Arduino Uno) is an ATmega328p chip where you can store your programs that will tell your
Arduino what to do.

7
Exploring the Arduino Uno Board
The following is a detailed introduction to the development board of Arduin Uno R3 model:

(1) Power port:

Arduino UNO has three power supply methods:

o Power supply via USB interface. The voltage is 5 V;


o Power is supplied with the DC power input interface, and the voltage requires 7 to 12
V;
o Power is supplied with the 5 V or VIN port at the power supply interface.
o The power supply at the 5 V port must be 5 V
o The power supply at the VIN port is 7 to 12 V.
o IOREF: Provide working reference voltage for the expansion board.
o RESET: reset pin. Restart the Arduino and start the program from the beginning.
o GND: Ground terminal.
o Vin: provides external power supply voltage, which can be directly connected to
external power supply by this port.

(2) Analog port (A0~A5):

Arduino Uno has 6 analog pins. Pins A0-A5 can read analog voltages. They are used as ADCs
(analog-to-digital converters). ADCs convert the voltages into bits that the microprocessor can
understand. These pins are used as analog inputs, but they can also be used as digital inputs or
digital outputs. They are often used to read sensor data.

(3) Digital port (0~13):

Arduino has 14 digital pins, labeled from 0 to 13 that can act as inputs or outputs.

o When set as inputs, these pins can read voltage. They can only read two states: HIGH or
LOW.
o When set as outputs, these pins can apply voltage. They can only apply 5V (HIGH) or 0V
(LOW).

Among them, pin 13 is connected to the on-board LED indicator (D13 indicator); digital pins can
be turned on or off. When they are on, they are at a high level of 5V. When they are off, they are
at a low level of 0V status. On the Arduino, when the digital pins are configured as outputs, they
are set to 0 or 5V. When the digital pin is configured as an input, the voltage is provided by an
external device. This voltage can be varied between 0-5V and converted to a digital 0 or 1 to
indicate low or high level. To determine this, there are 2 thresholds:

o If it is lower than 0.8v, it is regarded as 0.


o If it is higher than 2.0v, it is regarded as 1.
8
When connecting components to digital pins, make sure that the logic levels match. If the voltage
is between the thresholds, the return value will be undefined. Pins 3, 5, 6, 9, 10, 11 have PWM
function. Pins 10, 11, 12, and 13 can be used for SPI communication. 0 and 1 are Rx and Tx pins.
These two pins are generally used as serial ports. Non-serial devices should not occupy this pin
as much as possible. (Rx send, Tx receive). Pin 2 and 3 can input an external interrupt signal. A4
(SDA), A5 (SCL) and TWI interface can be used for TWI communication, being compatible
with I²C communication. You can use the official Wire library to operate. The AERF pin can be
used for analog input reference voltage.

Attention:

o Each pin can provide/receive up to 40mA of current. But the recommended current is
20mA.
o The absolute maximum current provided by all pins is 200mA.

(4) ICSP port:

The ICSP (In-Circuit Serial Programming) port is an online program programming port, which is
a 2*3 pin header on the Arduino development board, and its 6 pins are connected to the
microcontroller on the Arduino development board, corresponding to 5V, MISO, MOSI, SCK,
GND and RESET respectively. These pins enable users to program the firmware on the Arduino
development board. Generally, when programming a program, the ICSP port close to the
microcontroller is used.

(5) Indicator light:

Arduino Uno has 4 LED indicators. The functions are as follows:

o ON: power indicator. When the Arduino is powered on, the ON light will be on.
o TX: serial port sending indicator. When the USB is connected to the computer and the
Arduino transmits data to the computer, the TX light will be on.
o RX: serial port receiving indicator. When using USB to connect to the computer and
the Arduino receives the data from the computer, the RX light will be lit up.
o L: D13 pin indicator light, also known as programmable control indicator light. The
LED is connected to pin 13 of the Arduino by a special circuit. When the pin 13 is high
or high impedance, the LED will be lit; when it is low, it will not be lit. The LED can
be controlled to be on or off by a program or an external input signal.

(6) DC external plug:

Using an external power supply of 7-12V to power the Arduino.

9
(7) USB interface:

It is used to connect the USB interface of the computer to achieve serial communication,
uploading programs, and serial port monitoring between the Arduino and the computer.

(8) Reset button:

Restart the Arduino and start the program from the beginning.

(9) Microcontroller:

The "brain" of Arduino is based on the smallest system of ATmega328P microcontroller.


Everything on the Arduino board is meant to support this microcontroller. This is where you
store your programs to tell the Arduino what to do.

Note: For more information about the Arduino hardware parts, visit the Arduino official web
page.

Downloading the Arduino IDE


The Arduino IDE (Integrated Development Environment) is where you develop your programs
that will tell the Arduino what to do. You can load new programs onto the main chip, the
ATmega328p, via USB using the Arduino IDE. To download the Arduino IDE, please click on
the following link: https://www.arduino.cc/en/Main/Software. Select which Operating System
you‘re using and download it. Then, simply follow the installation wizard to install the Arduino
IDE.

When you first open the Arduino IDE, you should see something similar to the figure below:

Connecting your Arduino


Connect your Arduino UNO to your computer via USB.

10
After connecting your Arduino with a USB cable, you need to make sure that the Arduino IDE
has selected the right board.

In our case, we‘re using Arduino Uno, so we should go to Tools Board: Arduino/Genuino
Uno.

Then, you should select the serial port where your Arduino is connected to. Go to Tools Port
and select the right port.

Uploading an Arduino Sketch


To show you how to upload code to your Arduino board, we‘ll show you a simple example.
This is one of the most basic examples – it consists in blinking the on-board LED or digital pin
13 every second.

1. Open your Arduino IDE.


11
2. Go to File Examples 01.Basics Blink

By default, the Arduino IDE comes pre-configured for the Arduino UNO. Click the Upload
button and wait a few seconds.

After a few seconds, you should see a Done uploading message.

12
This code simply blinks the on-board LED on your Arduino UNO (highlighted with red color).
You should see the little LED turn on for one second, and turn off for another second
repeatedly.

Control an Output and Read an Input


An Arduino board contains digital pins, analog pins and PWM pins.

Difference between digital, analog and PWM


In digital pins, you have just two possible states, which are on or off. These can also be referred
as High or Low, 1 or 0 and 5V or 0V.

For example, if an LED is on, then, its state is High or 1 or 5V. If it is off, you‘ll have Low, or 0
or 0V.

In analog pins, you have unlimited possible states between 0 and 1023. This allows you to
read sensor values. For example, with a light sensor, if it is very dark, you‘ll read 1023, if it is
very bright you‘ll read 0 If there is a brightness between dark and very bright you‘ll read a
value between 0 and 1023.

PWM pins are digital pins, so they output either 0 or 5V. However these pins can output ―fake‖
intermediate voltage values between 0 and 5V, because they can perform ―Pulse Width
Modulation‖ (PWM). PWM allows to ―simulate‖ varying levels of power by oscillating the
output voltage of the Arduino.

13
Controlling an output
To control a digital output you use the digitalWrite() function and between brackets you write,
the pin you want to control, and then HIGH or LOW.

To control a PWM pin you use the analogWrite() function and between brackets you write the
pin you want to control and a number between 0 and 255.

Reading an input
To read an analog input you use the function analogRead() and for a digital input you use
digitalRead().

The best way for you to learn Arduino is practising. So, choose a project and start building
something.

14
3.Blinking an LED
It is the simple basic project created using Arduino. LED (Light Emitting Diode) is an electronic
device, which emits light when the current passes through its terminals. LED's are used in
various applications. It is also used as an ON/OFF indicator in different electronic devices.
In this project, we will connect the LED to the digital pin on the Arduino board. The LED will
work as a simple light that can be turned ON and OFF for a specified duration.
Structure of LED
An LED is a two-terminal device. The two terminals are called as Cathode and Anode. It is
shown below:

The long terminal is called Anode, and the shorter terminal is called Cathode. Here, cathode is
the negative terminal and anode is the positive terminal.
Components of the project
The components used in the blinking of an LED are listed below:
o 1 x Arduino UNO board.
o We can use any version of the UNO board, such as UNO R3, etc.
o 1 x Breadboard
o 2 x Jump wires
o 1 x LED
o 1 x Resistor of 220 Ohm.
We can use a resistor of any value upto 470 Ohms. We can use other value of resistors as well,
depending on our circuit requirements. Usually, the value should not exceed the allowable
forward current.

15
Structure of the project
The structure clearly shows the pinout of the UNO board. It also displays the LED and resistance
connected to the board.
It is shown below:

Sketch
We need to install the Arduino IDE, to begin with the coding, which is already discussed.
Open the IDE and start with the coding, which is given below:

void setup ()
{
pinMode ( 8, OUTPUT); // to set the OUTPUT mode of pin number 8.
}
void loop ()
{
digitalWrite (8, HIGH);
delay(1000); // 1 second = 1 x 1000 milliseconds
digitalWrite (8, LOW);
delay(500); // 0.5 second = 0.5 x 1000 milliseconds
}
We can modify the delay duration according to our choice or as per the requirements.
Every statement of coding is explained in Arduino coding basics. You can open the URL for
clear understanding.
16
The sketch will be uploaded to the board after the correct compiling, as shown below:

We are required to click on the Verify button to compile the code.


The RX and TX LED on the board will light up after the successful uploading of the code.

Procedure
The procedure to join the components of the project is shown below:
o Attach an LED on the breadboard. We need to plug-in the two terminals of an LED into
the holes of the breadboard.
We can plug-in the LED anywhere on the breadboard.
o Connect the resistor in series with the LED, as shown below:

o Connect the left leg of the resistor (connected in series with red LED) to the digital output pin
of the UNO board, i.e., PIN 8.
o Connect the negative/shorter terminal (Cathode) of the LED to the GND pin of the UNO
board using the wire, as shown below:
17
Here, the orange wire is connected to the PIN 8, and the blue wire is connected to the GND.

The shorter terminal indicates the negative. So, we will connect the shorter terminal to the
Ground (GND).
o Connect the USB cable.
o Select the board and serial port in the Arduino IDE.
o Upload the sketch or code on the board.
o The LED will dim and light for the specified duration.

Important points
The important points to be considered in this project are listed below:
o The resistor must be connected in series with the LED.
The resistor prevents the excess current from reaching the LED. The excess current in the
connection can burn the LED. Hence, a resistor in series with the LED is used in the
connection.
o We can use any pin as the OUTPUT pin. For example, 8, 13, 7, 4, and 3. The other pins are
PWM and analog pins.
o One terminal of the LED is connected to the Ground while the other terminal is connected to
the digital pin. The digital pin has only two values 0 or 1.
o HIGH = 1
o LOW = 0
o Arduino UNO board is recommended for all basic projects because it is easy to
understand and implement. It is also the standard Arduino board from all types of boards used. It
supplies power and also acts as a serial port.

18
4.Blinking various LEDs using Arrays

It is the simple basic project created using Arduino. LED (Light Emitting Diode) is an electronic
device, which emits light when the current passes through its terminals. LED's are used in
various applications. It is also used as an ON/OFF indicator in different electronic devices.
In this project, we will connect the LED to the digital pin on the Arduino board. The LED will
work as a simple light that can be turned ON and OFF for a specified duration.
Structure of LED
We have already discussed how to blink a single LED in previous topic.
Here, we will discuss a project to blink five LEDs using array. All the five LEDs will light one
after the other.
Components of the project
The components used in the blinking of various LEDs in array are listed below:
o Arduino UNO board.
o Breadboard
o Jump wires
o 5 x Red LEDs
o 5 x Resistor of 220 Ohm.
We can use any color LED as per our choice.
Principle
We will connect the five LEDs to pins 13, 12, 8, 4, and 2 of the Arduino board. The required
resistance of the resistors is enough to light up an LED without damaging the board and other
components.
The LED arranged one after another will light up. We can also change or rearrange the LEDs
connected to the specified pin number on the board.
Structure of the project
We will connect the five LEDs to pins 13, 12, 8, 4, and 2 of the Arduino board. The required
resistance of the resistors is enough to light up an LED without damaging the board and other
components.
The LED arranged one after another will light up. We can also change or rearrange the LEDs
connected to the specified pin number on the board.
It is shown below:

19
Connection
The connection of the above project is discussed below:
o Connect the resistor of 220 Ohm in series with the five LEDs. Now connect it to the pin
number 13, 12, 8, 4, and 2 of the Arduino board.
o Connect the negative terminal of the five LEDs to the GND (Ground).
Sketch
We need to install the Arduino IDE, to begin with the coding, which is already discussed.
Open the IDE and start with the coding, which is given below:

int timer = 500;


int LEDPins[] = {13, 12, 8, 4, 2}; // an array of declared pin numbers on the board
int countOFpin = 6; // the number of arrays
void setup()
{
// we have declared an array to intialize the LED pins as OUTPUT
for (int PIN = 0; PIN < countOFpin; PIN= PIN + 1)
{
pinMode(LEDPins[PIN], OUTPUT);
}
}
void loop()
{
// loop starting from the lowest pin in the array to the highest:
for (int PIN = 0; PIN < countOFpin; PIN++) {
20
// turns the pin ON:
digitalWrite(LEDPins[PIN], HIGH);
delay(timer);
// turnS the pin OFF:
digitalWrite(LEDPins[PIN], LOW);
}
// loop from the highest pin in the array to the lowest:
// It means the LEDs will light in the reverse direction as used above
for (int PIN = countOFpin - 1; PIN >= 0; PIN- -)
{
digitalWrite(LEDPins[PIN], HIGH);
delay(timer);
digitalWrite(LEDPins[PIN], LOW);
// We can also specify the time inside the delay( ) instead of the delcaring the timer
}
}
Connection Diagram

21
5.LED Fading using Arduino PWM

Pulse Width Modulation (PWM) is a technique by which width of a pulse is varied while keeping
the frequency of the wave constant. It is a method for generating an analog signal using a digital
source.
PWM Generation

A PWM signal consists of two main components that define its behaviour: a duty cycle and a
frequency.
What is the Duty Cycle of Signal?
o A period of a pulse consists of an ON cycle (5V) and an OFF cycle (0V).
o The fraction for which the signal is ON over a period is known as a duty cycle.
Duty Cycle Formula

A pulse with a period of 10ms will remain ON (high) for 2ms.


Therefore, duty cycle will be D = 2ms / 10ms = 20%
o Through PWM technique, we can control the power delivered to the load by using ON-
OFF signal.
o The PWM signals can be used to control the speed of DC motors and to change the
intensity of the LED.

22
Pulse Width Modulated signals with different duty cycle are shown below

Frequency of Signal
The frequency of a signal determines how fast the PWM completes a cycle (i.e. 1000 Hz would
be 1000 cycles per second) which means how fast it switches between ON (high) and OFF (low)
states. By repeating this ON-OFF pattern at a fast-enough rate, and with a certain duty cycle, the
output will appear to behave like a constant voltage analog signal when providing power to
devices.
Example: If we want to create a 2V analog signal for a given digital source that can be either
high (on) at 5V, or low (off) at 0V, we can use PWM with a duty cycle of 40%. It will provide
output 5V for 40% of the time. If the digital signal is cycled fast enough, then the voltage seen at
the output appears to be the average voltage. If the digital low is 0V (which is usually the case)
then the average voltage can be calculated by taking the digital high voltage multiplied by the
duty cycle, or 5V x 0.4 = 2V.

23
Now, let's see PWM in Arduino.
PWM Pins of Arduino Uno
Arduino Uno has 6 8-bit PWM channels. The pins with symbol ‗~‘ represents that it has PWM
support. These PWM pins are shown in below image.

Arduino Functions for PWM


analogWrite (pin, duty cycle)
o It is used to generate PWM or output analog value to a specified PWM channel.
o pin – pin on which we want to generate pwm or analog signal.
o duty cycle – it lies in between 0 (0%, always off) – 255 (100%, always on).
o e.g. analogWrite (3, 127) //generates pwm of 50% duty cycle

Components of the project


The components used in the blinking of various LEDs in array are listed below:
o Arduino UNO board.
o Breadboard
o Jump wires
o 1 x Red LEDs
o 1 x Resistor of 330 Ohm.

24
Sketch
Open the IDE and start with the coding, which is given below:
int led = 6; // the PWM pin the LED is attached to
int brightness = 0; // how bright the LED is
int fadeAmount = 5; // how many points to fade the LED by

void setup() {
pinMode(led, OUTPUT); // declare pwm pin to be an output:
}

void loop() {
analogWrite(led, brightness); // set the brightness of led

// change the brightness for next time through the loop:


brightness = brightness + fadeAmount;

// reverse the direction of the fading at the ends of the fade:


if (brightness <= 0 || brightness >= 255) {
fadeAmount = -fadeAmount;
}
delay(30); // wait for 30 milliseconds to see the dimming effect
}

Connection Diagram

25
6.LED Brightness Control Using a
Potentiometer

In this project, you‘ll create a dimmer switch by adding a potentiometer to control the brightness
of an LED.
Components of the project
The components used in the blinking of various LEDs in array are listed below:
o Arduino UNO board.
o Breadboard
o Jump wires
o 50k-ohm potentiometer
o Resistor of 470 Ohm.
o LED

Principle
A potentiometer is a variable resistor with a knob that allows you to alter the resistance of the
potentiometer as you turn it. It is commonly used in electrical devices such as volume controls on
audio equipment. This project uses a 50k-ohm potentiometer.

Structure of the project


The potentiometer manipulates a continuous analog signal, which represents physical
measurements. Humans perceive the world in analog; everything we see and hear is a continuous
transmission of information to our senses. This continuous stream is what defines analog data.
Digital information, on the other hand, estimates analog data using only numbers. To
approximate the continuous analog data from the potentiometer, the Arduino must represent the
signal as a series of discrete numbers—in this case, voltages. The center pin of the potentiometer
sends the signal to an Arduino analog IN—any pin from A0 to A5—to read the value.
The LED is actually being switched on and off, but it happens so quickly that our eyes
compensate and we see a continuously lit LED at varying light levels. This is known as
persistence of vision. To create persistence of vision, the Arduino uses a technique called pulse
width modulation (PWM). The Arduino creates a pulse by switching the power on and off very
quickly. The duration that the power is on or off (known as the pulse width) in the cycle
determines the average output, and by varying this pulse width the pattern can simulate voltages
between full on (5 volts) and off (0 volts). If the signal from the Arduino is on for half the time
and off for half, the average output will be 2.5 volts, halfway between 0 and 5. If the signal is on
for 80 percent and off for 20 percent, then the average voltage is 4 volts, and so on.
You can vary the signal, which in turn varies the pulse width, by turning the potentiometer left or
right, increasing or decreasing the resistance. Using this technique, you can change the voltage

26
sent to the LED and make it dimmer or brighter to match the analog signal from the
potentiometer. Only pins 3, 5, 6, 9, 10, or 11 on the Arduino can use PWM.

Connection Diagram

27
Sketch
This sketch works by setting pin A0 as your potentiometer and pin 9 as an OUTPUT to power the
LED. You then run a loop that continually reads the value from the potentiometer and sends that
value as voltage to the LED. The voltage value is between 0–5 volts, and the brightness of the
LED will vary accordingly. Upload the code in ―The Sketch‖ below. Turn the potentiometer to
control the brightness of the LED.
int potPin = A0; // Analog input pin connected to the potentiometer
int potValue = 0; // Value that will be read from the potentiometer
int led = 9; // Pin 9 (connected to the LED) is capable of PWM
// Runs once at beginning of the program
void setup() {
pinMode(led, OUTPUT); // Set pin 9 to output
}
// Loops continuously
void loop() {
potValue = analogRead(potPin); // Read potentiometer value
// from A0 pin
analogWrite(led, potValue/4); // Send potentiometer value to LED
// to control brightness with PWM
delay(10); // Wait for 10 ms
}
Video Link: https://youtu.be/bahSzV1EYwE

28
7.LED Brightness Control Using a
LDR

Arduino LDR (Light Dependent Resistor) project uses the photoresistor to light an LED. The
LED will light up whenever there is dark or no light over the sensor.
What is photoresistor?
It is defined as a light-controlled resistor, which is also called as LDR. It is a variable resistor that
controls the resistance in accordance with the received light intensity. It means, the resistance
decreases as intensity of light increases.
Components of the project
The components used in the blinking of various LEDs in array are listed below:
o Arduino UNO board.
o Breadboard
o Jump wires
o 1 x Red LED
o 1 x Resistor of 220 Ohm
o 1 x Resistor of 10K Ohm
o 1 x Photoresistor
Principle
We will connect the five LEDs to pins 13, 12, 8, 4, and 2 of the Arduino board. The required
resistance of the resistors is enough to light up an LED without damaging the board and other
components.
The LED arranged one after another will light up. We can also change or rearrange the LEDs
connected to the specified pin number on the board.
How to calculate the output voltage using photoresistor?
The structure of photoresistor is shown below:

The formula to calculate the dark output voltage is given below:

29
where,
o Vin = 5V
o Vout = Output voltage
o Here, R2 is the resistance connected in series with the photoresistor = 10K Ohm.
o R1 is the resistance of the photoresistor.
Connection

The connection of the above project is discussed below:


o Connect the positive leg of the LED in series with the resistor to the pin number 12 of the
Arduino board.
o Connect the negative leg of the LED to the Ground.
o Connect one edge of the photoresistor to the 5V pin on the Arduino board.

30
o Attach a 10K ohm resistance in series with another edge of the photoresistor and connect
it to the GND.
o Connect the edge of the photoresistor to the analog pin A0.
Sketch
Open the IDE and start with the coding, which is given below:

const int LEDpin = 12;


const int photoPIN = A0;

void setup() {
// initializing the serial communication:
Serial.begin(9600);
pinMode(photoPIN, INPUT);
pinMode(LEDpin, OUTPUT);
}
void loop() {
// read the sensor:
int sensorStatus = analogRead(photoPIN);
// now, it will check the reading or status of the sensor is < 200
// if it is, LED will be HIGH
if (sensorStatus <200)
{
digitalWrite(LEDpin, HIGH); // LED is ON
Serial.println(" LED is ON, status of sensor is DARK");
}
else
{
digitalWrite(LEDpin, LOW);
Serial.println(" ***************");
}
}

31
Connection Diagram

Output
The output on the serial monitor will appear as:

LED is one because there is dark over the sensor.

32
8.Arduino Accelerometer
This project shows you how to read from the ADXL3xx series (e.g. ADXL320, ADXL321,
ADXL322, ADXL330) accelerometer and receive the values in the serial monitor of the Arduino
Software (IDE) or another application that receives data over the serial port.
What is accelerometer?
The accelerometer is the device capable of detecting changes in motion in the form of
acceleration. It can also measure the vibration of a structure. The acceleration is defined as the
change in speed or velocity over time. The motion sensors are present inside the accelerometer.
How does accelerometer work?
The acceleration (change in motion) or the vibration generates the force that causes the
piezoelectric material to be stressed. The microscopic crystal structure present in it creates the
voltage from the stress. The accelerometer interprets this voltage. The voltage is further used to
determine the orientation and velocity.
Usage of Accelerometer
The uses of the accelerometer are listed below:
o It is used to detect earthquakes due to the presence of a motion sensor.
o It is present on the laptop, which protects the hard drives from damage.
o It is used to create custom projects.
o It can determine the movements (uphill, etc.) of the object.
ADXL335 Accelerometer
The structure of ADXL335 is shown below:

The position of the three axis (X-axis, Y-axis, and Z-axis) will change according to the
ADXL335 accelerometer's position. If we hold the board in a different position, the direction of
the three-axis will also change. Moving the board in a particular direction will cause a change in
the voltage of the respective axis. We can measure the changed voltage on the Arduino.

When we hold the board up and flat, the measured acceleration of 9.8m/s^2 will appear on the Z-
axis. It is also called as the gravity. Here, 1.0G = of 9.8m/s^2
33
where, G is the acceleration due to earth gravity. The sensitivity of ADXL335 accelerometer is:

s = 0.33V/G. Gravity force per ADC (Analog to Digital Converter) unit is:

It is because the sensors need 3.3V to operate. The accelerometer at rest will read half of its
maximum analog voltage.
Components of the project
The components used in the blinking of various LEDs in array are listed below:
o Arduino UNO board.
o Breadboard
o Jump wires
o 1 x ADXL335 accelerometer

Principle
We can directly plugged-in the accelerometer onto the Arduino. It is because the accelerometer
operates on minimal current. The Arduino UNO has six analog pins. The three analog pins will
be connected to the Vcc, Self-Test, and the Ground pin. The other three analog pins will be used
to read the analog output of the accelerometer.

34
Connection

The connection of the above project is discussed below:


o Connect X of the accelerometer to the analog pin A3 of the Arduino board.
o Connect Y of the accelerometer to the analog pin A2 of the Arduino board.
o Connect X of the accelerometer to analog pin A1 of the Arduino board.
o Connect Vcc of the accelerometer to analog pin A5 of the Arduino board.
o Connect GND of the accelerometer to analog pin A4 of the Arduino board.
o Connect ST of the accelerometer to analog pin Ao of the Arduino board.

35
Sketch
Upload the code on the Arduino connected with the accelerometer. The output can be clearly
seen on the Serial Monitor in the Arduino IDE. Open the IDE and start with the coding, which is
given below:

const int GND = A4;


const int PowerPIN = A5;
const int pinOfX = A3;
const int pinOfY= A2;
const int pinOfZ= A1;
void setup()
{
Serial.begin(9600);
pinMode(GND , OUTPUT);
pinMode(PowerPIN , OUTPUT);
digitalWrite(GND , LOW); // configuring the GND pin as LOW
digitalWrite(PowerPIN , HIGH); // configuring the power pin HIGH (5V/3.3V)
}
void loop()
{
// It prints the values of the sensors
Serial.print(analogRead(pinOfX)); // print a tab between values:
Serial.print("\t");
Serial.print(analogRead(pinOfY));
Serial.print("\t");
Serial.print(analogRead(pinOfZ));
Serial.println(); // It delays before next reading
delay(100);
}

36
Connection Diagram

Output
Data
Here are some accelerometer readings collected by positioning the y-axis of an ADXL322 2g
accelerometer at various angles from ground. Values should be the same for the other axes, but
will vary based on the sensitivity of the device. With the axis horizontal (i.e. parallel to ground or
0°), the accelerometer reading should be around 512, but values at other angles will be different
for a different accelerometer (e.g. the ADXL302 5g one).

Angle: -90 -80 -70 -60 -50 -40 -30 -20 -10 0
Acceleration: 662 660 654 642 628 610 589 563 537 510

Angle: 0 10 20 30 40 50 60 70 80 90
Acceleration: 510 485 455 433 408 390 374 363 357 355

37
9.Arduino Communication Protocols
Communication protocols is the set of rules that allows devices to communicate and exchange
data. These protocols are very significant in Arduino communication as Arduino constantly sends
and receives data. Using these protocols help Arduino to cover error detection and possible error
recovery methods. These protocols bring analog and digital devices together and make it possible
to design multiple projects.
Arduino Communication Protocols
By using Communication protocols, we can send and receive any sensor‘s data in Arduino. Some
simple sensors like Infrared (IR) can directly communicate with Arduino but some of the
complex sensors like Wi-Fi module, SD card module and Gyroscope cannot communicate
directly with Arduino without any communication protocols. So, that is why these protocols are
an integral part of Arduino communication.
Arduino have multiple peripherals attached to it; among them there are three communication
peripherals used in Arduino boards.
o UART
o SPI
o I2C

38
Arduino Communication Protocols
Communication among different electronic devices like Arduino is standardized among these
three protocols; it enables designers to communicate between different devices easily without any
compatibility issues. Working of these three protocols are the same as they serve the same
purpose of communication, but they differ in implementation inside a circuit. Further description
of these protocols are discussed below.
UART
UART is known as the Universal Asynchronous Receiver Transmitter. UART is a serial
communication protocol which means data bits are transferred in sequential form one after the
other. For setting up UART communication we need two lines. One is the Tx (D1) pin of the
Arduino board and the second one is the Rx(D0) pin of the Arduino board. Tx pin is for
transmitting data to devices and Rx pin is used for receiving data. Different Arduino boards have
multiple UART pins.
Arduino Digital Pin UART Pin
D1 Tx
D0 Rx

To establish Serial communication using UART port we need to connect two devices in below
shown configuration:

On Arduino Uno, one serial port is dedicated for communication which is commonly referred to
as USB port. As the name suggests Universal Serial Bus, so it is a serial port. Using the USB port
Arduino can establish communication with computers. The USB port is connected to onboard
pins Tx and Rx of Arduino. Using these pins, we can connect any external hardware other than
Computer through USB. Arduino IDE provides SoftwareSerial library (SoftwareSerial.h) which
allows users to use GPIO pins as Serial Tx and Rx pins.
o UART is simple to operate with Arduino
o UART doesn‘t need any clock signal
o Baud rate must be set within 10% limit of communicating devices to prevent data loss
o Multiple devices with Arduino in Master Slave configuration are not possible with UART
o UART is half duplex, which means devices cannot transmit and receive data at the same
time
o Only two devices at a time can communicate with UART protocol
Serial Peripheral Interface (SPI)

39
SPI is an acronym of serial peripheral interface that is specially designed for microcontrollers to
communicate with them. SPI operates on full-duplex mode which means SPI can send and
receive data simultaneously. When compared with UART and I2C it is the fastest communication
peripheral in Arduino boards. It is commonly used where high data rate is required like in LCD
display and Micro SD card applications.
SPI digital pins on Arduino are predefined. For Arduino Uno SPI pin configuration is as follows:
SPI Line GPIO ICSP Header Pin
SCK 13 3
MISO 12 1
MOSI 11 4
SS 10 -

o MOSI stands for Master Out Slave In, MOSI is Data transmission line for Master to
Slave.
o SCK is a Clock line which defines transmission speed and start end characteristics.
o SS stands for Slave Select; SS line allow Master to select a particular Slave device when
operating in multiple Slave configuration.
o MISO stands for Master in Slave Out; MISO is Slave to Master transmission line for
Data.

One of the main highlights of SPI protocol is Master-Slave configuration. Using SPI one device
can be defined as Master to control several Slave devices. Master is in full control of Slave
devices through SPI protocol.

SPI is synchronous protocol, which means communication is linked with common clock signal
between Master and Slave. SPI can control multiple devices as Slave over a single transmit and
receive line. All the Slaves are connected to Master using common MISO receive line along with
MOSI one common transmit line. SCK is also the common clock line among Master and Slave
devices. Only difference in Slave devices is each slave device is controlled through separate SS
select line. This means that each Slave need an extra GPIO pin from Arduino board which will
act as select line for that particular Slave device.

40
Some of the main highlights of SPI protocol is listed below:
o SPI is fastest protocol than I2C and UART
o No start and stop bits required like in UART which means continuous data transmission is
possible
o Slave can be easily addressed due to simple Master Slave configuration
o For each Slave an extra pin is occupied on Arduino board. Practically 1 Master can
control 4 Slave devices
o Data acknowledgment is missing like used in UART
o Multiple Master configuration is not possible
I2C Communication Protocol
Inter Integrated Circuit (I2C) is another communication protocol used by Arduino boards. I2C is
the most difficult and complicated protocol to implement with Arduino and other devices.
Despite of its complication it‘s offer multiple features that are missing in other protocols like
multiple Master and multiple Slaves configurations. I2C allows connecting up to 128 devices to
the main Arduino board. This is only possible because I2C share single wire among all the Slave
devices. I2C in Arduino uses an address system, meaning before sending data to Slave device
Arduino must first select Slave device by sending unique address. I2C uses only two wires
reducing overall Arduino pin count, but the bad side to it is I2C is slower than SPI protocol.
Arduino Analog Pin I2C Pin
A4 SDA
A5 SCL

At hardware level I2C is limited to only two wires, one for a data line known as SDA (Serial
Data) and second one for Clock line SCL (Serial Clock). At idle state both SDA and SCL are
pulled high. When data needs to be transmitted these lines are pulled low using MOSFET
circuitry. Using I2C in projects it is mandatory to use pull up resistors normally a value of
4.7Kohm. These pull up resistors ensure that both SDA and SCL lines remain high in their idle
start.
Some of the main highlights of I2C protocols are:
o Number of pins required are very low
o Multiple Master Slaves devices can be connected
o Only uses 2 wires
o Speed is slower as compared to SPI due to pull up resistors
o Resistors need more space in circuit
o Complexity of project increase with increase in number of devices

41
Comparison between UART vs I2C vs SPI

Protocol UART SPI I2C

Speed Slowest Fastest Faster than UART

Number of devices Up to 2 4 devices Up to 128 devices


4 (SCK, MOSI,
Wires required 2 (Tx, Rx) MISO,SS) 2 (SDA, SCL)

Duplex Mode Full Duplex Mode Full Duplex Mode Half Duplex

Number of Master- Single Master-Single Single Master-Multiple Multiple Masters-


Slaves possible Slave Slaves Multiple Slaves

Can easily control Complex with


Complexity Simple multiple devices increase in devices

Acknowledgment bit No No Yes

42
10.Serial UART Communication
between Two Arduino Boards
Now, we will connect two Arduino boards using Tx and Rx pins to establish a serial
communication between them one Arduino board which will transmit data will act as a Master
and the second Arduino board which will receive instructions will act as Slave. We will setup our
Arduino boards in Master and Slave configuration. Before going further, we need the following
equipment to start our UART serial communication.
Components of the project
The components used in the blinking of various LEDs in array are listed below:
o 2x Arduino Boards
o 2x USB B cable
o 6x Jumper wires
o Breadboard
o Resistor 220 Ohm
o LED
Principle
To start communication between two Arduino boards, one will be configured as Sender and other
Arduino board as the receiver. So, we must write two programs, one for sender and second for
receiver. Follow the below mentioned steps to establish serial communication.
Example 1: Passing a String from One Arduino to Other through UART Communication
We will define a string in our Master Arduino and will try to pass it to Slave Arduino using
UART serial communication. Follow below given steps to pass data between two Arduinos.
Step 1: Connect Master Arduino
Using a USB B cable connects the Arduino board which is acting as Master to the PC.
Remember to select the COM port first before uploading the sketch. Here in our case the Arduino
is connected at COM6 port.

43
Now upload below code to the sender Master Arduino board.
Sketch 1
/Sender Arduino Board Code (Master)
char mystring[15] = "LinuxHint.com "; //String data which is to be sent
void setup() {
Serial.begin(9600); // Begin the Serial at 9600 Baud rate
}
void loop() {
Serial.write(mystring,15); //Write the serial data
delay(1000);
}

Above code will send a simple message LinuxHint.com to the other Arduino. First, we have
defined an array ―LinuxHint.com‖. The number 15 inside brackets shows that this array can hold
15 characters. 13 are alphabets while 2 are set for space so that we can see clear output in the
serial monitor. Inside setup() serial communication is established using Serial.begin() and 9600 is
selected as baud rate.
The loop() section of the sketch contains the Serial.write() function. These functions will write a
message to the receiver Slave Arduino board with 1000 milliseconds delay.
Step 2: Connect Slave Arduino
Connect the second Arduino board which is Slave in our configuration. Connect this board at any
PC port other than the port used in the previous step by the Master Arduino board. Before
uploading the Arduino code select Arduino COM port. Our Slave Arduino board is connected at
COM8.

Now upload below given code in Slave Arduino board.

44
Sketch 2:
//Receiver Arduino Board Code
char mystring[20]; //Initialized variable to store receive
void setup() {
Serial.begin(9600); // Begin the Serial at 9600 Baud
}
void loop() {
Serial.readBytes(mystring,15); //Read the serial data
Serial.println(mystring); //Print data on Serial Monitor
Serial.println(" RECEIVER");
delay(1000);
}
Above code of Slave Arduino is similar like Master Arduino only difference is here instead of
Serial.write() we have used Serial.readBytes() which will read incoming data from Master
Arduino. After reading data I will be printed on the serial monitor using Serial.println() function.
Step 3: Connect Both Arduino Using TX and Rx Pins
Once Arduino code is uploaded in both Arduino boards now connect Master and Slave Arduino
board as shown in figure below. Connect Tx pin of first Arduino with Rx pin of second Arduino
similarly Rx pin of first Arduino with Tx pin of second Arduino.
Remember while uploading code in both these Arduino do not connect Tx and Rx pins otherwise
serial communication will not be possible.

Connection:

45
Output of Master Arduino:
Master Arduino is sending a string constantly to Slave Arduino with a delay of 1000
milliseconds.

Output of Slave Arduino:


Slave Arduino will first print RECEIVER in output serial terminal after that it will receive an
array LinuxHint.com with a delay of 1000 milliseconds from Master Arduino. Hence serial
communication is done between two Arduino boards.

46
Example 2: Blink LED Using Two Arduino Boards through UART Communication
Step 1: Upload Code to Master Arduino Board
Connect the Arduino board which is acting as Master with the PC using USB B cable and select
the COM port at which Arduino is connected. In our case the Master Arduino board is connected
at the COM7 port.

Upload the given code below in the Sender Arduino board.

Sketch: //Transmitter (Tx) Arduino Board Code

void setup()

Serial.begin(9600);

void loop()

Serial.print(1);

delay(2000);

Serial.print(0);

delay(2000);

In above code Master Arduino is sending instructions to Slave Arduino in the form of numbers 1
and 0. Master sends number 1 then waits for 2 seconds after that it sends number 0 then again

47
goes for a delay of 2 seconds. After that it starts repeating in a loop. Here we have used
the Serial.print() function which will convert Master Arduino instructions into ASCII characters
which means master will transmit values 49 for 1 and 48 for 0.

Step 2: Upload Code to Slave Arduino Board


Now Connect second Arduino board which is acting as Slave with any other port of PC using
USB B cable. Remember to select the Arduino board COM port first before uploading sender
code. Slave Arduino board is connected at COM8 port of PC.

Now upload the below code in second Arduino board which is acting as slave.

Sketch: //Receiver (Rx) Arduino Board Code

char serialinput = ' ';


byte LED = 2;
void setup()
{
pinMode(LED, OUTPUT);
Serial.begin(9600);
}
void loop()
{
if(Serial.available())
{
char serialinput = Serial.read();
if (serialinput =='0') { digitalWrite(LED, LOW); }
if (serialinput =='1') { digitalWrite(LED, HIGH); }
Serial.println(serialinput);
}
}

48
In above code of Slave Arduino char serial input is initialized which will receive and store
instructions coming from Master Arduino.After that in the loop section of code a check will be
made using if condition.

if(Serial.available())

Above command will check whether there is any data coming in the buffer or not.

If there is any data coming a single character is read and stored in char variable serialinput.
Since we are interested in 0 and 1 values only. If statements will do the work here. If statements
will check the serialinput value if it is 1 it will send high signal to LED connected at pin 2 of
Slave board. If it received serialinput 0 it will send a Low signal to pin number 2.
Note: Always connect both Arduino boards at separate COM ports and before uploading new
code select Arduino COM port first. It‘s recommended to use two separate windows of IDE for
both Arduino boards.

Step 2: Upload Code to Slave Arduino Board


Connect Arduino boards in below configuration as shown in picture. Connect Tx of the first
Arduino with Rx of the second Arduino. Similarly connect the Rx of first Arduino with the Tx of
second Arduino. Don‘t connect Tx and Rx pins before uploading Arduino code as Arduino has
only one serial communication port connecting these two ports with any other device will block
serial communication with PC through USB cable. Connect LED at digital pin number 2 and
GND pin of Arduino, in between these two pins connect a 220ohm resistor to maintain safe
current limits. Connect Arduino GND together.

Connection:

49
Output LED Blinking
After uploading code in both Arduino boards. Master will send instructions on and off with a
delay of 2000ms. In output we can see an LED blinking consecutively in 1 sec on and 1 sec off
configuration.

LED Turn On

LED Turn Off

50
11.I2C Communication Protocol
In this project, we are going to have an overview on the I2C protocol and the Arduino library
―wire‖ which is the specific library for I2C protocol. A circuit containing two Arduino Boards
along with two LEDs and two potentiometers are used to explain about the I2C protocol and to
see the results in practice.

Using the potentiometer of the master Arduino board, we will control the LED connected to the
slave Arduino board, and vice versa. Meaning that we will control the output of the slave using
the input of the master, and also control the output of the master using the input of the slave. The
transmitted data will also be displayed on the Serial Monitor.

The most important features of the I2C communication protocol are the following:

o It‘s not so fast (But fast enough for most applications)


o Suitable for short distances (e.g. maximum distance in 100KHz frequency is 1 meter)
o Synchronous communication
o Data is transmitted serially
o Logic level can be 3.3V or 5V

There are two types of devices that connect to the I2C bus in the I2C protocol: The master and
the slave. In this protocol, multiple slaves can be connected to a single master, like a
microcontroller. And also, a single slave can be controlled and monitored by multiple masters,
but only one of the masters can be active at a time.

Each master can select which slave to communicate with. The selection is done using the slave‘s
7-bit addresses (10-bit in some cases). So, there can be approximately 128 slave devices
connected to the I2C bus. So, in other words, each slave has its own specific I2C address and
there is no address for the masters.

51
The data transmitted in the I2C bus is synchronized by clock line, SCL. The master is responsible
for the synchronization.

The “Wire” Library

To work with the I2C protocol, we use the ―Wire‖ library, which is one of the Arduino IDE
libraries. Working with the I2C communication protocol would be so easy using this library. This
library has a lot of useful functions, including:

o begin(): Using this function, you can determine the Arduino board to be the master or the
slave.
o requestFrom(): this function is used on the master side and can be used to request data
transmission from the slave. The number of bytes and also the slave address are specified
in this function.
o beginTransmission(): This function which is used by the master starts the communication
with a special slave using its address.
o endTransmission(): The communication started by the previous function ends using this
function.
o write(): Both the master and the slave use this function to send data to the I2C bus.
o available(): Both the master and the slave use this function to calculate the number of
bytes received (by the ―read()‖ function)
o read(): The function for reading a byte of data from the I2C bus. (used by Both the master
and the slave)
o setClock(): This is used by the master to set the clock frequency.
o onReceive(): This is defined as a function by the slave and is called when data is received
from the master.
o onRequest(): This is defined as a function by the slave and is called when data is
requested by the master.

Hardware Components

o Arduino UNO R3 ×2
o BreadBoard × 2
o 5K Ohm Volume Potentiometer ×2
o 5mm Red LED × 1
o 330 Ohm Resistor × 2
o 10CM Male-Male Jumper Wires × 1
o 20CM Male-Male Jumper Wires ×1

52
Procedure:

Connect Two Arduino Boards, One of Them as the Master and the Other as the Slave. Now, we
have reached the main part of the tutorial and are going to establish a communication between
two Arduino Boards through I2C protocol. One of the Arduino Boards acts as the master and the
other as the slave. First, its practical circuit is made. Then, we will explain its program and after
uploading the programs on the two Arduino boards, we can see the results.

Step 1: Circuit

The following circuit shows how you should connect the two Arduino boards to other
components:

As you can see in the image above, the communication between the Arduino Boards is only
through the I2C bus. The Arduino Board on the left is the master and the one on the right is the
slave. Each Arduino Board has a potentiometer and an LED connected to it. We will control each
LED using the Arduino Board on the other side.

Step 2: The Code of the Master Side

Once you have prepared the circuit, you should upload the codes of the master and the slave on
their Arduino Boards. First, upload the following code on the Arduino acting as the master:

53
Sketch:

#include <Wire.h>
int value = 0;
void setup() {
Wire.begin(); // join i2c bus (address optional for master)
Serial.begin(9600);
pinMode(5, OUTPUT);
}
void loop() {
int y = analogRead(A1); //Read from A1 & Save to value
value = map(y, 0, 1023, 0, 255);
Wire.beginTransmission(8); // transmit to device #8
Wire.write("Master value : "); // sends these bytes
Wire.write(value); // sends one byte
Wire.endTransmission(); // stop transmitting
Wire.requestFrom(8, 1); // request 1 byte from slave device #8
while (Wire.available()) { // slave may send less than requested
int c = Wire.read(); // receive a byte as character
analogWrite(5, c);
Serial.print("Slave value : ");
Serial.println(c); // print the character
}
delay(100);
}

We want to send the value of the potentiometer on the master side to the slave and receive a byte
of the potentiometer data by the slave, display it on the Serial Monitor and control the brightness
of the LED with it.

The following points are worth mentioning regarding the code above:

o First, we include the ―Wire‖ library.


o We start working with library using the ―begin()‖ function.
o In the main loop, the analog input is stored in the variable ―value‖ and converted to the
range of 0-255.
o Then, using the function ―beginTransmission(8)‖, the address of the slave is entered and
I2C communication is started for data transfer.
o Then, using the function ―write()‖, some characters containing some letters signs are sent,
and then, a byte of the actual data is sent.
o Finally, the transmission of data is ended using the command line ―endTransmission()‖.
o In the next step, the master requests to receive one byte of data from the slave that has the
address ―8‖. This can be done using the command line ―requestFrom(8,1)‖. After that, we
store the data received from the slave–this data is in the range 0-255- and control the LED
brightness with it. This value is also displayed on the Serial Monitor.

54
Step 3: The Code of the Slave Side

Now, upload the following code on the Arduino acting as the slave:

Sketch:
#include <Wire.h>
int x;
int value=0;
void setup() {
Wire.begin(8); // join i2c bus with address #8
Wire.onRequest(requestEvent); // register event
Wire.onReceive(receiveEvent); // register event
Serial.begin(9600); // start serial for output
pinMode(9,OUTPUT);
}
void loop() {
delay(100);
analogWrite(9,x);
int t=analogRead(A0); //Read from A0 & Save to value
value=map(t,0,1023,0,255);
}
// function that executes whenever data is received from master
void receiveEvent() {
while (1 < Wire.available()) { // loop through all but the last
char c = Wire.read(); // receive byte as a character
Serial.print(c); // print the character
}
x = Wire.read(); // receive byte as an integer
Serial.println(x); // print the integer
}
// function that executes whenever data is requested by master
void requestEvent() {
Wire.write(value); // respond with message of 1 byte
// as expected by master
}

We want to send the potentiometer value of the slave to the master and receive the data sent from
the master. And then, display it on the Serial Monitor and control the LED brightness with it.

The following points are worth mentioning regarding the code above:

o First, we include the ―Wire‖ library.


o We start working with the library using the ―begin(8)‖ function. The slave address is
determined here.
o The functions ―onRequest‖ and ―onReceive‖ are used to request sending data and
receiving data, respectively. We will also explain the inside of each functions in the
following.
o The ―receiveEvent()‖ function: Using this function, the data sent from the master is
received. First, in the while loop, all bytes except for the last one are received. These
55
bytes are the characters of the phrase ―Master value:‖. After the while loop, the last byte,
which is the value of the potentiometer on the master side, is received and stored in the
variable ―x‖.
o requestEvent(): When the master requests for data, the slave sends the wanted data to the
master using this function and the ―write()‖ command line.
o Now, in the main loop, the value ―x‖ which is sent from the master is used to control the
brightness of the LED. In other words, by rotating the potentiometer on the master side,
the value of ―x‖ changes, and the brightness of the LED changes as the result.
o In the rest of the main loop, the value of the potentiometer is read, converted to a value
ranging 0-255, stored in the variable ―x‖ and prepare it to be sent to the master.

Step 4: Results

After successfully uploading the codes on both Arduino Boards, open the Serial Monitor of both
PORTS and see the changes of the values and the brightness of LEDs by rotating the
potentiometers. The result is similar to the following video:

https://electropeak.com/learn/wp-content/uploads/2021/08/20210608-Master-Slave-two-arduino-
i2c.mp4

In the video above, it can be seen that you can control the LED of the slave side by rotating the
potentiometer of the master side. The value can also be seen on the Serial Monitor of the slave
side. The same thing goes for the master, too. By rotating the potentiometer on the slave side, the
LED brightness on the master side and also the value displayed on the Serial Monitor changes.

56
12.SPI Communication Between
Two Arduinos
Now let‘s see how to perform SPI communication between two Arduino boards. We will
configure one Arduino as a master device and another Arduino board as a slave device. A master
device will transmit 1 if the user pressed the push button which is connected with the D2 of
Arduino. SPI Slave Arduino receives this data and based on received data make a decision to
turn-on or turn-off LED which is connected with the D4 pin of Arduino.
Hardware Components:
o Two Arduino UNO
o Two 5mm LEDs
o Two Pushbuttons
o Two 220 ohm resistors
o Two 10k ohm resistors
o Connecting Wires
o Breadboard
Connection Schematic:

In the above circuit diagram, for both the Master and the Slave, Arduino digital pin 4 is
connected with anode pin of LED through a 220 ohm current limiting resistor. The cathode pin is
grounded.
Next, the push button‘s one terminal is connected with 3.3 volts of Arduino and other terminals
of a push button is connected with Arduino digital pin 4 through 10k pull-down resistor. The
other end of the resistor is connected with a ground. When pushbutton is not pressed, logic low

57
will appear on pin 4 or push button state will be low and when the push button is pressed, a logic
high will be on pin 4.
To enable SPI communication between the two boards, connect the SPI pins of master Arduino
with the SPI pins of the slave Arduino.
Now let us understand the code of the Master device.
Arduino SPI Master Device Code
Sketch:
#include<SPI.h>
#define push 2
#define LED 4
int x;
int value;
void setup (void)
{
Serial.begin(115200);

pinMode(push,INPUT);
pinMode(LED,OUTPUT);

SPI.begin();
SPI.setClockDivider(SPI_CLOCK_DIV8);
digitalWrite(SS,HIGH);
}
void loop(void)
{
byte m_send,m_receive;

value = digitalRead(push);

if(value == HIGH)
{
x = 1;
}
else
{
x = 0;
}

digitalWrite(SS, LOW);

m_send = x;
m_receive=SPI.transfer(m_send);

if(m_receive == 1)
{
digitalWrite(LED,HIGH);
}
else
58
{
digitalWrite(LED,LOW);
}
delay(1000);
}
Arduino SPI Slave Device Code
#include<SPI.h>
#define inputbutton 2
#define outputLED 4

volatile boolean received;


volatile byte Slavereceived,Slavesend;
int buttonvalue;
int x;

void setup()

{
Serial.begin(115200);

pinMode(inputbutton,INPUT);
pinMode(outputLED,OUTPUT);
pinMode(MISO,OUTPUT);

SPCR |= _BV(SPE);
received = false;

SPI.attachInterrupt();

ISR (SPI_STC_vect)
{
Slavereceived = SPDR;
received = true;
}

void loop()
{
if(received)
{
if (Slavereceived==1)
{
digitalWrite(outputLED,HIGH);
}else
{
digitalWrite(outputLED,LOW);
}

buttonvalue = digitalRead(inputbutton);

59
if (buttonvalue == HIGH)
{
x=1;

}else
{
x=0;
}

Slavesend=x;
SPDR = Slavesend;
delay(1000);
}
}
Output
To see the demonstration of the above code, upload the master and slave code to the respective
Arduino boards. But, before uploading code, make sure to select the Arduino board from Tools >
Board and also select the correct COM port to which the Arduino board is connected from Tools
> Port.
Now press the pushbutton of master Arduino and the slave Arduino‘s LED turns ON. Likewise,
press the pushbutton of the slave Arduino and the master Arduino‘s LED turns ON.

https://youtu.be/p-Px2UN4onI
When button is pushed at Arduino 1, after some time (bear for some time) LED at Arduino 2 is
turned ON. This delay is due to limitations of simulation resources of Proteus and PC.
When button is pushed at Arduino 2, after some time (Have patience to observe result) LED at
Arduino 1 is turned ON. This delay is due to limitations of simulation resources of Proteus and
PC.

60
Arduino Based Projects
13.Project 1: Traffic Lights

Introduction
In this project you‘re going to build a traffic lights system:

o There are 3 LEDs with different colors (green, yellow and red) to mimic the traffic
lights for the cars
o There are 2 LEDs with different colors (green and red) to mimic the traffic lights for
the pedestrians
o There is a pushbutton to mimic the ones in the pedestrians traffic lights

Components of the project


o 1x Breadboard
o Arduino UNO – read Best Arduino Starter Kits
o 3x 5mm LED (1x red, 1x yellow, 1x green)
o 2x 3mm LED (1x red, 1x green)
o 5x 220Ohm Resistor
o 1x 10kOhm Resistor
o 1x pushbutton
o Jumper Wires

61
I‘m using LEDs of different sizes but if you don‘t have LEDs of different sizes, it is ok.
The project still works.

Schematics
Assemble all the parts by following the schematics below.

Code
You don‘t need any library for this code. The code is very simple. Here‘s some tips to better
understand what‘s going on.

• The car light is always green, and so the pedestrian light is always red unless
someone presses the button.
• When someone presses the button here‘s what happens:
• The car light changes to yellow and then to red
• The pedestrian light changes to green
• The lights are in this state for a while (in the code this time is the variable
crossTime)
• The pedestrian green light flashes and goes to red
62
• The car light changes from red to green

All these actions will be inside the function changeLights(). Everytime you want to change the
lights, you just need to call the changeLights() function.

Sketch
Copy the following code to your Arduino IDE, and upload it to your Arduino board.
Make sure you have the right board and COM port selected.

int redCar = 13;


int yellowCar = 12;
int greenCar = 11;
int greenPed = 2;
int redPed = 3;
int button = 7;
int crossTime = 2000;
unsigned long changeTime;
void setup() {
// initialize timer
changeTime = millis();
// here we are initializing our pins as outputs
pinMode(redCar, OUTPUT);
pinMode(yellowCar, OUTPUT);
pinMode(greenCar, OUTPUT);
pinMode(redPed, OUTPUT);
pinMode(greenPed, OUTPUT);
pinMode(button, INPUT);
//turn on the green light
digitalWrite(greenCar, HIGH);
digitalWrite(redPed, HIGH);
digitalWrite(redCar, LOW);
digitalWrite(yellowCar, LOW);
digitalWrite(greenPed, LOW);
Serial.begin(9600);
}
void loop() {
// this variable will tell us if the button is pressed
int state = digitalRead(button);
Serial.println(state);
// if the button is pressed and if it has passed 5 seconds since last button press
if (state == HIGH && (millis() - changeTime) > 5000) {
//call the function to change the lights
changeLights();
}
}
void changeLights() {
digitalWrite(greenCar, LOW); // the green LED will turn off
digitalWrite(yellowCar, HIGH); // the yellow LED will turn on for 2 second
delay(2000);
digitalWrite(yellowCar, LOW); // the yellow LED will turn off
63
digitalWrite(redCar, HIGH); // the red LED will turn on for 5 seconds
digitalWrite(redPed, LOW);
digitalWrite(greenPed, HIGH);
delay(crossTime);
// flash the ped green
for (int x=0; x<10; x++) {
digitalWrite(greenPed, LOW);
delay(100);
digitalWrite(greenPed, HIGH);
delay(100);
}
digitalWrite(greenPed, LOW);
digitalWrite(redCar, LOW);
digitalWrite(redPed, HIGH);
digitalWrite(greenCar, HIGH);
changeTime = millis();
}

Demonstration
When you press the button, the light for the cars changes from green to red, and the pedestrian
light changes from red to green.

After the crosstime, the pedestrian green led flashes and changes to red. The light for the cars
changes from red to green.

64
Wrapping Up
If you‘re starting with the Arduino, a good exercise is to change the value of some variables like
crossTime and changeTime and see what happens.

If you want something a little bit more challenging, try to mimic what happens in a junction, with
several lights for several cars and pedestrians.

65
14.Project 2 -LED Brightness on a
16x2 LCD

Introduction
This is a beginner project where you‘ll use a 16×2 LCD to display the LED brightness. Shortly,
in this project we‘ll control an LED brightness using a potentiometer. The
LED brightness will be displayed on the LCD screen using a progress bar

Watch the video below

Watch on YouTube: http://youtu.be/sAklcqiywPw

66
Introducing the LCD
The simplest and inexpensive way to display information is with an LCD (liquid crystal
display). These are found in everyday electronics devices such as vending machines,
calculators, parking meters, printers, and so on. These are ideal for displaying text or small
icons. The figure below shows a 16×2 LCD front and back view.

This LCD has 2 rows, and each row can display 16 characters. It also has LED backlight to adjust
the contrast between the characters and the background.

Parts Required
For this project you need the following parts:

• Arduino UNO
• 1x Breadboard
• 1x LCD 16×2
• 2x 10k Ohm Potentiometers
• 1x 5mm LED
• 1x 220Ohm Resistor
• Jumper wires

67
Schematics
Wire all the parts by following the next schematic diagram.

The next table shows a brief description of each pin of the LCD display. Make sure your LCD
uses the same pinout.
Interface Pin Connections:
Pin No Symbol Level Description
1 Vss … Ground for Logic (0V)
2 Vdd … Power Supply for Logic (+5.0V)
3 Vo … Power Supply for LCD drive
4 RS H/L Register Selection (H: Data register, L: Instruction
Register)
5 R/W H/L Read/Write Selection (H: Read, L: Write)
6 E H/L  L Enable Signal for LCM
7-14 DB0-DB7 H/L Data Bus Lines
15 LEDA … Power Supply for Backlight (+5.0V)
16 LEDK … Power Supply for Backlight (.)

68
Sketch
Copy the following code and upload it to your Arduino board. The code is well commented so
that you can easily understand how it works, and modify it to include in your own projects.

// include the library code


#include <LiquidCrystal.h>
// initialize the library with the numbers of the interface pins
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
int potPin = A0; // Analog pin 0 for the LED brightness potentiometer
int ledPin = 6; // LED Digital Pin with PWM
int potValue = 0; // variable to store the value coming from the potentiometer
int brightness = 0; // converts the potValue into a brightness
int pBari = 0; // progress bar
int i = 0; // foor loop
//progress bar character for brightness
byte pBar[8] = {
B11111,
B11111,
B11111,
B11111,
B11111,
B11111,
B11111,
};
void setup() {
// setup our led as an OUTPUT
pinMode(ledPin, OUTPUT);
// set up the LCD's number of columns and rows:
lcd.begin(16, 2);
// Print a message to the LCD
lcd.print(" LED Brightness");
//Create the progress bar character
lcd.createChar(0, pBar);
}
void loop() {
// clears the LCD screen
lcd.clear();
// Print a message to the LCD
lcd.print(" LED Brightness");
//set the cursor to line number 2
lcd.setCursor(0,1);
// read the value from the potentiometer
potValue = analogRead(potPin);
// turns the potValue into a brightness for the LED
brightness=map(potValue, 0, 1024, 0, 255);
//lights up the LED according to the bightness
analogWrite(ledPin, brightness);
// turns the brighness into a percentage for the bar
69
pBari=map(brightness, 0, 255, 0, 17);
//prints the progress bar
for (i=0; i<pBari; i++)
{
lcd.setCursor(i, 1);
lcd.write(byte(0));
}
// delays 750 ms
delay(750);
}

70
15.Project 3 - Parking Sensor

Introduction
In this project we have an ultrasonic sensor that measures the distance and an LED bar graph
that lights up accordingly to our distance from the sensor. As we get closer to the sensor the
buzzer beeps in a different way. This circuit can work as a parking sensor.

Parts Required
• Arduino UNO – read Best Arduino Starter Kits
• 1x 74HC595 8 Bit Shift Register
• 1x Breadboard
• 8x LEDs (for example: 3x red, 3x yellow, 2x green)
• 9x 220 Ohm Resistors
• 1x Buzzer
• 1x Ultrasonic Sensor (for exemple: HC-SR04)
• Jumper Wires

71
Schematics
Assemble the circuit by following the next schematic diagram:

Sketch
Upload the following code to your Arduino board:

int tonePin = 4; //Tone - Red Jumper


int trigPin = 9; //Trig - violet Jumper
int echoPin = 10; //Echo - yellow Jumper
int clockPin = 11; //IC Pin 11 - white Jumper
int latchPin = 12; //IC Pin 12 - Blue Jumper
int dataPin = 13; //IC Pin 14 - Green Jumper
byte possible_patterns[9] = {
B00000000,
B00000001,
B00000011,
B00000111,
B00001111,
B00011111,
B00111111,
B01111111,
B11111111,
};
int proximity=0;
int duration;
int distance;
void setup() {
72
//Serial Port
Serial.begin (9600);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(clockPin, OUTPUT);
pinMode(latchPin, OUTPUT);
pinMode(dataPin, OUTPUT);
pinMode(tonePin, OUTPUT);
}
void loop() {
digitalWrite(latchPin, LOW);
digitalWrite(trigPin, HIGH);
delayMicroseconds(1000);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = (duration/2) / 29.1;
/*if (distance >= 45 || distance <= 0){
Serial.println("Out of range");
}
else {
Serial.print(distance);
Serial.println(" cm");
}*/
proximity=map(distance, 0, 45, 8, 0);
//Serial.println(proximity);
if (proximity <= 0){
proximity=0;
}
else if (proximity >= 3 && proximity <= 4){
tone(tonePin, 200000, 200);
}
else if (proximity >= 5 && proximity <= 6){
tone(tonePin,5000, 200);
}
else if (proximity >= 7 && proximity <= 8){
tone(tonePin, 1000, 200);
}
shiftOut(dataPin, clockPin, MSBFIRST, possible_patterns[proximity]);
digitalWrite(latchPin, HIGH);
delay(600);
noTone(tonePin);
}

73
Watch the video demonstration

Watch on YouTube: http://youtu.be/7ZPc__5tL3c

74
16.Project 4 -Control LEDs with IR
Remote Control

Introduction
In this project you‘ll use an infrared (IR) receiver to control 3 LEDs with a remote control.
You‘ll turn them on and off with the buttons of your remote control. This is a good beginner
project to get you introduced to the infrared receiver.

This project is divided into two parts:

• You‘ll decode the IR signals transmitted by your remote control


• You‘ll use that info to perform a task with your Arduino (control 3 LEDs)

Infrared (IR) Receiver


The infrared receiver is the component in the figure below. This is the TSOP4838.

75
As you can see, it has three pins:

• OUT (OUTPUT)
• GND (Ground)
• VCC (Voltage source)

When you press your remote control, it sends infrared modulated signals. These signals contain
information that your receiver collects.

Each button sends specific information. So, we can assign that information to a specific button.

76
Parts Required
For this project you‘ll need a remote control. If you don‘t have any remote control at home, you
need to buy one.

Any remote control will do, even if it is a very old one that you don‘t use. Actually, if it is an
old one that you have laying around that‘s perfect. It‘s a new purpose for something old.

• Arduino UNO – read Best Arduino Starter Kits


• 1x Breadboard
• 1x Remote control
• 1x IR receiver ( I‘ll be using TSOP4838)
• 3x LEDs
• 4x 220ohm resistors
• Jumper cables

1. Decode the IR signals


In this part of the project you need to decode the IR signals associated with each button.

Schematics
Connect the IR receiver accordingly to the schematics below.

77
Sketch
To control the IR receiver, you need to install the IRremote Library in the Arduino IDE.

Installing the IRremote library

1. Click here to download the IRremote library. You should have a .zip folder in
your Downloads
2. Unzip the .zip folder and you should get IRremote-master folder
3. Rename your folder from IRremote-master to IRremote
4. Move the IRremote folder to your Arduino IDE installation libraries folder
5. Finally, re-open your Arduino IDE
Note: this library conflicts with the RobotIRremote library. So, in order to use it, you should
move temporarily the RobotIRremote library out of the Arduino IDE libraries folder. If you
don‘t do this, the code will not compile!

Copy the following code to your Arduino IDE, and upload it to your Arduino board.
Make sure that you have the right board and COM port selected.

78
#include <IRremote.h>

int RECV_PIN = 11;

IRrecv irrecv(RECV_PIN);

decode_results results;

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);

Open the serial monitor at a baud rate of 9600.

In this project you want to control 3 LEDs. Choose 6 buttons for the following tasks:

1. LED1 – ON
2. LED1 – OFF
3. LED2 – ON
4. LED2 – OFF
5. LED3 – ON
6. LED3 – OFF

79
Press button number 1. You should see a code on the serial monitor. Press the same button
several times to make sure you have the right code for that button. If you see something like
FFFFFFFF ignore it, it‘s trash.

Do the same for the other buttons.

Write down the code associated with each button, because you‘ll need that information later.

2. Building the final circuit


In this part, you‘ll build the circuit with three LEDs that will be controlled using your remote.
Assemble all the parts by following the schematics below.

Code
Now, grab the codes you captured in the previous step. You need to convert your codes from hex
to decimal.

For that, you can use the following website: www.binaryhexconverter.com/hex-todecimal-


converter

Here‘s a conversion example for one of my codes:

80
Repeat that process to all your hex values and save the decimal values. These are the ones you
need to replace in the code below.

Copy the following sketch to your Arduino IDE. Write your own decimal values in the sketch
provided in the case lines and upload it to your Arduino board. Make sure that you have the
right board and COM port selected.

#include <IRremote.h>
int bluePin = 10; //define digital pin 10 for blue LED
int greenPin = 9; //define digital pin 9 for green LED
int yellowPin = 8; //define digital pin 8 for yellow LED
IRrecv irrecv(7); //define pin 7 as receiver
decode_results results; //store IR receiver results here
void setup()
{
pinMode(bluePin, OUTPUT); // sets the digital pin as output
pinMode(greenPin, OUTPUT); // sets the digital pin as output
pinMode(yellowPin, OUTPUT); // sets the digital pin as output
irrecv.enableIRIn(); // start the receiver
}
void loop()
{
if (irrecv.decode(&results))
{
switch (results.value)
{
case 551520375: //when you press the 1 button
digitalWrite(bluePin, HIGH);
break;
case 551495895: //when you press the 4 button
digitalWrite(bluePin, LOW);
break;
case 551504055: //when you press the 2 button
digitalWrite(greenPin, HIGH);
break;
case 551528535: //when you press the 5 button
digitalWrite(greenPin, LOW);
break;
case 551536695: //when you press the 3 button
81
digitalWrite(yellowPin, HIGH);
break;
case 551512215: //when you press the 6 button
digitalWrite(yellowPin, LOW);
break;
}
irrecv.resume(); // Receives the next value from the button you press
}
delay(10);
}

Demonstration
Now you can control each LED individually using the buttons of your remote control.

Wrapping up
This is a great project to learn about the IR receiver. There are endless possibilities for what you
can do with it.

For example, you can replace those LEDs with a relay to control your house appliances.

This can be particularly useful because some remotes have a bunch of buttons that you never use.
So, why not use them to do something?

P.S. I should warn you that I‘ve found some issues with the IRremote library. For example, I‘ve
found that this library conflicts with the analogwrite() arduino function.

82
REFERENCES
1. Arduino Projects Book by Scott Fitzgerald and Michael Shiloh 2012 Arduino
LLC ( https://www.uio.no/studier/emner/matnat/ifi/IN1060/v21/arduino/arduino-
projects-book.pdf)
2. Random Nerd Tutorials - Arduino Step-by-step Projects Course by Rui Santos
(https://randomnerdtutorials.com/arduino-step-by-step-projects/)
3. A Hands-On Introduction with 65 Projects by john boxall
(https://www.prorobot.ru/load/arduino-workshop-a-hands-on-Introduction.pdf)
4. Arduino Play ground Geeky Projects for the Curious Maker by warren Andrews
(https://books.google.com/books/about/Arduino_Playground.html?id=PSHLjwE
ACAAJ)

83

You might also like