Voice Controlled Home Automation

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 55

ABSTRACT

The concept of Home Automation is gaining popularity as it helps in reducing


human effort and errors and thus increasing the efficiency. With the help of
Home Automation system, we can control different appliances like lights, fans,
TV, AC etc. Additionally, a home automation system can also provide other
features like security, alarms, emergency systems etc. can be integrated.

There are many types of Home Automation Systems like Bluetooth Controlled,
Internet Controlled, RF Controlled, Remote Controlled (IR Remote) etc. Each
type has its own advantages and disadvantages. In this project, we have
designed a Voice Activated Home Automation system, where different
appliances are controlled by sending a Voice Command.

The Voice Activated Home Automation project is implemented using Arduino


UNO, Bluetooth and a smart phone. Further sections will explain circuit
diagram, components required and working.
CHAPTER - 1
1.INTRODUCTION
A home automation system is a technological solution that enables automating
the bulk of electronic, electrical and technology-based tasks within a home. It
uses a combination of hardware and software technologies that enable control
and management over appliances and devices within a home.
The concept of Home Automation is gaining popularity as it helps in reducing
human effort and errors and thus increasing the efficiency. With the help of
Home Automation system, we can control different appliances like lights, fans,
TV, AC etc. Additionally, a home automation system can also provide other
features like security, alarms, emergency systems etc. can be integrated.

Home automation is one of the major growing industries that can change the
way people live. Some of these home automation systems target those seeking
luxury and sophisticated home automation platforms; others target those with
special needs like the elderly and the disabled. Typical wireless home
automation system allows one to control house hold appliances from a
centralized control unit which is wireless. These appliances usually have to be
specially designed to be compatible with each other and with the control unit
for most commercially available home automation systems.

According to major companies that are involved in speech recognition


researches, voice will be the primary interface between humans and machines
in the near future. The problem lies with the situation of the elderly or disabled
people, who cannot usually help themselves to move around, and might
require external assistance. People who live alone might also need a helping
hand at home. Therefore a voice controlled home automation system is
designed, so that the users can perform certain tasks by just the use of their
voices, moreover, the system is designed to have a hand-held device(remote)
so that the user can easily speak their commands, otherwise they would have
to walk over to the microphone to speak. Having a remote will make the
system more user-friendly and portable.
The developed system can be integrated as a single portable unit and allows
one to wirelessly control lights, fans, air conditioners, television sets, security
cameras, electronic doors, computer systems, audio/visual equipment’s etc.
and turn ON or OFF any appliance that is plugged into a wall outlet, get the
status of different sensors and take decision accordingly.

Some of the processes within home automation system design,


implementation and maintenance include:

 Installation of computer control for heating, ventilation and air


conditioning systems
 Internet/remote/network access to all installed components and
equipment
 Installation and maintenance of network-enabled surveillance cameras
and physical security systems
 Central control and management capabilities over electrical fixtures and
electronic appliances

Devices within the home automation system connect and communicate with
each over a local wired or wireless network. The entire home automation
system usually requires system management software, installation of
device/appliance controllers, motion and temperature sensors and other
components.

There are many types of Home Automation Systems like Bluetooth Controlled,
Internet Controlled, RF Controlled, Remote Controlled (IR Remote) etc. Each
type has its own advantages and disadvantages. In this project, we have
designed a Voice Activated Home Automation system, where different
appliances are controlled by sending a Voice Command.

The Voice Activated Home Automation project is implemented using Arduino


UNO, Bluetooth and a smart phone. Further sections will explain circuit
diagram, components required and working of the project.
1.2 NECESSITY OF AUTOMATION

A home automation system will control lighting, climate, entertainment systems, and


appliances. It may also include home security such as access control and alarm
systems. When connected with the Internet, home devices are an important
constituent of the Internet of Things.

Automation can also result in enhanced quality, precision and accuracy, it


involves the various control systems operation that enable operating
equipment to run on their own, speed for tasks and many more. Robotics
serves as an important means to provide industrial automation

Voice Acti

1.3 Advantages and disadvantages of automation

Advantages commonly attributed to automation include higher production


rates and increased productivity, more efficient use of materials, better
product quality, improved safety, shorter workweeks for labour, and reduced
factory lead times. Higher output and increased productivity have been two of
the biggest reasons in justifying the use of automation. Despite the claims of
high quality from good workmanship by humans, automated systems typically
perform the manufacturing process with less variability than human workers,
resulting in greater control and consistency of product quality. Also, increased
process control makes more efficient use of materials, resulting in less scrap.

Disadvantages of automated equipment include the high capital expenditure


required to invest in automation (an automated system can cost millions of
dollars to design, fabricate, and install), a higher level of maintenance needed
than with a manually operated machine, and a generally lower degree of
flexibility in terms of the possible products as compared with a manual system
(even flexible automation is less flexible than humans, the most versatile
machines of all).
1.4 Applications
 The Voice Activated Home Automation system will help us control different loads
(electrical appliances) with simple voice commands.
 This kind of system is very useful for people with disabilities.
 Further, the project can be expanded by adding different sensors (light, smoke, etc.). 
CHAPTER - 2
2.COMPONENT DESCRIPTION

Components Required
i. Arduino UNO – 1
ii. 2 HC – 05 Bluetooth Module – 1
iii. Smart Phone or Tablet – 1
iv. 2N2222 NPN Transistor – 4
v. 12V Relay – 4
vi. 1 KΩ Resistor – 4
vii. 1N4007 PN Junction Diode – 4
viii. Power Supply
ix. Connecting Wires
x. Breadboard (Prototyping Board)
xi. App for transmitting voice to Bluetooth

2.1 2N2222 TRANSISTOR


The 2N2222 is a common NPN bipolar junction transistor (BJT) used for general
purpose low-power amplifying or switching applications. It is designed for low
to medium current, low power, medium voltage, and can operate at
moderately high speeds.

2.2 RESISTOR
A resistor is a passive two-terminal electrical component that
implements electrical resistance as a circuit element. In electronic circuits,
resistors are used to reduce current flow, adjust signal levels, to divide
voltages, bias active elements, and terminate transmission lines, among other
uses. High-power resistors that can dissipate many watts of electrical power as
heat, may be used as part of motor controls, in power distribution systems, or
as test loads for generators. Fixed resistors have resistances that only change
slightly with temperature, time or operating voltage. Variable resistors can be
used to adjust circuit elements (such as a volume control or a lamp dimmer), or
as sensing devices for heat, light, humidity, force, or chemical activity.

2.3 DIODES
A diode is a device which allows current flow through only one direction. That
is the current should always flow from the Anode to cathode. The cathode
terminal can be identified by using a grey bar as shown in the picture above.
For 1N4007 Diode, the maximum current carrying capacity is 1A it withstand
peaks up to 30A. Hence we can use this in circuits that are designed for less
than 1A.  The reverse current is 5uA which is negligible. The power dissipation
of this diode is 3W.

2.4 RELAYS
Relays are switches that open and close circuits electromechanically or
electronically. Relays control one electrical circuit by opening and closing
contacts in another circuit. As relay diagrams show, when a relay contact is
normally open (NO), there is an open contact when the relay is not energized.

2.5 ARDUINO
Arduino is a microcontroller platform that has captured the imagination of
electronics enthusiasts. Its ease of use and open source nature make it a great
choice for anyone wanting to build electronic projects. Ultimately, it allows you
to connect electronics through its pins so that it can control things—for
instance, turn lights or motors on and off or sense things such as light and
temperature. This is why Arduino is sometimes given the description physical
computing.

Because Arduinos can be connected to your computer by a universal serial bus


(USB)lead, this also means that you can use the Arduino as an interface board
to control those same electronics from your computer.
Power Supply
Referring to Figure directly below the USB connector is the 5-volt (5V) voltage
regulator. This regulates whatever voltage (between 7V and 12V) is supplied
from the power socket into a constant 5V. The 5V voltage regulator chip is
actually quite big for a surface mount component. This is so that it can
dissipate the heat required to regulate the voltage at a reasonably high
current. This is useful when driving external electronics.

Power Connections
Next let us look at the connectors at the bottom of Figure . You can read the
connection names next to the connectors. The first is Reset. This does the
same thing as the Reset button on the Arduino. Rather like rebooting a PC,
using the Reset connector resets the microcontroller so that it begins its
program from the start. To reset the microcontroller with the Reset connector,
you momentarily set this pin low (connecting it to 0V). The rest of the pins in
this section just provide different voltages (3.5V, 5V, GND, and 9V), as they are
labeled. GND, or ground, just means zero volts. It is the reference voltage to
which all other voltages on the board are relative.

Analog Inputs
The six pins labeled as Analog In A0 to A5 can be used to measure the voltage
connected to them so that the value can be used in a sketch. Note that they
measure a voltage and not a current. Only a tiny current will ever flow into
them and down to ground because they have a very large internal resistance.
That is, the pin having a large internal resistance only allows a tiny current to
flow into the pin. Although these inputs are labeled as analog, and are analog
inputs by default, these connections can also be used as digital inputs or
outputs.

Digital Connections
We now switch to the top connector and start on the right-hand side in Figure .
Here we find pins labeled Digital 0 to 13. These can be used as either inputs or
outputs. When used as outputs, they behave rather like the power supply
voltages discussed earlier in this section, except that these are all 5V and can
be turned on or off from your sketch. So, if you turn them on from your sketch
they will be at 5V, and if you turn them off they will be at 0V. As with the
power supply connectors, you must be careful not to exceed their maximum
current capabilities. The first two of these connections (0 and 1) are also
labeled RX and TX, for receive and transmit. These connections are reserved
for use in communication and are indirectly the receive and transmit
connections for your USB link to your computer. These digital connections can
supply 40 mA (milliamps) at 5V. That is more than enough to light a standard
LED, but not enough to drive an electric motor directly.
Microcontroller
Continuing our tour of the Arduino board, the microcontroller chip itself is the
black rectangular device with 28 pins. This is fitted into a dual inline (DIL)
socket so that it can be easily replaced. The 28-pin microcontroller chip used
on the Arduino Uno board is the ATmega328. The heart—or, perhaps more
appropriately, the brain—of the device is the central processing unit (CPU). It
controls everything that goes on within the device. It fetches program
instructions stored in the flash memory and executes them. This might involve
fetching data from working memory (RAM), changing it, and then putting it
back. Or, it may mean changing one of the digital outputs from 0V to 5V. The
EEPROM memory is a little like the flash memory in that it is nonvolatile. That
is, you can turn the device off and on and it will not have forgotten what is in
the EEPROM. Whereas the flash memory is intended for storing program
instructions (from sketches), the EEPROM is used to store data that you do not
want to lose in the event of a reset or the power being turned off.

Other Components
Above the microcontroller is a small, silver, rectangular component. This is a
quartz crystal oscillator. It ticks 16 million times a second, and on each of those
ticks, the microcontroller can perform one operation—addition, subtraction, or
another mathematical operation. To the right of the crystal is the Reset switch.
Clicking on this switch sends a logic pulse to the Reset pin of the
microcontroller, causing the microcontroller to start its program afresh and
clear its memory. Note that any program stored on the device will be retained,
because this is kept in non-volatile flash memory—that is, memory that
remembers even when the device is not powered. To the right of the Reset
button is the Serial Programming Connector. It offers another means of
programming the Arduino without using the USB port. Because we do have a
USB connection and software that makes it convenient to use, we will not avail
ourselves of this feature. In the top-left corner of the board next to the USB
socket is the USB interface chip. This chip converts the signal levels used by the
USB standard to levels that can be used directly by the Arduino board.
Powering Up Arduino Board :
When you buy an Arduino board, it is usually preinstalled with a sample Blink
program that will make the little built-in light-emitting diode (LED) flash. The
LED marked L is wired up to one of the digital input output sockets on the
board. It is connected to digital pin 13. This limits pin 13 to being the one used
as an output. However, the LED uses only a small amount of current, so you
can still connect other things to that connector. All you need to do to get your
Arduino up and running is supply it with some power. The easiest way to do
this is to plug in it into the USB port on your computer. You will need a type-A-
to-type-B USB lead. This is the same type of lead that is normally used to
connect a computer to a printer. If everything is working OK, the LED should
blink. New Arduino boards come with this Blink sketch already installed so that
you can verify that the board works.

2.5.1 UPLOADING ARDUINO SKETCH:

After learning about the main parts of the Arduino UNO board, we are
ready to learn how to set up the Arduino IDE. Once we learn this, we will
be ready to upload our program on the Arduino board.

In this section, we will learn in easy steps, how to set up the Arduino IDE
on our computer and prepare the board to receive the program via USB
cable.

Step 1 − First you must have your Arduino board (you can choose your
favorite board) and a USB cable. In case you use Arduino UNO, Arduino
Duemilanove, Nano, Arduino Mega 2560, or Diecimila, you will need a
standard USB cable (A plug to B plug), the kind you would connect to a
USB printer as shown in the following image.
In case you use Arduino Nano, you will need an A to Mini-B cable instead
as shown in the following image.

Step 2 − Download Arduino IDE Software.

You can get different versions of Arduino IDE from the Download page on
the Arduino Official website. You must select your software, which is
compatible with your operating system (Windows, IOS, or Linux). After
your file download is complete, unzip the file.
Step 3 − Power up your board.

The Arduino Uno, Mega, Duemilanove and Arduino Nano automatically


draw power from either, the USB connection to the computer or an
external power supply. If you are using an Arduino Diecimila, you have
to make sure that the board is configured to draw power from the USB
connection. The power source is selected with a jumper, a small piece of
plastic that fits onto two of the three pins between the USB and power
jacks. Check that it is on the two pins closest to the USB port.

Connect the Arduino board to your computer using the USB cable. The
green power LED (labeled PWR) should glow.

Step 4 − Launch Arduino IDE.

After your Arduino IDE software is downloaded, you need to unzip the
folder. Inside the folder, you can find the application icon with an infinity
label (application.exe). Double-click the icon to start the IDE.
Step 5 − Open your first project.

Once the software starts, you have two options –


1.Create a new project.

2.Open an existing project example.


To create a new project, select File → New.To open an existing


project example, select File → Example → Basics → Blink.
Here, we are selecting just one of the examples with the name Blink. It
turns the LED on and off with some time delay. You can select any other
example from the list.

Step 6 − Select your Arduino board.

To avoid any error while uploading your program to the board, you must
select the correct Arduino board name, which matches with the board
connected to your computer.

Go to Tools → Board and select your board.


Here, we have selected Arduino Uno board according to our tutorial, but
you must select the name matching the board that you are using.

Step 7 − Select your serial port.

Select the serial device of the Arduino board. Go to Tools → Serial


Portmenu. This is likely to be COM3 or higher (COM1 and COM2 are
usually reserved for hardware serial ports). To find out, you can
disconnect your Arduino board and re-open the menu, the entry that
disappears should be of the Arduino board. Reconnect the board and
select that serial port.
Step 8 − Upload the program to your board.

Before explaining how we can upload our program to the board, we must
demonstrate the function of each symbol appearing in the Arduino IDE
toolbar.

A − Used to check if there is any compilation error.

B − Used to upload a program to the Arduino board.

C − Shortcut used to create a new sketch.

D − Used to directly open one of the example sketch.

E − Used to save your sketch.


F − Serial monitor used to receive serial data from the board and send
the serial data to the board.

Now, simply click the "Upload" button in the environment. Wait a few
seconds; you will see the RX and TX LEDs on the board, flashing. If the
upload is successful, the message "Done uploading" will appear in the
status bar.

2.6 RELAY BOARD

Relays are most commonly used switching device in electronics. Let us learn
how to use one in our circuits based on the requirement of our project.
Before we proceed with the circuit to drive the relay we have to consider two
important parameter of the relay. Once is the trigger voltage, this is the
voltage required to turn on the relay that is to change the contact from
Common->NC to Common->NO. Our relay here has 5V trigger voltage, but you
can also find relays of values 3V, 6V and even 12V so select one based on the
available voltage in your project. The other parameter is your load voltage &
current, this is the amount of voltage or current that the NC, NO or Common
terminal of the relay could withstand, in our case for DC it is maximum of 30V
and 10A. Make sure the load you are using falls into this range.
Relay Pin Configuration

Pin Pin Name Description


Number

1 Coil End 1 Used to trigger (On/Off) the Relay, Normally one end is
connected to 5V and the other end to ground

2 Coil End 2 Used to trigger (On/Off) the Relay, Normally one end is
connected to 5V and the other end to ground

3 Common (COM) Common is connected to one End of the Load that is to be


controlled

4 Normally Close (NC) The other end of the load is either connected to NO or NC. If
connected to NC the load remains connected before trigger

5 Normally Open (NO) The other end of the load is either connected to NO or NC. If
connected to NO the load remains disconnected before trigger
Features of 5-Pin 5V Relay

 Trigger Voltage (Voltage across coil) : 5V DC


 Trigger Current (Nominal current) : 70mA
 Maximum AC load current: 10A @ 250/125V AC
 Maximum DC load current: 10A @ 30/28V DC
 Compact 5-pin configuration with plastic moulding
 Operating time: 10msec Release time: 5msec
 Maximum switching: 300 operating/minute (mechanically)

Applications of Relay

 Commonly used in switching circuits.


 For Home Automation projects to switch AC loads
 To Control (On/Off) Heavy loads at a pre-determined time/condition
 Used in safety circuits to disconnect the load from supply in event of
failure
 Used in Automobiles electronics for controlling indicators glass motors
etc.
 

2.7 BLUETOOTH MODULE

HC‐05 module is an easy to use Bluetooth SPP (Serial Port Protocol) module,
designed for transparent wireless serial connection setup. The HC-05
Bluetooth Module can be used in a Master or Slave configuration, making it a
great solution for wireless communication. This serial port bluetooth module is
fully qualified Bluetooth V2.0+EDR (Enhanced Data Rate) 3Mbps Modulation
with complete 2.4GHz radio transceiver and baseband. It uses CSR Bluecore
04‐External single chip Rluetooth system with CMOS technology and with AFH
(Adaptive Frequency Hopping Feature).The Bluetooth module HC-05 is a
MASTER/SLAVE module. By default the factory setting is SLAVE. The Role of the
module (Master or Slave) can be configured only by AT COMMANDS. The slave
modules cannot initiate a connection to another Bluetooth device, but can
accept connections. Master module can initiate a connection to other devices.
The user can use it simply for a serial port replacement to establish connection
between MCU and GPS, PC to your embedded project, etc

Pin Configuration:

Pin Pin Name Description


Number
1. Enable / Key This pin is used to toggle between Data Mode (set
low) and AT command mode (set high). By default it is
in Data mode
2. Vcc Powers the module. Connect to +5V Supply voltage
3. Ground Ground pin of module, connect to system ground.
4. TX – Transmits Serial Data. Everything received via
Transmitter Bluetooth will be given out by this pin as serial data.
5. RX – Receive Serial Data. Every serial data given to this pin
Receiver will be broadcasted via Bluetooth
6. State The state pin is connected to on board LED , it can be
used as a feedback to check if Bluetooth is working
properly.
7. LED Indicates the status of Module
 Blink once in 2 sec: Module has entered
Command Mode
 Repeated Blinking: Waiting for connection in
Data Mode
 Blink twice in 1 sec: Connection successful in
Data Mode
8. Button Used to control the Key/Enable pin to toggle between
Data and command Mode

HC-05 Default Settings


Default Bluetooth Name: “HC-05”

Default Password: 1234 or 0000

Default Communication: Slave

Default Mode: Data Mode

Data Mode Baud Rate: 9600, 8, N, 1

Command Mode Baud Rate: 38400, 8, N, 1

Default firmware: LINVOR

HC-05 Technical Specifications


Serial Bluetooth module for Arduino and other microcontrollers

Operating Voltage: 4V to 6V (Typically +5V)

Operating Current: 30mA

Range: <100m

Works with Serial communication (USART) and TTL compatible

Follows IEEE 802.15.1 standardized protocol


Uses Frequency-Hopping Spread spectrum (FHSS)

Can operate in Master, Slave or Master/Slave mode

Can be easily interfaced with Laptop or Mobile phones with Bluetooth

Supported baud rate: 9600,19200,38400,57600,115200,230400,460800

Hardware Connections :
As we know that Vcc and Gnd of the module goes to Vcc and Gnd of Arduino.
The TXD pin goes to RXD pin of Arduino and RXD pin goes to TXD pin of
Arduino i.e (digital pin 0 and 1).The user can use the on board Led. But here,
Led is connected to digital pin 12 externally for betterment of the process.

Program for HC-05 Bluetooth Module


The program given below is the HC-05 bluetooth module program. This
process is quite different from others since we are going to use android mobile
to control and communicate with arduino. Here the bluetooth module acts as
an interface between our mobile and Arduino board. Before getting into the
execution process, follow the given procedure:

First of all, the user should install an application called AMR_VOICE from online
which is a free application. After installation, pair the bluetooth module to your
mobile as like connecting one device to other using bluetooth. The default
pairing code is 1234. Upload the given program to the Arduino Uno board.
After uploading the code, unplug the USB from the Arduino. Now use external
power adapter to power the Uno board. Here Byte stream mode is used to
communicate. So select that mode and give the input as 1, as soon as the
input has given the led will turn on and for 0 led will turn off.
CHAPTER – 3
3.1 HOME AUTOMATION MODEL

Home automation system introduces a computerization or automation of


some electrical and electronic systems. This system includes complete
automation of lights, temperature control, door security, etc. In this paper, a
hardware system is developed and installed to monitor and control various
home appliances. It can control the appliances based on its configuration. This
system automatically turn on lights at a specified time in the evening. It can
measure light intensity in a room by using hardware sensor and turn on bulb
when light intensity becomes low. The system can allow a person to control
appliances from a remote location by internet.

WHAT IS HOME AUTOMATION AND HOW DOES IT WORK ?

Home Automation describes a system of networked, controllable devices


that work together to make your home more comfortable, customized,
efficient, and secure.The range of controls that you have over your automated
devices range depending on the purpose of the device .
3.2 CIRCUIT DESCRIPTION

We will now see the design of the Voice Activated Home Automation circuit.
First, we will connect the Bluetooth Module to the Arduino. Since Bluetooth
uses UART protocol, we need to use the RX and TX pins of the Arduino. We will
be using “SoftwareSerial” library to define our own RX and TX pins (Pin 2 is RX
and Pin 3 is TX).

NOTE: We have left out the Bluetooth’s RX and Arduino’s TX connection as it is


not used. In case you face a problem, connect a voltage divider to convert the
Arduino TX’s 5V signal to Bluetooth RX’s 3.3V.

Next, we will connect the relays to the Arduino. Since we used a readymade
relay board with 4 – channels, all we need to do is to connect the inputs of the
individual relays to the Arduino. For detailed connection like the resistor,
transistor, diode and relay, refer the circuit diagram.

NOTE: We did not connect any load to the relay but you can always connect
some small loads and check out the functioning.
3.3 Working of the Project

In this project, a simple Voice Activated Home Automation system is designed.


Voice commands are used to control different appliances. We will now see the
working of the project. All the connections are made as per the circuit diagram
above.

After making the necessary connections, we have to switch on the power


supply to the circuit. Now, we need to pair the Phone’s Bluetooth to the HC –
05 Bluetooth Module. Before that, we have to install the App mentioned above
in the phone. The home screen of the app looks something like this.

Next step is to connect the phone with the Bluetooth module. For this, choose
the option “Connect Robot” and select the appropriate Bluetooth Device. If the
devices aren’t paired earlier, we need to pair them now using the Pin of the HC
– 05 Bluetooth Module.

After successful connection, the devices are ready to transmit data. For that,
press the press microphone icon on the app and start giving voice commands.

NOTE: Make sure that the voice recognition feature is enabled on the phone
(this is usually associated with Google app).

For example, if we press the microphone icon and say “turn on light”, the app
will recognise the command and the transfers it to the Bluetooth Module. Also,
the command gets displayed on the screen for our reference.
When the string “turn on light” is detected by the app, it will send the string as
“*turn on light#”. So, the actual message received by the Bluetooth Module is
in the format of “*Message#”. The reason for padding the ‘*’ and ‘#’ at the
begging and end of the string is to identify the starting and ending of the
message.
CHAPTER – 4
SKETCH AND ITS EXPLANATION

4.1 Arduino - Communication

Hundreds of communication protocols have been defined to achieve this data


exchange. Each protocol can be categorized into one of the two categories:
parallel or serial.
Parallel Communication
Parallel connection between the Arduino and peripherals via input/output
ports is the ideal solution for shorter distances up to several meters. However,
in other cases when it is necessary to establish communication between two
devices for longer distances it is not possible to use parallel connection.
Parallel interfaces transfer multiple bits at the same time. They usually require
buses of data - transmitting across eight, sixteen, or more wires. Data is
transferred in huge, crashing waves of 1’s and 0’s.

Advantages and Drawbacks of Parallel Communication


Parallel communication certainly has its advantages. It is faster than serial,
straightforward, and relatively easy to implement. However, it requires many
input/output (I/O) ports and lines. If you have ever had to move a project from
a basic Arduino Uno to a Mega, you know that the I/O lines on a
microprocessor can be precious and few. Therefore, we prefer serial
communication, sacrificing potential speed for pin real estate.
Serial Communication Modules
Today, most Arduino boards are built with several different systems for
serial communication as standard equipment.
Which of these systems are used depends on the following factors −

 How many devices the microcontroller has to exchange data with?


 How fast the data exchange has to be?
 What is the distance between these devices?
 Is it necessary to send and receive data simultaneously?
One of the most important things concerning serial communication is
the Protocol, which should be strictly observed. It is a set of rules, which must
be applied such that the devices can correctly interpret data they mutually
exchange. Fortunately, Arduino automatically takes care of this, so that the
work of the programmer/user is reduced to simple write (data to be sent) and
read (received data).
Types of Serial Communications
Serial communication can be further classified as −
 Synchronous − Devices that are synchronized use the same clock and
their timing is in synchronization with each other.
 Asynchronous − Devices that are asynchronous have their own clocks
and are triggered by the output of the previous state.
It is easy to find out if a device is synchronous or not. If the same clock is given
to all the connected devices, then they are synchronous. If there is no clock
line, it is asynchronous.
For example, UART (Universal Asynchronous Receiver Transmitter) module is
asynchronous.
The asynchronous serial protocol has a number of built-in rules. These rules
are nothing but mechanisms that help ensure robust and error-free data
transfers. These mechanisms, which we get for eschewing the external clock
signal, are −

 Synchronization bits
 Data bits
 Parity bits
 Baud rate
Synchronization Bits
The synchronization bits are two or three special bits transferred with each
packet of data. They are the start bit and the stop bit(s). True to their name,
these bits mark the beginning and the end of a packet respectively.
There is always only one start bit, but the number of stop bits is configurable
to either one or two (though it is normally left at one).
The start bit is always indicated by an idle data line going from 1 to 0, while
the stop bit(s) will transition back to the idle state by holding the line at 1.

Data Bits
The amount of data in each packet can be set to any size from 5 to 9 bits.
Certainly, the standard data size is your basic 8-bit byte, but other sizes have
their uses. A 7-bit data packet can be more efficient than 8, especially if you
are just transferring 7-bit ASCII characters.
Parity Bits
The user can select whether there should be a parity bit or not, and if yes,
whether the parity should be odd or even. The parity bit is 0 if the number of
1’s among the data bits is even. Odd parity is just the opposite.
Baud Rate
The term baud rate is used to denote the number of bits transferred per
second [bps]. Note that it refers to bits, not bytes. It is usually required by the
protocol that each byte is transferred along with several control bits. It means
that one byte in serial data stream may consist of 11 bits. For example, if the
baud rate is 300 bps then maximum 37 and minimum 27 bytes may be
transferred per second.
Arduino UART
The following code will make Arduino send hello world when it starts up.

void setup() {
Serial.begin(9600); //set up serial library baud rate to 9600

Serial.println("hello world"); //print hello world

void loop() {

After the Arduino sketch has been uploaded to Arduino, open the Serial
monitor   at the top right section of Arduino IDE.
Type anything into the top box of the Serial Monitor and press send or enter
on your keyboard. This will send a series of bytes to the Arduino.
The following code returns whatever it receives as an input.
The following code will make Arduino deliver output depending on the input
provided.

void setup() {

Serial.begin(9600); //set up serial library baud rate to 9600

void loop() {

if(Serial.available()) //if number of bytes (characters) available for reading


from {

serial port

Serial.print("I received:"); //print I received

Serial.write(Serial.read()); //send what you read

}
Notice that Serial.print and Serial.println will send back the actual ASCII code,
whereas Serial.write will send back the actual text. See ASCII codes for more
information.
4.2 PROGRAM STRUCTURE:
Sketch − The first new terminology is the Arduino program called “sketch”.
Arduino programs can be divided in three main parts: Structure,
Values(variables and constants), and Functions. In this tutorial, we will learn
about the Arduino software program, step by step, and how we can write the
program without any syntax or compilation error.
Let us start with the Structure. Software structure consist of two main
functions −

 Setup( ) function
 Loop() function

Void setup ( ) {
}
 PURPOSE − The setup() function is called when a sketch starts. Use it to
initialize the variables, pin modes, start using libraries, etc. The setup
function will only run once, after each power up or reset of the Arduino
board.
 INPUT − -
 OUTPUT − -
 RETURN − -
 PURPOSE − After creating a setup() function, which initializes and sets
the initial values, the loop() function does precisely what its name
suggests, and loops consecutively, allowing your program to change and
respond. Use it to actively control the Arduino board.

Void Loop ( ) {

}
 PURPOSE − After creating a setup() function, which initializes and sets
the initial values, the loop() function does precisely what its name
suggests, and loops consecutively, allowing your program to change and
respond. Use it to actively control the Arduino board.
 INPUT − -
 OUTPUT − -
 RETURN − -
4.3 SKETCH:
#include <SoftwareSerial.h>
const int rxPin = 2;
const int txPin = 3;
SoftwareSerial mySerial(rxPin, txPin);

int ac=4;
int light=5;
int fan=6;
int tv=7;
String data;
void setup()
{
Serial.begin(9600);
mySerial.begin(9600);

pinMode(ac, OUTPUT);
pinMode(light, OUTPUT);
pinMode(fan, OUTPUT);
pinMode(tv, OUTPUT);

digitalWrite(ac, LOW);
digitalWrite(light, LOW);
digitalWrite(fan, LOW);
digitalWrite(tv, LOW);
}

void loop()
{
int i=0;
char ch=0;
data="";
while(mySerial.available()<=0)
{
ch = mySerial.read();
if(ch=='#')
break;
data+=ch;
}
Serial.println(data);

if(data=="*turn on AC")
{
digitalWrite(ac,HIGH);
Serial.println("ac on");
}
else if(data=="*turn off AC")
{
digitalWrite(ac,LOW);
Serial.println("ac off");
}
else if(data=="*turn on light")
{
digitalWrite(light,HIGH);
Serial.println("light on");
}
else if(data=="*turn off light")
{
digitalWrite(light,LOW);
Serial.println("light off");
}
else if(data=="*turn on fan")
{
digitalWrite(fan,HIGH);
Serial.println("fan on");
}
else if(data=="*turn off fan")
{
digitalWrite(fan,LOW);
Serial.println("fan off");
}
else if(data=="*turn on TV")
{
digitalWrite(tv,HIGH);
Serial.println("tv on");
}
else if(data=="*turn on TV")
{
digitalWrite(tv,LOW);
Serial.println("tv off");
}
else if(data=="*turn on all")
{
digitalWrite(ac,HIGH);
digitalWrite(light,HIGH);
digitalWrite(fan,HIGH);
digitalWrite(tv,HIGH);
Serial.println("all on");
}
else if(data=="*turn off all")
{
digitalWrite(ac,LOW);
digitalWrite(light,LOW);
digitalWrite(fan,LOW);
digitalWrite(tv,LOW);
Serial.println("all off");

SOFTWARE SERIAL

Arduino and Genuino boards have built in support for serial communication on
pins 0 and 1, but what if you need more serial ports? The software serial library
has been developed to allow serial communication to take place on the other
digital pins of your boards, using software to replicate the functionality of the
hardwired RX and TX lines. This can be extremely helpful when the need arises
to communicate with two serial enabled devices, or to talk with just one device
while leaving the main serial port open for debugging purpose.

The Arduino hardware has built-in support for serial communication on pins 0
and 1 (which also goes to the computer via the USB connection). The native
serial support happens via a piece of hardware (built into the chip) called
a UART. This hardware allows the Atmega chip to receive serial communication
even while working on other tasks, as long as there room in the 64 byte serial
buffer.

The SoftwareSerial library has been developed to allow serial communication


on other digital pins of the Arduino, using software to replicate the
functionality (hence the name "SoftwareSerial"). It is possible to have multiple
software serial ports with speeds up to 115200 bps. A parameter enables
inverted signaling for devices which require that protocol.

LIMITATIONS:

The library has the following known limitations:

 If using multiple software serial ports, only one can receive data at a
time.
 Not all pins on the Mega and Mega 2560 support change interrupts, so
only the following can be used for RX: 10, 11, 12, 13, 14, 15, 50, 51, 52, 53, A8
(62), A9 (63), A10 (64), A11 (65), A12 (66), A13 (67), A14 (68), A15 (69).
 Not all pins on the Leonardo and Micro support change interrupts, so
only the following can be used for RX: 8, 9, 10, 11, 14 (MISO), 15 (SCK), 16
(MOSI).
 On Arduino or Genuino 101 the current maximum RX speed is 57600bps
 On Arduino or Genuino 101 RX doesn't work on Pin 13

SoftwareSerial(rxPin, txPin, inverse_logic)

Description
SoftwareSerial is used to create an instance of a SoftwareSerial object, whose
name you need to provide. The inverse_logic argument is optional and defaults
to false. See below for more details about what it does.
Multiple SoftwareSerial objects may be created, however only one can be
active at a given moment.

You need to call SoftwareSerial.begin() to enable communication.

Parameters
rxPin: the pin on which to receive serial data

txPin: the pin on which to transmit serial data

inverse_logic: is used to invert the sense of incoming bits (the default is normal
logic). If set, SoftwareSerial treats a LOW (0 volts on the pin, normally) on the
Rx pin as a 1-bit (the idle state) and a HIGH (5 volts on the pin, normally) as a 0-
bit. It also affects the way that it writes to the Tx pin. Default value is false.

Warning: You should not connect devices which output serial data outside the
range that the Arduino can handle, normally 0V to 5V, for a board running at
5V, and 0V to 3.3V for a board running at 3.3V.

Serial.begin():
Description
Sets the speed (baud rate) for the serial communication. Supported baud rates
are 300, 600, 1200, 2400, 4800, 9600, 14400, 19200, 28800, 31250, 38400,
57600, and 115200.

Parameters
speed: the baud rate (long)

Returns
none

available():

Description
Get the number of bytes (characters) available for reading from a software
serial port. This is data that's already arrived and stored in the serial receive
buffer.

Syntax
mySerial.available()

Parameters
none

Returns
The number of bytes available to read

mySerial.read():

Description
Return a character that was received on the RX pin of the software serial port.
Note that only one SoftwareSerialinstance can receive incoming data at a time
(select which one with the listen() function).
Parameters
none

Returns
the character read, or -1 if none is available.

SoftwareSerial: println(data)

Description
Prints data to the transmit pin of the software serial port, followed by a
carriage return and line feed. Works the same as the Serial.println() function.

Parameters
vary, see Serial.println() for details

Returns
byte
println() will return the number of bytes written, though reading that number
is optional

pinMode()
[Digital I/O]

Descripti on

Configures the specified pin to behave either as an input or an output.


See the description of (digital pins ) for details on the functionality of the
pins.

As of Arduino 1.0.1, it is possible to enable the internal pullup resistors


with the mode INPUT_PULLUP. Additionally, the INPUT mode explicitly
disables the internal pullups.
Syntax

pinMode(pin, mode)

Parameters

pin: the number of the pin whose mode you wish to set

mode: INPUT, OUTPUT, or INPUT_PULLUP. (see the

digitalWrite()
[Digital I/O]

Descripti on

Write a HIGH or a LOW value to a digital pin.

If the pin has been configured as an OUTPUT with pinMode(), its voltage


will be set to the corresponding value: 5V (or 3.3V on 3.3V boards)
for HIGH, 0V (ground) for LOW.

If the pin is configured as an INPUT, digitalWrite() will enable (HIGH) or


disable (LOW) the internal pullup on the input pin. It is recommended to
set the pinMode() to INPUT_PULLUP to enable the internal pull-up
resistor. See the digital pins tutorial for more information.

If you do not set the pinMode() to OUTPUT, and connect an LED to a pin,


when calling digitalWrite(HIGH), the LED may appear dim. Without
explicitly setting pinMode(), digitalWrite() will have enabled the internal
pull-up resistor, which acts like a large current-limiting resistor.

Syntax

digitalWrite(pin, value)

Parameters

pin: the pin number

value: HIGH or LOW
Returns

Nothing

int
[Data Types]

Descripti on

Integers are your primary data-type for number storage.

On the Arduino Uno (and other ATmega based boards) an int stores a 16-
bit (2-byte) value. This yields a range of -32,768 to 32,767 (minimum
value of -2^15 and a maximum value of (2^15) - 1). On the Arduino Due
and SAMD based boards (like MKR1000 and Zero), an int stores a 32-bit
(4-byte) value. This yields a range of -2,147,483,648 to 2,147,483,647
(minimum value of -2^31 and a maximum value of (2^31) - 1).

int’s store negative numbers with a technique called (2’s complement


math ). The highest bit, sometimes referred to as the "sign" bit, flags the
number as a negative number. The rest of the bits are inverted and 1 is
added.

The Arduino takes care of dealing with negative numbers for you, so that
arithmetic operations work transparently in the expected manner. There
can be an unexpected complication in dealing with the bitshift right
operator  (>>) however.

Syntax

int var = val;

string
[Data Types]
Descripti on

Text strings can be represented in two ways. you can use the String data
type, which is part of the core as of version 0019, or you can make a
string out of an array of type char and null-terminate it. This page
described the latter method. For more details on the String object, which
gives you more functionality at the cost of more memory, see the String
object  page.

Syntax

All of the following are valid declarations for strings.

char Str1[15];
char Str2[8] = {'a', 'r', 'd', 'u', 'i', 'n', 'o'};
char Str3[8] = {'a', 'r', 'd', 'u', 'i', 'n', 'o', '\0'};
char Str4[] = "arduino";
char Str5[8] = "arduino";
char Str6[15] = "arduino";

Possibilities for declaring strings

 Declare an array of chars without initializing it as in Str1


 Declare an array of chars (with one extra char) and the compiler will
add the required null character, as in Str2
 Explicitly add the null character, Str3
 Initialize with a string constant in quotation marks; the compiler will
size the array to fit the string constant and a terminating null character,
Str4
 Initialize the array with an explicit size and string constant, Str5
 Initialize the array, leaving extra space for a larger string, Str6

Null termination

Generally, strings are terminated with a null character (ASCII code 0). This
allows functions (like Serial.print()) to tell where the end of a string is.
Otherwise, they would continue reading subsequent bytes of memory
that aren’t actually part of the string.
This means that your string needs to have space for one more character
than the text you want it to contain. That is why Str2 and Str5 need to be
eight characters, even though "arduino" is only seven - the last position is
automatically filled with a null character. Str4 will be automatically sized
to eight characters, one for the extra null. In Str3, we’ve explicitly
included the null character (written '\0') ourselves.

Note that it’s possible to have a string without a final null character (e.g.
if you had specified the length of Str2 as seven instead of eight). This will
break most functions that use strings, so you shouldn’t do it intentionally.
If you notice something behaving strangely (operating on characters not
in the string), however, this could be the problem.

Single quotes or double quotes?

Strings are always defined inside double quotes ("Abc") and characters
are always defined inside single quotes('A').

Wrapping long strings

You can wrap long strings like this:

char myString[] = "This is the first line"


" this is the second line"
" etcetera";

Arrays of strings

It is often convenient, when working with large amounts of text, such as a


project with an LCD display, to setup an array of strings. Because strings
themselves are arrays, this is in actually an example of a two-dimensional
array.

In the code below, the asterisk after the datatype char “char*” indicates


that this is an array of “pointers”. All array names are actually pointers, so
this is required to make an array of arrays. Pointers are one of the more
esoteric parts of C++ for beginners to understand, but it isn’t necessary to
understand pointers in detail to use them effectively here.

char
[Data Types]
Descripti on

A data type used to store a character value. Character literals are written
in single quotes, like this: 'A' (for multiple characters - strings - use double
quotes: "ABC").

Characters are stored as numbers however. You can see the specific
encoding in the ASCII chart . This means that it is possible to do arithmetic
on characters, in which the ASCII value of the character is used (e.g. 'A' +
1 has the value 66, since the ASCII value of the capital letter A is 65).
See Serial.println reference for more on how characters are translated to
numbers.

The size of the char datatype is at least 8 bits. It’s recommended to only


use char for storing characters. For an unsigned, one-byte (8 bit) data
type, use the byte  data type.

Syntax

char var = val;

Parameters

var: variable name


val: the value to assign to that variable

if

[Control Structure]

Descripti on

The if statement checks for a condition and executes the proceeding


statement or set of statements if the condition is 'true'.

Syntax
if (condition) {
//statement(s)
}

Parameters

condition: a boolean expression i.e., can be true or false

Comparison Operators:

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)

Beware of accidentally using the single equal sign (e.g. if (x = 10) ). The
single equal sign is the assignment operator, and sets x to 10 (puts the
value 10 into the variable x). Instead use the double equal sign (e.g. if (x
== 10)), which is the comparison operator, and tests whether x is equal to
10 or not. The latter statement is only true if xequals 10, but the former
statement will always be true.

This is because C++ evaluates the statement if (x=10) as follows: 10 is


assigned to x (remember that the single equal sign is the (assignment
operator)), so x now contains 10. Then the 'if' conditional evaluates 10,
which always evaluates to TRUE, since any non-zero number evaluates to
TRUE. Consequently, if (x = 10) will always evaluate to TRUE, which is not
the desired result when using an 'if' statement. Additionally, the
variable x will be set to 10, which is also not a desired action.

while
[Control Structure]

Descripti on

A while loop 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.

Syntax

while (condition) {
// statement(s)
}

The condition is a boolean expression that evaluates to true or false.

All functions,datatypes,structures and libraries used in sketch are


explained above.

Initially pin numbers are assigned to variables.In setup()


baudrate,pinmode and initial state of pins are assigned.

When the string “turn on light” is detected by the app, it will send the string
as “*turn on light#”. So, the actual message received by the Bluetooth Module
is in the format of “*Message#”. The reason for padding the ‘*’ and ‘#’ at the
begging and end of the string is to identify the starting and ending of the
message.

We are able to delete the ‘#’ from the string but left out the ‘*’ in order to
identify the starting of the string.

This is done by using while loop.Using while loop characters are retrieved and
compared with # and added to data. When # is encountered break is used to
come out of loop.Then data is compared with *statement and corresponding
action is performed.

We are able to delete the ‘#’ from the string but left out the ‘*’ in order to
identify the starting of the string. The received message is compared with
some predefined strings and if the message matches with any of them, then
corresponding action like turning on or turning off the load happens.

We have used the following commands: “turn on AC”, “turn off AC”, “turn on
light”, “turn off light”, “turn on TV”, “turn off TV”, “turn on fan”, “turn off fan”,
“turn on all” and “turn off all”.
CHAPTER – 5
CONCLUSION

You might also like