0% found this document useful (0 votes)
4 views62 pages

IOT Based Garbage Monitoring Using Arduino

The IoT Garbage Monitoring System is designed to enhance urban cleanliness by monitoring garbage levels in bins using ultrasonic sensors and displaying the data on a web page. It utilizes an AVR microcontroller, Wi-Fi modem, and LCD screen to provide real-time updates and alerts when bins reach capacity. The system aims to streamline waste management and improve city sanitation efforts.

Uploaded by

scmediaworks374
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views62 pages

IOT Based Garbage Monitoring Using Arduino

The IoT Garbage Monitoring System is designed to enhance urban cleanliness by monitoring garbage levels in bins using ultrasonic sensors and displaying the data on a web page. It utilizes an AVR microcontroller, Wi-Fi modem, and LCD screen to provide real-time updates and alerts when bins reach capacity. The system aims to streamline waste management and improve city sanitation efforts.

Uploaded by

scmediaworks374
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

IOT Garbage

Monitoring System
------------------------------------------------------------------------------------------------

CONTENT

----------------------------------------------------

2
CONTENT

[Link] CONTENT [Link]

1 Abstract 4

2 Block Diagram 6

3 Hardware & Software Specification 7

4 Arduino 8

5 Circuit Diagram 10

6 Working Principle 24

7 GSM Modem 30

8 Arduino Software 36

9 Conclusion 63

10 Reference 64

3
----------------------------------------------------

ABSTRACT

----------------------------------------------------

4
ABSTARCT

This project IOT Garbage Monitoring system is a very innovative system

which will help to keep the cities clean. This system monitors the garbage bins and

informs about the level of garbage collected in the garbage bins via a web page. For

this the system uses ultrasonic sensors placed over the bins to detect the garbage level

and compare it with the garbage bins depth. The system makes use of AVR family

microcontroller, LCD screen, Wi-Fi modem for sending data and a buzzer. The

system is powered by a 12V transformer. The LCD screen is used to display the status

of the level of garbage collected in the bins.

Whereas a web page is built to show the status to the user monitoring it. The

web page gives a graphical view of the garbage bins and highlights the garbage

collected in color in order to show the level of garbage collected. The LCD screen

shows the status of the garbage level. The system puts on the buzzer when the level of

garbage collected crosses the set limit. Thus this system helps to keep the city clean by

informing about the garbage levels of the bins by providing status of the bins via a

thingspeak server.

5
Block Diagram:

6
Hardware Specifications

 AVR family microcontroller


 Wi-Fi Modem esp8266
 LED’s
 LCD Display
 12V transformer
 Ultrasonic sensors
 Resistors
 Capacitors
 Diodes

Software Specifications

 Arduino compiler
 Iot sever thingspeak
 MC Programming Language: Embedded C

7
ARDUINO UNO R3

8
ARDUINO
ARDUINO UNO R3:

The Arduino Uno is a version of the Arduino Uno, but uses an surface mount
version of the Atmega328P instead of the through-hole version. This version
was made in response to a shortage in supply of the through-hole Atmega328P.
The board is based on the ATmega328 (datasheet). It has 14 digital input/output
pins (of which 6 can be used as PWM outputs), 6 analog inputs, a 16 MHz
crystal oscillator, a USB connection, a power jack, an ICSP header, and a reset
button. It contains everything needed to support the microcontroller; simply
connect it to a computer with a USB cable or power it with a AC-to-DC adapter
or battery to get started.

9
Summary

Microcontroller ATmega328

Operating Voltage 5V

Input Voltage (recommended) 7-12V

Input Voltage (limits) 6-20V

Digital I/O Pins 14 (of which 6 provide PWM output)

Analog Input Pins 6

DC Current per I/O Pin 40 mA

DC Current for 3.3V Pin 50 mA

Flash Memory 32 KB (ATmega328) of which 0.5 KB used by bootloader

SRAM 2 KB (ATmega328)

EEPROM 1 KB (ATmega328)

Clock Speed16 MHz

Schematic & Reference Design

10
CIRCUIT:

Power

The Arduino Uno can be powered via the USB connection or with an external
power supply. The power source is selected automatically.

External (non-USB) power can come either from an AC-to-DC adapter (wall-
wart) or battery. The adapter can be connected by plugging a 2.1mm center-
positive plug into the board's power jack. Leads from a battery can be inserted
in the Gnd and Vin pin headers of the POWER connector.
11
The board can operate on an external supply of 6 to 20 volts. If supplied with
less than 7V, however, the 5V pin may supply less than five volts and the board
may be unstable. If using more than 12V, the voltage regulator may overheat
and damage the board. The recommended range is 7 to 12 volts.

The power pins are as follows:

VIN. The input voltage to the Arduino board when it's using an external
power source (as opposed to 5 volts from the USB connection or other regulated
power source). You can supply voltage through this pin, or, if supplying voltage
via the power jack, access it through this pin.

5V. The regulated power supply used to power the microcontroller and other
components on the board. This can come either from VIN via an on-board
regulator, or be supplied by USB or another regulated 5V supply.

3V3. A 3.3 volt supply generated by the on-board regulator. Maximum


current draw is 50 mA.

GND. Ground pins.

Memory

12
The ATmega328 has 32 KB (with 0.5 KB used for the bootloader). It also has 2
KB of SRAM and 1 KB of EEPROM (which can be read and written with the
EEPROM library).

Input and Output

Each of the 14 digital pins on the Uno can be used as an input or output, using
pinMode(), digitalWrite(), and digitalRead() functions. They operate at 5 volts.
Each pin can provide or receive a maximum of 40 mA and has an internal pull-
up resistor (disconnected by default) of 20-50 kOhms. In addition, some pins
have specialized functions:

Serial: 0 (RX) and 1 (TX). Used to receive (RX) and transmit (TX) TTL
serial data. These pins are connected to the corresponding pins of the
ATmega8U2 USB-to-TTL Serial chip.

External Interrupts: 2 and 3. These pins can be configured to trigger an


interrupt on a low value, a rising or falling edge, or a change in value. See the
attachInterrupt() function for details.

PWM: 3, 5, 6, 9, 10, and 11. Provide 8-bit PWM output with the
analogWrite() function.

SPI: 10 (SS), 11 (MOSI), 12 (MISO), 13 (SCK). These pins support SPI


communication using the SPI library.

LED: 13. There is a built-in LED connected to digital pin 13. When the pin is
HIGH value, the LED is on, when the pin is LOW, it's off.

13
The Uno has 6 analog inputs, labeled A0 through A5, each of which provide 10
bits of resolution (i.e. 1024 different values). By default they measure from
ground to 5 volts, though is it possible to change the upper end of their range
using the AREF pin and the analogReference() function. Additionally, some
pins have specialized functionality:

I2C: A4 (SDA) and A5 (SCL). Support I2C (TWI) communication using the
Wire library.

There are a couple of other pins on the board:

AREF. Reference voltage (0 to 5V only) for the analog inputs. Used with
analogReference().

Reset. Bring this line LOW to reset the microcontroller. Typically used to add
a reset button to shields which block the one on the board.

See also the mapping between Arduino pins and ATmega328 ports.

Communication

The Arduino Uno has a number of facilities for communicating with a


computer, another Arduino, or other microcontrollers. The ATmega328
provides UART TTL (5V) serial communication, which is available on digital
14
pins 0 (RX) and 1 (TX). An ATmega8U2 on the board channels this serial
communication over USB and appears as a virtual com port to software on the
computer. The '8U2 firmware uses the standard USB COM drivers, and no
external driver is needed. However, on Windows, a .inf file is required. The
Arduino software includes a serial monitor which allows simple textual data to
be sent to and from the Arduino board. The RX and TX LEDs on the board will
flash when data is being transmitted via the USB-to-serial chip and USB
connection to the computer (but not for serial communication on pins 0 and 1).

A SoftwareSerial library allows for serial communication on any of the Uno's


digital pins.

The ATmega328 also supports I2C (TWI) and SPI communication. The
Arduino software includes a Wire library to simplify use of the I2C bus; see the
documentation for details. For SPI communication, use the SPI library.

Programming

The Arduino Uno can be programmed with the Arduino software (download).
Select "Arduino Uno from the Tools > Board menu (according to the
microcontroller on your board). For details, see the reference and tutorials.

The ATmega328 on the Arduino Uno comes preburned with a bootloader that
allows you to upload new code to it without the use of an external hardware

15
programmer. It communicates using the original STK500 protocol (reference, C
header files).

You can also bypass the bootloader and program the microcontroller through
the ICSP (In-Circuit Serial Programming) header; see these instructions for
details.

The ATmega8U2 firmware source code is available . The ATmega8U2 is


loaded with a DFU bootloader. The Uno SMD has a pulldown resistor tying the
HWB pin to ground, so all that's needed to enter DFU mode is to briefly short
enough to short pins 5 and 6 of the 8U2 icsp connector. This will connect the
8U2 reset pin to ground. You can then use Atmel's FLIP software (Windows) or
the DFU programmer (Mac OS X and Linux) to load a new firmware. Or you
can use the ISP header with an external programmer (overwriting the DFU
bootloader). See this user-contributed tutorial for more information.

Automatic (Software) Reset

Rather than requiring a physical press of the reset button before an upload, the
Arduino Uno is designed in a way that allows it to be reset by software running
on a connected computer. One of the hardware flow control lines (DTR) of the
ATmega8U2 is connected to the reset line of the ATmega328 via a 100
nanofarad capacitor. When this line is asserted (taken low), the reset line drops
long enough to reset the chip. The Arduino software uses this capability to
allow you to upload code by simply pressing the upload button in the Arduino

16
environment. This means that the bootloader can have a shorter timeout, as the
lowering of DTR can be well-coordinated with the start of the upload.

This setup has other implications. When the Uno is connected to either a
computer running Mac OS X or Linux, it resets each time a connection is made
to it from software (via USB). For the following half-second or so, the
bootloader is running on the Uno. While it is programmed to ignore malformed
data (i.e. anything besides an upload of new code), it will intercept the first few
bytes of data sent to the board after a connection is opened. If a sketch running
on the board receives one-time configuration or other data when it first starts,
make sure that the software with which it communicates waits a second after
opening the connection and before sending this data.

The Uno contains a trace that can be cut to disable the auto-reset. The pads on
either side of the trace can be soldered together to re-enable it. It's labeled
"RESET-EN". You may also be able to disable the auto-reset by connecting a
110 ohm resistor from 5V to the reset line; see this forum thread for details.

USB Overcurrent Protection

The Arduino Uno has a resettable polyfuse that protects your computer's USB
ports from shorts and overcurrent. Although most computers provide their own
internal protection, the fuse provides an extra layer of protection. If more than
500 mA is applied to the USB port, the fuse will automatically break the
connection until the short or overload is removed.

Physical Characteristics
17
The maximum length and width of the Uno PCB are 2.7 and 2.1 inches
respectively, with the USB connector and power jack extending beyond the
former dimension. Four screw holes allow the board to be attached to a surface
or case. Note that the distance between digital pins 7 and 8 is 160 mil (0.16"),
not an even multiple of the 100 mil spacing of the other pins.

18
ESP8266 WIFI MODULE

19
ESP8266 ARDUINO CORE

ESP8266 module is a microcontroller board with Wi-Fi capability which is


designed to operate as a standalone device as well as a slave device when it
is connected to a microcontroller (master).

Beginners may think ESP8266 module is a slave device and need a


microcontroller to make it functional, but this is not always true. The ESP8266
can operate as a standalone device as it sport a 32-bit microcontroller chip,
RAM, GPIO pins and a flash memory which can be programmed using Arduino
IDE.

But this module have only two GPIO pins and may limit our number of sensors
and peripherals which we may connect to it. If you are going to connect one or
two (max) sensors then you may not need any additional microcontroller to
support the sensors, you can directly add the library files (if necessary) and
write a code just as you do for any arduino boards.

As we need more than two pins for the sensors, we are using the ESP8266 as a
slave device; this is done by uploading a program code to ESP8266 which will
accept serial data from arduino. We will see how to upload the code to ESP8266
using Arduino Uno board in detail later part of this article.

Specifications:

 ESP8266 module has its own SoC or system on chip, it utilizes Tensilica
L106 32-bit processor clocked at 80MHz.
 It has 32KB instruction RAM, 32KB instruction cache RAM, 80KB user
data RAM and 16 KBETS system data RAM.
 It can operate from 2.5V to 3.6V (nominal 3.3V) and 5V will kill the
board. It has average current consumption about 80mA.
 It supports 802.11n (2.4 GHz) and can communicate with a speed of 72.2
Mbps (max).
 It supports these network protocols: IPv4, TCP/UDP/HTTP.

20
Pin Diagram of ESP8266:

21
16x2 LCD

22
16x2 LCD Description:

Standard HD44780 LCDs are useful for creating standalone projects.

* 16 characters wide, 2 rows

* White text on blue background

* Connection port is 0.1" pitch, single row for easy bread boarding and
wiring

* Pins are documented on the back of the LCD to assist in wiring it up

* Single LED backlight included can be dimmed easily with a resistor or


PWM and uses much less power than LCD with EL (electroluminescent)
backlights

* Can be fully controlled with only 6 digital lines! (Any analog/digital pins
can be used)

* Built in character set supports most English/European/Japanese text, see the


HD44780 datasheet for the full character set

23
* Up to 8 extra characters can be created for custom glyphs or 'foreign'
language support

A 16x2 LCD means it can display 16 characters per line and there are 2 such
lines. In this LCD each character is displayed in 5x7 pixel matrix. This LCD has
two registers.

1. Command/Instruction Register- stores the command instructions given to

the LCD. A command is an instruction given to LCD to do a predefined task

like initializing, clearing the screen, setting the cursor position, controlling

display etc.

2. Data Register- stores the data to be displayed on the LCD. The data is the

ASCII value of the character to be displayed on the LCD.

Commonly used LCD Command codes:

Hex Command to LCD Instruction Register


Code

1 Clear screen display

2 Return home

4 Decrement cursor

6 Increment cursor

E Display ON, cursor blinking

80 Force the cursor to the beginning of the 1st line

C0 Force cursor to the beginning of the 2nd line

38 Use 2 lines and 5x7 matrix


24
The pin description of this module is given below.

Pin configuration:

Pin Symbol Description

1 VSS Ground 0V

2 VCC Main power supply +5 V

3 VEE Power supply to Contrast adjustment by providing a variable resistor


control contrast through VCC

4 RS Register Select RS=0 to select Command Register

RS=1 to select Data Register

5 R/W Read/write R/W=0 to write to the register

R/W=1 to read from the register

6 EN Enable A high to low pulse (minimum 450ns wide) is


given when data is sent to data pins

7 DB0

8 DB1
To display letters or
9 DB2 numbers, their ASCII
10 DB3 codes are sent to data 8-bit data pins
pins (with RS=1).
11 DB4 Also instruction
12 DB5 command codes are
sent to these pins.
13 DB6

14 DB7

15 Led+ Backlight VCC +5 V

25
16 Led- Backlight Ground 0V

Programming the LCD:

1. Data pin8 (DB7) of the LCD is busy flag and is read when R/W = 1 & RS =

0. When busy flag=1, it means that LCD is not ready to accept data since it is

busy with the internal operations. Therefore before passing any data to LCD, its

command register should be read and busy flag should be checked.

2. To send data on the LCD, data is first written to the data pins with R/W = 0

(to specify the write operation) and RS = 1 (to select the data register). A high

to low pulse is given at EN pin when data is sent. Each write operation is

performed on the positive edge of the Enable signal.

3. To send a command on the LCD, a particular command is first specified to

the data pins with R/W = 0 (to specify the write operation) and RS = 0 (to select

the command register). A high to low pulse is given at EN pin when data is sent.

Displaying single character ‘A’ on LCD

The LCD is interfaced with microcontroller (AT89S52). This microcontroller

has 40 pins with four 8-bit ports (P0, P1, P2, and P3). Here P1 is used as output

port which is connected to data pins of the LCD. The control pins (pin 4-6) are

controlled by pins 2-4 of P0 port. Pin 3 is connected to a preset of 10k? to adjust

26
the contrast on LCD screen. This program uses the above concepts of

interfacing the LCD with controller by displaying the character ‘A’ on it.

27
ULTRASONIC SENSOR

28
HC-SR04 Ultrasonic Distance Sensor

HC-SR04 Ultrasonic Distance Sensor that can report the range of objects
up to 13 feet away. This is a good thing to know when you’re trying to save
your robot from hitting a wall.

They are low power (suitable for battery operated devices), affordable, easy to
interface and extremely popular with hobbyists.

What is Ultrasound?

Ultrasound is a high-pitched sound wave whose frequency exceeds the audible


range of human hearing.

Humans can hear sound waves that vibrate in the range of about 20 times a
second (a deep rumbling noise) to 20,000 times a second (a high-pitched
whistle). However, ultrasound has a frequency of more than 20,000 Hz and is
therefore inaudible to humans.

HC-SR04 Hardware Overview

An HC-SR04 ultrasonic distance sensor actually consists of two ultrasonic


transducers.

One acts as a transmitter that converts the electrical signal into 40 KHz
ultrasonic sound pulses. The other acts as a receiver and listens for the
transmitted pulses.

When the receiver receives these pulses, it produces an output pulse whose
width is proportional to the distance of the object in front.

This sensor provides excellent non-contact range detection between 2 cm to 400


cm (~13 feet) with an accuracy of 3 mm.

29
Since it operates on 5 volts, it can be connected directly to an Arduino or any
other 5V logic microcontroller.

Technical Specifications

Here are the specifications:

Operating Voltage DC 5V

Operating Current 15mA

Operating Frequency 40KHz

Max Range 4m

Min Range 2cm

Ranging Accuracy 3mm

Measuring Angle 15 degree

Trigger Input Signal 10µS TTL pulse

Dimension 45 x 20 x 15mm

HC-SR04 Ultrasonic Sensor Pinout

Let’s take a look at its


pinout.

VCC supplies power to the HC-SR04 ultrasonic sensor. You can connect it to
the 5V output from your Arduino.

30
Trig (Trigger) pin is used to trigger ultrasonic sound pulses. By setting this pin
to HIGH for 10µs, the sensor initiates an ultrasonic burst.

Echo pin goes high when the ultrasonic burst is transmitted and remains high
until the sensor receives an echo, after which it goes low. By measuring the time
the Echo pin stays high, the distance can be calculated.

GND is the ground pin. Connect it to the ground of the Arduino.

How Does HC-SR04 Ultrasonic Distance Sensor Work?

It all starts when the trigger pin is set HIGH for 10µs. In response, the sensor
transmits an ultrasonic burst of eight pulses at 40 kHz. This 8-pulse pattern is
specially designed so that the receiver can distinguish the transmitted pulses
from ambient ultrasonic noise.

These eight ultrasonic pulses travel through the air away from the transmitter.
Meanwhile the echo pin goes HIGH to initiate the echo-back signal.

If those pulses are not reflected back, the echo signal times out and goes low
after 38ms (38 milliseconds). Thus a pulse of 38ms indicates no obstruction
within the range of the sensor.

If those pulses are reflected back, the echo pin goes low as soon as the signal is
received. This generates a pulse on the echo pin whose width varies from 150
µs to 25 ms depending on the time taken to receive the signal.

31
Calculating the Distance

The width of the received pulse is used to calculate the distance from the
reflected object. This can be worked out using the simple distance-speed-time
equation we learned in high school. An easy way to remember the equation is to
put the letters in a triangle.

Let us take an example to make it more clear. Suppose we have an object in


front of the sensor at an unknown distance and we receive a pulse of 500µs
width on the echo pin. Now let’s calculate how far the object is from the sensor.
For this we will use the below equation.

Distance = Speed x Time

Here we have the value of time i.e. 500 µs and we know the speed. Of course
it’s the speed of sound! It is 340 m/s. To calculate the distance we need to

32
convert the speed of sound into cm/µs. It is 0.034 cm/μs. With that information
we can now calculate the distance!

Distance = 0.034 cm/µs x 500 µs

But we’re not done yet! Remember that the echo pulse indicates the time it
takes for the signal to be sent and reflected back. So to get the distance, you
have to divide your result by two.

Distance = (0.034 cm/µs x 500 µs) / 2

Distance = 8.5 cm

Now we know that the object is 8.5 cm away from the sensor.

Wiring an HC-SR04 Sensor to an Arduino

Now that we have a complete understanding of how the HC-SR04 ultrasonic


sensor works we can start connecting it to our Arduino!

Connecting the HC-SR04 to Arduino is very easy. Start by placing the sensor on
your breadboard. Connect the VCC pin to the 5V pin on the Arduino and the
GND pin to the ground pin. Now connect the trig and echo pins to digital pins
#9 and #10 respectively.

The following table lists the pin connections:

HC-SR04 Sensor Arduino

VCC 5V

Trig 9

Echo 10

GND GND

33
BUZZER

34
BUZZER

A buzzer or beeper is an audio signaling device, which may be


mechanical, electromechanical, or electronic. Typical uses of buzzers and
beepers include alarms, timers and confirmation of user input such as a mouse
click or keystroke.A piezoelectric element may be driven by an oscillating
electronic circuit or other audio signal source. Sounds commonly used to
indicate that a button has been pressed are a click, a ring or a beep. Electronic
buzzers find many applications in modern [Link] Lead Buzzers for
external mounting, ideal for robots and alarm systems. Available in both AC
and DC types, with sound output up to 110dB.

In our project the buzzer is used to create audible warning.

POWER SUPPLY:

35
The power supply circuits built using filters, rectifiers, and then voltage regulators. Starting
with an ac voltage, a steady dc voltage is obtained by rectifying the ac voltage, then filtering to a dc
level, and finally, regulating to obtain a desired fixed dc voltage. The regulation is usually obtained
from an IC voltage regulator unit, which takes a dc voltage and provides a somewhat lower dc
voltage, which remains the same even if the input dc voltage varies, or the output load connected to
the dc voltage changes. The block diagram of power supply is shown in fig below.

AC I/P

TransformerRectifier Filter Regulator Load

Block diagram of power supply

Transformer

The potential transformer will step down the power supply voltage (0-230V) to (0-6V) level.
Then the secondary of the potential transformer will be connected to the precision rectifier, which is
constructed with the help of op–amp. The advantages of using precision rectifier are it will give peak
voltage output as DC, rest of the circuits will give only RMS output.

Bridge rectifier

Bridge rectifier is used to maintain the proper DC polarity at the input to the circuit,
irrespective of telephone line polarity. It comprises of four diodes connected to form a bridge. It uses
the entire AC wave (both positive and negative sections). 1.4V is used up in the bridge rectifier
because each diode uses 0.7V when conducting and there are always two diodes conducting, as shown
in fig below.

36
[Link] Voltage Regulators:

Voltage regulators comprise a class of widely used ICs. Regulator IC units contain the
circuitry for reference source, comparator amplifier, control device, and overload protection
all in a single IC. Although the internal construction of the IC is somewhat different from that
described for discrete voltage regulator circuits, the external operation is much the same. IC
units provide regulation of either a fixed positive voltage, a fixed negative voltage, or an
adjustably set voltage.

[Link] terminal Voltage Regulators:

Fig shows the basic connection of a three-terminal voltage regulator IC to a load. The fixed
voltage regulator has an unregulated dc input voltage, V in, applied to one input terminal, a regulated
output dc voltage, Vout, from a second terminal, with the third terminal connected to ground.

IN OUT

Secondary Vin 7805

GND

37
ARDUINO IDE

38
39
ARDUINO SOFTWARE (IDE)

The Arduino Integrated Development Environment - or Arduino Software


(IDE) - contains a text editor for writing code, a message area, a text console, a
toolbar with buttons for common functions and a series of menus. It connects to
the Arduino and Genuino hardware to upload programs and communicate with
them.

Writing Sketches

Programs written using Arduino Software (IDE) are called sketches. These
sketches are written in the text editor and are saved with the file extension .ino.
The editor has features for cutting/pasting and for searching/replacing text. The
message area gives feedback while saving and exporting and also displays
errors. The console displays text output by the Arduino Software (IDE),
including complete error messages and other information. The bottom righthand
corner of the window displays the configured board and serial port. The toolbar
buttons allow you to verify and upload programs, create, open, and save
sketches, and open the serial monitor.

NB: Versions of the Arduino Software (IDE) prior to 1.0 saved sketches
with the extension .pde. It is possible to open these files with version 1.0,
you will be prompted to save the sketch with the .ino extension on save.

Verify
Checks your code for errors compiling it.
Upload
Compiles your code and uploads it to the configured board. See uploading
below for details.

Note: If you are using an external programmer with your board, you can
hold down the "shift" key on your computer when using this icon. The text
will change to "Upload using Programmer"
New
Creates a new sketch.
Open
Presents a menu of all the sketches in your sketchbook. Clicking one will
open it within the current window overwriting its content.

Note: due to a bug in Java, this menu doesn't scroll; if you need to open a
sketch late in the list, use the File | Sketchbook menu instead.
Save
40
Saves your sketch.
Serial Monitor
Opens the serial monitor.

Additional commands are found within the five menus: File, Edit, Sketch,
Tools, Help. The menus are context sensitive, which means only those items
relevant to the work currently being carried out are available.

File

 New
Creates a new instance of the editor, with the bare minimum structure of a
sketch already in place.
 Open
Allows to load a sketch file browsing through the computer drives and
folders.
 Open Recent
Provides a short list of the most recent sketches, ready to be opened.
 Sketchbook
Shows the current sketches within the sketchbook folder structure;
clicking on any name opens the corresponding sketch in a new editor
instance.
 Examples
Any example provided by the Arduino Software (IDE) or library shows
up in this menu item. All the examples are structured in a tree that allows
easy access by topic or library.
 Close
Closes the instance of the Arduino Software from which it is clicked.
 Save
Saves the sketch with the current name. If the file hasn't been named
before, a name will be provided in a "Save as.." window.
 Save as...
Allows to save the current sketch with a different name.
 Page Setup
It shows the Page Setup window for printing.
 Print
Sends the current sketch to the printer according to the settings defined in
Page Setup.
 Preferences
Opens the Preferences window where some settings of the IDE may be
customized, as the language of the IDE interface.

41
 Quit
Closes all IDE windows. The same sketches open when Quit was chosen
will be automatically reopened the next time you start the IDE.

Edit

 Undo/Redo
Goes back of one or more steps you did while editing; when you go back,
you may go forward with Redo.
 Cut
Removes the selected text from the editor and places it into the clipboard.
 Copy
Duplicates the selected text in the editor and places it into the clipboard.
 Copy for Forum
Copies the code of your sketch to the clipboard in a form suitable for
posting to the forum, complete with syntax coloring.
 Copy as HTML
Copies the code of your sketch to the clipboard as HTML, suitable for
embedding in web pages.
 Paste
Puts the contents of the clipboard at the cursor position, in the editor.
 Select All
Selects and highlights the whole content of the editor.
 Comment/Uncomment
Puts or removes the // comment marker at the beginning of each selected
line.
 Increase/Decrease Indent
Adds or subtracts a space at the beginning of each selected line, moving
the text one space on the right or eliminating a space at the beginning.
 Find
Opens the Find and Replace window where you can specify text to search
inside the current sketch according to several options.
 Find Next
Highlights the next occurrence - if any - of the string specified as the
search item in the Find window, relative to the cursor position.
 Find Previous
Highlights the previous occurrence - if any - of the string specified as the
search item in the Find window relative to the cursor position.

Sketch

42
 Verify/Compile
Checks your sketch for errors compiling it; it will report memory usage
for code and variables in the console area.
 Upload
Compiles and loads the binary file onto the configured board through the
configured Port.
 Upload Using Programmer
This will overwrite the bootloader on the board; you will need to use
Tools > Burn Bootloader to restore it and be able to Upload to USB serial
port again. However, it allows you to use the full capacity of the Flash
memory for your sketch. Please note that this command will NOT burn
the fuses. To do so a Tools -> Burn Bootloader command must be
executed.
 Export Compiled Binary
Saves a .hex file that may be kept as archive or sent to the board using
other tools.
 Show Sketch Folder
Opens the current sketch folder.
 Include Library
Adds a library to your sketch by inserting #include statements at the start
of your code. For more details, see libraries below. Additionally, from
this menu item you can access the Library Manager and import new
libraries from .zip files.
 Add File...
Adds a source file to the sketch (it will be copied from its current
location). The new file appears in a new tab in the sketch window. Files
can be removed from the sketch using the tab menu accessible clicking on
the small triangle icon below the serial monitor one on the right side o the
toolbar.

Tools

 Auto Format
This formats your code nicely: i.e. indents it so that opening and closing
curly braces line up, and that the statements inside curly braces are
indented more.
 Archive Sketch
Archives a copy of the current sketch in .zip format. The archive is placed
in the same directory as the sketch.
 Fix Encoding & Reload
Fixes possible discrepancies between the editor char map encoding and
other operating systems char maps.
43
 Serial Monitor
Opens the serial monitor window and initiates the exchange of data with
any connected board on the currently selected Port. This usually resets the
board, if the board supports Reset over serial port opening.
 Board
Select the board that you're using. See below for descriptions of the
various boards.
 Port
This menu contains all the serial devices (real or virtual) on your
machine. It should automatically refresh every time you open the top-
level tools menu.
 Programmer
For selecting a harware programmer when programming a board or chip
and not using the onboard USB-serial connection. Normally you won't
need this, but if you're burning a bootloader to a new microcontroller, you
will use this.
 Burn Bootloader
The items in this menu allow you to burn a bootloader onto the
microcontroller on an Arduino board. This is not required for normal use
of an Arduino or Genuino board but is useful if you purchase a new
ATmega microcontroller (which normally come without a bootloader).
Ensure that you've selected the correct board from the Boards menu
before burning the bootloader on the target board. This command also set
the right fuses.

Help

Here you find easy access to a number of documents that come with the
Arduino Software (IDE). You have access to Getting Started, Reference, this
guide to the IDE and other documents locally, without an internet connection.
The documents are a local copy of the online ones and may link back to our
online website.

 Find in Reference
This is the only interactive function of the Help menu: it directly selects
the relevant page in the local copy of the Reference for the function or
command under the cursor.

Sketchbook

The Arduino Software (IDE) uses the concept of a sketchbook: a standard place
to store your programs (or sketches). The sketches in your sketchbook can be
opened from the File > Sketchbook menu or from the Open button on the
44
toolbar. The first time you run the Arduino software, it will automatically create
a directory for your sketchbook. You can view or change the location of the
sketchbook location from with the Preferences dialog.

Beginning with version 1.0, files are saved with a .ino file extension.
Previous versions use the .pde extension. You may still open .pde named
files in version 1.0 and later, the software will automatically rename the
extension to .ino.

Tabs, Multiple Files, and Compilation

Allows you to manage sketches with more than one file (each of which appears
in its own tab). These can be normal Arduino code files (no visible extension),
C files (.c extension), C++ files (.cpp), or header files (.h).

Uploading

Before uploading your sketch, you need to select the correct items from the
Tools > Board and Tools > Port menus. The boards are described below. On
the Mac, the serial port is probably something like /dev/tty.usbmodem241 (for
an Uno or Mega2560 or Leonardo) or /dev/[Link]-1B1 (for a
Duemilanove or earlier USB board), or /dev/tty.USA19QW1b1P1.1 (for a
serial board connected with a Keyspan USB-to-Serial adapter). On Windows,
it's probably COM1 or COM2 (for a serial board) or COM4, COM5, COM7,
or higher (for a USB board) - to find out, you look for USB serial device in the
ports section of the Windows Device Manager. On Linux, it should be
/dev/ttyACMx,/dev/ttyUSBx or similar. Once you've selected the correct serial
port and board, press the upload button in the toolbar or select the Upload item
from the Sketch menu. Current Arduino boards will reset automatically and
begin the upload. With older boards (pre-Diecimila) that lack auto-reset, you'll
need to press the reset button on the board just before starting the upload. On
most boards, you'll see the RX and TX LEDs blink as the sketch is uploaded.
The Arduino Software (IDE) will display a message when the upload is
complete, or show an error.

When you upload a sketch, you're using the Arduinobootloader, a small


program that has been loaded on to the microcontroller on your board. It allows
you to upload code without using any additional hardware. The bootloader is
active for a few seconds when the board resets; then it starts whichever sketch
was most recently uploaded to the microcontroller. The bootloader will blink
the on-board (pin 13) LED when it starts (i.e. when the board resets).

Libraries
45
Libraries provide extra functionality for use in sketches, e.g. working with
hardware or manipulating data. To use a library in a sketch, select it from the
Sketch > Import Library menu. This will insert one or more #include
statements at the top of the sketch and compile the library with your sketch.
Because libraries are uploaded to the board with your sketch, they increase the
amount of space it takes up. If a sketch no longer needs a library, simply delete
its #include statements from the top of your code.

There is a list of libraries in the reference. Some libraries are included with the
Arduino software. Others can be downloaded from a variety of sources or
through the Library Manager. Starting with version 1.0.5 of the IDE, you do can
import a library from a zip file and use it in an open sketch. See these
instructions for installing a third-party library.

To write your own library, see this tutorial.

Third-Party Hardware

Support for third-party hardware can be added to the hardware directory of


your sketchbook directory. Platforms installed there may include board
definitions (which appear in the board menu), core libraries, bootloaders, and
programmer definitions. To install, create the hardware directory, then unzip
the third-party platform into its own sub-directory. (Don't use "arduino" as the
sub-directory name or you'll override the built-in Arduino platform.) To
uninstall, simply delete its directory.

For details on creating packages for third-party hardware, see the Arduino IDE
1.5 3rd party Hardware specification.

Serial Monitor

This displays serial sent from the Arduino or Genuino board over USB or serial
connector. To send data to the board, enter text and click on the "send" button or
press enter. Choose the baud rate from the drop-down menu that matches the
rate passed to [Link] in your sketch. Note that on Windows, Mac or Linux
the board will reset (it will rerun your sketch) when you connect with the serial
monitor. Please note that the Serial Monitor does not process control characters;
if your sketch needs a complete management of the serial communication with
control characters, you can use an external terminal program and connect it to
the COM port assigned to your Arduino board.

You can also talk to the board from Processing, Flash, MaxMSP, etc (see the
interfacing page for details).
46
Preferences

Some preferences can be set in the preferences dialog (found under the Arduino
menu on the Mac, or File on Windows and Linux). The rest can be found in the
preferences file, whose location is shown in the preference dialog.

Language Support

Since version 1.0.1 , the Arduino Software (IDE) has been translated into 30+
different languages. By default, the IDE loads in the language selected by your
operating system. (Note: on Windows and possibly Linux, this is determined by
the locale setting which controls currency and date formats, not by the language
the operating system is displayed in.)

If you would like to change the language manually, start the Arduino Software
(IDE) and open the Preferences window. Next to the Editor Language there is
a dropdown menu of currently supported languages. Select your preferred
language from the menu, and restart the software to use the selected language. If
your operating system language is not supported, the Arduino Software (IDE)
will default to English.
47
You can return the software to its default setting of selecting its language based
on your operating system by selecting System Default from the Editor
Language drop-down. This setting will take effect when you restart the
Arduino Software (IDE). Similarly, after changing your operating system's
settings, you must restart the Arduino Software (IDE) to update it to the new
default language.

Boards

The board selection has two effects: it sets the parameters (e.g. CPU speed and
baud rate) used when compiling and uploading sketches; and sets and the file
and fuse settings used by the burn bootloader command. Some of the board
definitions differ only in the latter, so even if you've been uploading
successfully with a particular selection you'll want to check it before burning the
bootloader. You can find a comparison table between the various boards here.

Arduino Software (IDE) includes the built in support for the boards in the
following list, all based on the AVR Core. The Boards Manager included in the
standard installation allows to add support for the growing number of new
boards based on different cores like Arduino Due, Arduino Zero, Edison,
Galileo and so on.

 ArduinoYùn
An ATmega32u4 running at 16 MHz with auto-reset, 12 Analog In, 20
Digital I/O and 7 PWM.
 Arduino/Genuino Uno
An ATmega328P running at 16 MHz with auto-reset, 6 Analog In, 14
Digital I/O and 6 PWM.
 ArduinoDiecimila or Duemilanove w/ ATmega168
An ATmega168 running at 16 MHz with auto-reset.
 Arduino Nano w/ ATmega328P
An ATmega328P running at 16 MHz with auto-reset. Has eight analog
inputs.
 Arduino/Genuino Mega 2560
An ATmega2560 running at 16 MHz with auto-reset, 16 Analog In, 54
Digital I/O and 15 PWM.
 Arduino Mega
An ATmega1280 running at 16 MHz with auto-reset, 16 Analog In, 54
Digital I/O and 15 PWM.
 Arduino Mega ADK
An ATmega2560 running at 16 MHz with auto-reset, 16 Analog In, 54
Digital I/O and 15 PWM.

48
 Arduino Leonardo
An ATmega32u4 running at 16 MHz with auto-reset, 12 Analog In, 20
Digital I/O and 7 PWM.
 Arduino/Genuino Micro
An ATmega32u4 running at 16 MHz with auto-reset, 12 Analog In, 20
Digital I/O and 7 PWM.
 ArduinoEsplora
An ATmega32u4 running at 16 MHz with auto-reset.
 Arduino Mini w/ ATmega328P
An ATmega328P running at 16 MHz with auto-reset, 8 Analog In, 14
Digital I/O and 6 PWM.
 Arduino Ethernet
Equivalent to Arduino UNO with an Ethernet shield: An ATmega328P
running at 16 MHz with auto-reset, 6 Analog In, 14 Digital I/O and 6
PWM.
 ArduinoFio
An ATmega328P running at 8 MHz with auto-reset. Equivalent to
Arduino Pro or Pro Mini (3.3V, 8 MHz) w/ ATmega328P, 6 Analog In,
14 Digital I/O and 6 P

 WM.
 Arduino BT w/ ATmega328P
ATmega328P running at 16 MHz. The bootloader burned (4 KB)
includes codes to initialize the on-board bluetooth module, 6 Analog In,
14 Digital I/O and 6 PWM..
 LilyPadArduino USB
An ATmega32u4 running at 8 MHz with auto-reset, 4 Analog In, 9
Digital I/O and 4 PWM.
 LilyPadArduino
An ATmega168 or ATmega132 running at 8 MHz with auto-reset, 6
Analog In, 14 Digital I/O and 6 PWM.
 Arduino Pro or Pro Mini (5V, 16 MHz) w/ ATmega328P
An ATmega328P running at 16 MHz with auto-reset. Equivalent to
ArduinoDuemilanove or Nano w/ ATmega328P; 6 Analog In, 14 Digital
I/O and 6 PWM.
 Arduino NG or older w/ ATmega168
An ATmega168 running at 16 MHz without auto-reset. Compilation and
upload is equivalent to ArduinoDiecimila or Duemilanove w/
ATmega168, but the bootloader burned has a slower timeout (and blinks
the pin 13 LED three times on reset); 6 Analog In, 14 Digital I/O and 6
PWM.

49
 Arduino Robot Control
An ATmega328P running at 16 MHz with auto-reset.
 Arduino Robot Motor
An ATmega328P running at 16 MHz with auto-reset.
 Arduino Gemma
An ATtiny85 running at 8 MHz with auto-reset, 1 Analog In, 3 Digital
I/O and 2 PWM.

50
CONNECT ESP8266 TO
THINGSPEAK

51
Connect ESP8266 to ThingSpeak

When makers and hobbyists think of Internet of Things (IoT), two things
come to their mind: one is ESP8266 and the other is ThingSpeak. One is the
Hardware part of the IoT System whereas the other provides the necessary API
(or the user interface) for the system. In this project, I’ll show you how to
Connect ESP8266 to ThingSpeak Application and how the ESP8266
ThingSpeak collaboration works.

Overview

We have already seen one such IoT implementation using ESP8266 and aREST
Platform. What makes ThingSpeak different and special is that is uses simple
HTTP Protocol to transfer, store and retrieve information from different sensors.

Also, the ThingSpeak Application allows us to log the sensor data, track
locations and even social networking of things.

Another important thing (or rather a unique feature) about ThingSpeak is its
support from MATLAB. The close relationship between ThingSpeak and
MATLAB has lead to integrate several key features of MATLAB into the
ThingSpeak Application.

One such feature is to analyse and visualize the user data i.e. the sensor data in a
graphical way without the MATLAB License.

Keeping the corporate stuff aside, the ThingSpeak Application is a great tool for
our IoT related projects and hence this project focuses on the basics i.e. how to
connect ESP8266 to ThingSpeak Application and also how the ESP8266
ThingSpeak Interface can be used in our future projects.

Creating ThingSpeak Account

The first thing you need to do is to create an account with ThingSpeak. Since
the collaboration with MATLAB, you can use your MathWorks credentials to
login to ThingSpeak using the Sign In link from this page: THINGSPEAK

52
If you do not have one, you need to create an account with MathWorks and
login to ThingSpeak Application.

NOTE: The MathWorks Account can be used for both MATLAB as well as
ThingSpeak logins.

After logging in, you need to create a new channel for the data to be stored. For
this go to Channels–>My Channels and click on New Channel.

Enter the name of the channel and name of Field 1 in the corresponding
sections. Fields in a channel are used to hold the data and each channel can have
up to 8 fields. After entering the details save the channel.

In my case, I’ve created a Channel called “Test Channel” and the Field 1 as
“Random Number”. You will see why in the later sections.

There are a few other things you need to do in the ThingSpeak Application, but
I’ll tell about it when you need it.
53
The next step is to prepare the hardware for the project, which includes
ESP8266 WiFi Module, Arduino UNO Board and a few connecting wires.

Prerequisites for the Project

I’ll show you two ways of how to connect ESP8266 to ThingSpeak Application.
For both the ways, you need to make sure that your ESP8266 Module is loaded
or flashed with AT Commands Firmware.

For more information on this, I suggest you to go through the procedure


mentioned in the project HOW TO UPDATE FLASH ESP8266
FIRMWARE.

NOTE:

 For flashing the AT Commands firmware, you need to enable the


programming mode in ESP8266 by connecting GPIO0 to GND and
resetting the module.
 But in this circuit (assuming you have already flashed the firmware), the
ESP Module is in Normal Mode i.e. GPIO0 can be left floating.

After flashing your ESP with AT Commands Firmware, you can now proceed
with connecting ESP8266 to ThingSpeak. As I said before, you can do this in
two ways: One is through AT Commands and the other way is through Arduino
(even this way uses AT Commands but Arduino controls them).

I’ll show you both ways to connect ESP8266 to ThingSpeak.

Circuit Diagram for ESP8266 ThingSpeak Interface through AT


Commands

The circuit diagram in order to connect ESP8266 to ThingSpeak is very simple.


In fact, you might have already seen this connection before. The Arduino UNO
Board is used just to transmit the data between the computer and the ESP8266
i.e. it acts as an USB-to-UART Converter.

54
Components Required

 Any Arduino Board or USB-to-UART Converter


 ESP8266 WiFi Module (ESP-01)
 Connecting Wires

Connect ESP8266 to ThingSpeak using AT Commands

Connect the Arduino board to the computer and open the serial monitor of
Arduino and check for connectivity using the following command.

AT

Note that I have set the baud rate to 115200 and also selected “Both NL & CR”
option in the Serial Monitor.

After you get a response as “OK”, you can proceed with connecting your ESP
Module to your WiFi Network using the following command.

AT+CWJAP=”SSID”,”PASSWORD”

Replace SSID with the name of your WiFi Network and enter the password in
place of [Link] will now get a confirmation response regarding
WiFi Connection as follows.

55
WIFI CONNECTED
WIFI GOT IP

OK

Now, you need to set single connection using the following command.

AT+CIPMUX=0

Next step is to connect to the ThingSpeak API using TCP Protocol. For this,
you need to use the following command.

AT+CIPSTART=”TCP”,”[Link]”,80

Alternatively, you can use the IP Address of the host [Link] i.e.
[Link].

AT+CIPSTART=”TCP”,”[Link]”,80

NOTE:
56
• After starting the TCP connection, if you don’t perform any action, the
connection will be closed automatically after some time, usually after 1 minute.

Now, you have successfully enabled the “TCP” connection between the
ESP8266 and ThingSpeak. Next, you can send any data through this TCP
Connection.

For this, use the following commands one after the other.

AT+CIPSEND=51

GET /update?api_key=XXXXXXXXXXXXXXXX&field1=255

AT+CIPCLOSE

Once the TCP connection is established, you can send data using certain
commands. This part can be a little tricky but trying it for a couple of times, you
will understand the process.

In order to send the data, you need send three different information: One is the
actual send command, next is the data along with the ThingSpeak Field Key and
finally the close connection command. I’ll try to explain these steps in a detailed
way as possible.

Before sending the data, you need to acquire the API Key. For this, go to you
channel (the one you have just created) and click on “API Keys” Tab. Below
that, you can find Write API Key, which is an alphanumeric string of 16
characters. Make a note of this key.

Now, use the following command to initialize the data transmission.

AT+CIPSEND=51

The value 51 is the length of the data to be transmitted. This includes the
complete data including the API Key and the “\r” and “\n” values. For this
command, you will get the following response.

OK

>

57
Now type the following information and hit send. Here,
“XXXXXXXXXXXXXXXX” is nothing but the 16 character Write API Key,
which you have just copied. And the number “143” is the actual data you are
transmitting to field1.

GET /update?api_key=XXXXXXXXXXXXXXXX&field1=143

After typing this text and hitting on send, you will not get any response. It is
actually waiting for the close command. Once you hit send for the above text,
immediately type the following command and hit send.

AT+CIPCLOSE

The moment you hit send, you will get the following response (not the exact
one, but something similar).

Recv 51 bytes

SEND OK

+IPD,1:5CLOSED

Here, the number 5 means, it is my 5TH message to that Key. Now, Open the
ThingSpeak API and open your channel. In the “Private View” tab, you can see
the value ‘143’ in the Field 1 Chart.

That’s it. If you understood and followed all these steps, then you might have
successfully connected ESP8266 to ThingSpeak API. To send more data, repeat
the steps from creating the TCP Connection.

Circuit Diagram for ESP8266 ThingSpeak Interface using Arduino

Since I’ll be programming the Arduino and controlling the ESP8266 through
Arduino, the circuit diagram will be slightly different. But the components will
be the same.

58
Connect ESP8266 to ThingSpeak using Arduino

Here comes Arduino to the rescue. Make all the connections as per the above
circuit diagram and we will proceed with the code.

Code

Use the following code to upload to Arduino. Note that you have make few
changes to the code. The changes will be regarding WiFi SSID, WiFi Password
and API Key (16 character). I think, rest of the values can be left as it is.

#include <SoftwareSerial.h> //Software Serial library


SoftwareSerialespSerial(2, 3); //Pin 2 and 3 act as RX and TX. Connect them to
TX and RX of ESP8266
#define DEBUG true
String mySSID = "SSID"; // WiFi SSID
59
String myPWD = "PASSWORD"; // WiFi Password
String myAPI = "XXXXXXXXXXXXXXXX"; // API Key
String myHOST = "[Link]";
String myPORT = "80";
String myFIELD = "field1";
intsendVal;
void setup()
{
[Link](9600);
[Link](115200);
espData("AT+RST", 1000, DEBUG); //Reset the ESP8266 module
espData("AT+CWMODE=1", 1000, DEBUG); //Set the ESP mode as station
mode
espData("AT+CWJAP=\""+ mySSID +"\",\""+ myPWD +"\"", 1000,
DEBUG); //Connect to WiFi network
/*while(![Link]("OK"))
{
//Wait for connection
}*/
delay(1000);
}
void loop()
{
/* Here, I'm using the function random(range) to send a random value to the
ThingSpeak API. You can change this value to any sensor data
so that the API will show the sensor data
*/
sendVal = random(1000); // Send a random number between 1 and 1000
String sendData = "GET /update?api_key="+ myAPI +"&"+ myFIELD
+"="+String(sendVal);
espData("AT+CIPMUX=1", 1000, DEBUG); //Allow multiple connections
espData("AT+CIPSTART=0,\"TCP\",\""+ myHOST +"\","+ myPORT, 1000,
DEBUG);
espData("AT+CIPSEND=0," +String([Link]()+4),1000,DEBUG);
[Link](">");
[Link](sendData);
[Link]("Value to be sent: ");
[Link](sendVal);
espData("AT+CIPCLOSE=0",1000,DEBUG);
60
delay(10000);
}
String espData(String command, constint timeout, boolean debug)
{
[Link]("AT Command ==> ");
[Link](command);
[Link](" ");
String response = "";
[Link](command);
long int time = millis();
while ( (time + timeout) >millis())
{
while ([Link]())
{
char c = [Link]();
response += c;
}
}
if (debug)
{
//[Link](response);
}
return response;
}

61
view rawESP8266_Connect_To_ThingSpeak.ino hosted with by GitHub

After uploading the code, if you open the serial monitor (baud rate set to 9600),
you can see the AT Commands being transmitted to the ESP8266 Module.

Initially, the AT Commands will setup the WiFi Connection to the ESP Module.
After enabling the connection, the Arduino will establish TCP connection to the
ThingSpeak API and transmits the random number for every 5 seconds.

This data can be monitored in the ThingSpeak API Website i.e. in the channel
you created (under the Private View tab).

62

You might also like