You are on page 1of 121

SBMA1501 - FUNDAMENTALS OF MICROPROCESSOR

AND MICROCONTROLLER

COURSE HANDLED BY

Dr.V.Vijaya Baskar
School of EEE,
Sathyabama Institute of Science and Technology,
Chennai.
Unit 5

UNIT 5 ARDUINO UNO

Arduino – Architecture, Pin diagram, Programming Structure, Simple program to


blink LED, Subroutine, 16x2 LED display,Interfacing with Arduino: LCD,
Temperature Sensor, Humidity Sensor and ultrasonic sensor
Arduino UNO Microcontroller
Arduino is a prototype platform (open-source) based on an easy-
to-use hardware and software. It consists of a circuit board, which
can be programed (referred to as a microcontroller) and a ready-
made software called Arduino IDE (Integrated Development
Environment), which isused to write and upload the computer
code to the physical board.
WHAT IS AN ARDUINO?

 Microcontroller-based prototyping kit


 Easy to use, low cost board for students, hobbyists &
professionals
 Many different board types and revisions exist
 Also – a software API and development environment
 Board layout and software is open source
The key features are −

 Arduino boards are able to read analog or digital input signals from different
sensors and turn it into an output such as activating a motor, turning LED
on/off, connect to the cloud and many other actions.
 You can control your board functions by sending a set of instructions to the
microcontroller on the board via Arduino IDE (referred to as uploading
software).
 Unlike most previous programmable circuit boards, Arduino does not need an
extra piece of hardware (called a programmer) in order to load a new code onto
the board. You can simply use a USB cable.
 Additionally, the Arduino IDE uses a simplified version of C++, making it easier
to learn to program.
Arduino Boards
• Various kinds of Arduino boards are available depending on
different microcontrollers used.
• Boards differ in Operating Voltage, clock speed, and number
of Digital I/O, Analog & PWM pins.
• All Arduino boards have one thing in common: they are
programmed through the Arduino IDE.
Arduino Boards
DIFFERENCE BETWEEN ARDUINO BOARDS

 Microcontroller used Memory


 Clock speed
 Available RAM
 # of and type of pins
 Digital
 Analog
 PWM
Board features
Arduino UNO Microcontroller
 we will learn about the different components on the Arduino
board.
 We will study the Arduino UNO board because it is the most
popular board in the Arduino board family.
 In addition, it is the best board to get started with electronics
and coding.
 Some boards look a bit different from this one, but most
Arduinos have majority of these components in common
TECHNOLOGY - UNO
 The Uno is one of the most popular Arduinos available
 Based on the Atmel ATmega328 microcontroller
 14 I/O pins
 USB & power connectors
 16MHz clock speed
Arduino Uno Board
Arduino Uno Board
Components of Arduino UNO Microcontroller

• Power (Barrel Jack)


• Power USB
• Crystal Oscillator
• Arduino Reset
• Analog pins
• Power LED indicator
• TX and RX LEDs
• Digital I/O
• AREF
• Vcc , GND, Vin
• Main microcontroller
Arduino UNO Architecture
1 Power USB
Arduino board can be powered by using the USB cable from your computer. All you
need to do is connect the USB cable to the USB connection (1).

Power (Barrel Jack)


2 Arduino boards can be powered directly from the AC mains power supply by
connecting it to the Barrel Jack (2).
Voltage Regulator
3 The function of the voltage regulator is to control the voltage given to the Arduino
board and stabilize the DC voltages used by the processor and other elements.
Crystal Oscillator
The crystal oscillator helps Arduino in dealing with time issues. How does Arduino
4 calculate time? The answer is, by using the crystal oscillator. The number printed on
top of the Arduino crystal is 16.000H9H. It tells us that the frequency is 16,000,000
Hertz or 16 MHz.
5,17
Arduino Reset
You can reset your Arduino board, i.e., start your program from the beginning. You can
reset the UNO board in two ways. First, by using the reset button (17) on the board.
Second, you can connect an external reset button to the Arduino pin labelled RESET (5).

Pins (3.3, 5, GND, Vin)


•3.3V (6) − Supply 3.3 output volt
•5V (7) − Supply 5 output volt
•Most of the components used with Arduino board works fine with 3.3 volt and 5 volt.
6,7,8 &9
•GND (8)(Ground) − There are several GND pins on the Arduino, any of which can be
used to ground your circuit.
•Vin (9) − This pin also can be used to power the Arduino board from an external power
source, like AC mains power supply.
Analog pins
The Arduino UNO board has six analog input pins A0 through A5. These pins can read
10
the signal from an analog sensor like the humidity sensor or temperature sensor and
convert it into a digital value that can be read by the microprocessor.

Main microcontroller
Each Arduino board has its own microcontroller (11). You can assume it as the brain of
your board. The main IC (integrated circuit) on the Arduino is slightly different from
11 board to board. The microcontrollers are usually of the ATMEL Company. You must
know what IC your board has before loading up a new program from the Arduino IDE.
This information is available on the top of the IC. For more details about the IC
construction and functions, you can refer to the data sheet.

ICSP pin
Mostly, ICSP (12) is an AVR, a tiny programming header for the Arduino consisting of
12 MOSI, MISO, SCK, RESET, VCC, and GND. It is often referred to as an SPI (Serial
Peripheral Interface), which could be considered as an "expansion" of the output.
Actually, you are slaving the output device to the master of the SPI bu
Power LED indicator
This LED should light up when you plug your Arduino into a power source to
13 indicate that your board is powered up correctly. If this light does not turn on,
then there is something wrong with the connection.

TX and RX LEDs
On your board, you will find two labels: TX (transmit) and RX (receive). They
appear in two places on the Arduino UNO board. First, at the digital pins 0 and
14 1, to indicate the pins responsible for serial communication. Second, the TX

and RX led (13). The TX led flashes with different speed while sending the
serial data. The speed of flashing depends on the baud rate used by the board.
RX flashes during the receiving process.
Digital I/O
The Arduino UNO board has 14 digital I/O pins (15) (of which 6 provide PWM
(Pulse Width Modulation) output. These pins can be configured to work as input
15
digital pins to read logic values (0 or 1) or as digital output pins to drive different
modules like LEDs, relays, etc. The pins labeled “~” can be used to generate
PWM.
AREF
AREF stands for Analog Reference. It is sometimes, used to set an external
reference voltage (between 0 and 5 Volts) as the upper limit for the analog
input pins.
ATMEGA328

 8-bit AVR RISC-based microcontroller


 32KB program flash memory
 1KB EEPROM
 2KB SRAM
 16 MHz max clock frequency
 20 GPIO pins
ATMEGA328 – CONTINUED

32 general purpose registers


3 timers/counters
Internal & external interrupts
USART
2-wire serial interface
SPI port
6-channel 10-bit A2D
ATMEGA328 ARCHITECTURE
ATMEGA328 ARCHITECTURE CONTD.

Harvard architecture Separate memories & buses for


program and data
Instructions executed in single-level pipeline
Fast-access register file 32 x 8 bit general purpose
registers
 Single clock cycle access time Single cycle ALU
operation
AVR ARCHITECTURE – ISA
Supports arithmetic and logic operations between registers or
between a register and a constant
Supports single register operations
Updates status register after arithmetic operations
Most AVR instructions are 16-bit but can support 32-bit instructions
Interrupts and subroutines PC stored on the stack allocated in
SRAM
Only limited by total SRAM size
User programs MUST initialize the SP in reset routine
AVR ARCHITECTURE – PROGRAM MEMORY

Split into boot and application memory


 Boot Memory Contains the primary reset vector & starts on chip
power up
 Configures hardware and branches into application memory
 Can program the application flash memory
 Application Memory Contains the user program
 Has separate reset vector branched to by boot memory
AVR USAGE IN ARDUINO BOARDS

ATmega8
ATmega168
ATmega328
ATmega1280
ATmega2560
Many different Arduino boards with different Atmega
microcontrollers
All are based on the AVR architecture
Internet of Things
• Sensors and actuators embedded in physical objects are
linked through wired and wireless networks

• The Internet of things is the internet working of physical


devices, vehicles, buildings and other items—
embedded with electronics, software, sensors, actuators, and
network connectivity that enable these objects to collect and
exchange data.
Requirements of IOT
• Hardware Requirements

– Microcontroller

– Sensors

– GSM Module

– Bluetooth

• Software Requirements

– Arduino IDE
Sensors
• A sensor is a device that detects and responds to some type
of input from the physical environment.

• A sensor is a device that sense the data from physical


environment and converts real world data (Analog) into data

that a computer can understand.


Sensors
• Analog sensors-produce continuous analog output signal
and these sensors are considered as analog sensors
• Ex: light sensors, sound sensors, temperature sensors

• Digital An electronic or electrochemical sensor,


sensors-
where data conversion and data transmission are done
digitally.
•It has two discrete values. It is on, or it is off.
•Ex: Push button, LED sensors
Sensors
GSM Module
Bluetooth
Set up the Arduino IDE

Step 1 − First you must have your board (you can choose your
favorite board) and a USB cable.

Step 2 − Download Arduino IDE Software from the Arduino

website and run the file.


Step 3 − Power up your board and Connect the Arduino
board to your computer
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.
Step 6-Select your Board
Step 7-Select your serial port
Select the serial device of the Arduino board. Go to Tools → Serial Port menu. 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- Compile & Upload the program
to your board
Arduino program structure
The Arduino software is open-source..
Sketch − The first new terminology is the Arduino program called “sketch”.

Structure
Arduino programs can be divided in three main parts: Structure, Values (variables and
constants), and Functions.
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 − -

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 − -
Arduino - Functions
 Functions allow structuring the programs in segments of code to perform
individual tasks. The typical case for creating a function is when one needs to
perform the same action multiple times in a program.
Standardizing code fragments into functions has several advantages −
 Functions help the programmer stay organized. Often this helps to
conceptualize the program.
 Functions codify one action in one place so that the function only has to be
thought about and debugged once.
 This also reduces chances for errors in modification, if the code needs to be
changed.
 Functions make the whole sketch smaller and more compact because
sections of code are reused many times.
 They make it easier to reuse code in other programs by making it modular,
and using functions often makes the code more readable.
Functions Contd.

some basic facts about functions where stated –


1) each function must have a unique name,
2) the function name is followed by parentheses ()
3) functions have a return type, e.g. void,
4) the body of a function is enclosed in opening and closing braces {}.
The Structure of a Function
Before a function can be used in a sketch, it must be created. The following
code is an example of a function that was created to print a dashed line in
the Arduino IDE.

void DashedLine()
{
Serial.println("----------------");
}

The code above that creates the function is called the function definition.
The image below shows the components of a function.
Function Name

When we create a function, it must be given a name. The naming convention for
functions is the same as for variables:
The function name can be made up of alphanumeric characters (A to Z; a to z;
0 to 9) and the underscore (_).
The function name may not start with a number i.e. the numbers 0 to 9.
A function name must not be used that is the same as a language keyword or
existing function.
The function name ends with parentheses (). Nothing is passed to the
example function above, so the parentheses are empty. Passing values or
parameters to functions will be explained later in this tutorial.
Return Type
A function must have a return type. The example function does not
return anything, so has a return type of void. Returning a value from a
function will be explained in the next part of this course.
Function Body
The function body is made up of statements placed between braces {}.
The statements make up the functionality of the function (what the
function will do when it is called).
When a function is used, it is said to be "called". We will look at how to
call a function next.
Calling a Function

void setup()
{
Serial.begin(9600);
DashedLine();
Serial.println("| Program Menu |");
DashedLine();
}
void loop() {
}
void DashedLine()
{
Serial.println("----------------");
}
In the sketch above, the DashedLine() function is created at the
bottom of the file and then called twice at the top of the file as
shown in the image below.

Calling a Function in an Arduino Sketch


To call a function, use the function name followed by opening and closing
parentheses. Finally terminate the statement that calls the function with a
semicolon.
Why Use Functions
 The function used in the example above is very simple, so all the benefits of
using functions will not be seen immediately.
 One advantage of using functions is that they avoid having to write the same
code over and over again in a sketch which saves time and memory. Every
time that a function is called, we are just reusing code that has been written
once.
 If a function needs to be modified, it only has to be done once and the
modifications will take effect every place in a sketch that the function is called.
If a function was not used, each place that the statements are found in a
sketch to do a particular task would need to be located and modified.
 Functions can be used to break a sketch up into pieces which make it more
modular and easier to understand. Functions can be reused in other sketches.
Passing a Value to a Function

In the sketch above, the length of the line that the function prints out is fixed in
the function. If we change the text that is in the box, it may not fit in the box
properly. The function needs to be modified so that we can tell it what size line
it must draw.
The above function can be modified to pass a value to it that will tell it how
many characters long to make the line that it draws.
void setup()
{ Serial.begin(9600); // draw the menu box
DashedLine(24);
Serial.println("| Program Options Menu |");
DashedLine(24);
}
void loop()
{}
void DashedLine(int len)
{ int i; // draw the line
for (i = 0; i < len; i++)
{ Serial.print("-");
}// move the cursor to the next line
Serial.println("");
}
Arduino Code Basics

Arduino programs run on two basic sections:


void setup() {

//setup motors, sensors etc

}
void loop() {

// get information from sensors


// send commands to motors

}
SETUP

The setup section is used for assigning input and outputs (Examples:
motors, LED’s, sensors etc) to ports on the Arduino
It also specifies whether the device is OUTPUT or INPUT
To do this we use the command “pinMode”

59
59
SETUP

void setup() {
port #

pinMode(9, OUTPUT);
pinMode(10, OUTPUT);Input or Output

http://www.arduino.cc/en/Reference/HomePage
LOOP

void loop() { Port # from setup

digitalWrite(9, HIGH);
digitalWrite(10, HIGH);
delay(1000);
digitalWrite(9, LOW);
digitalWrite(10, LOW);
Turn the LED on
delay(1000); or off
Wait for 1 second
or 1000 milliseconds
}
61
Digital Input/Output

1
Digital IO is binary valued—
it’s either on or off, 1 or 0
0
Internally, all
microprocessors are digital,
why?
Arduino Digital I/0 Programming-Keywords

pinMode(pin, mode)
Sets pin to either INPUT or OUTPUT

X=digitalRead(pin)
Reads HIGH or LOW from a pin

digitalWrite(pin, value)
Writes HIGH or LOW to a pin

Electronic stuff
Output pins can provide 40 mA of current
Writing HIGH to an input pin installs a 20KΩ pullup
Exercise 1 – Controlling LEDs

64
1. LED Blinking
Exercise 2: Digital IO

Use a push-button to turn ON/Off LED


Algorithm for Exercise-2

Configure pin 9 as input port and pin 8 as output port using


pinMode function.
Check whether switch is pressed or not.
(this can be done by reading the value of pin 9 using digitalRead
function)
Make pin 8 High if pin 9 is high(i.e switch pressed)
Otherwise make pin 8 low.
Program for Exercise 2
void setup() {
// initialize serial communication at 9600 bits per second:
// make the pushbutton's pin an input and led pin as output
pinMode(9, INPUT);
pinMode(8, OUTPUT);
}
// the loop routine runs over and over again forever:
void loop() {
// read the input pin:
int x = digitalRead(9); // to read state of the button switch:
delay(1); // delay in between reads for stability
if (x==HIGH){
digitalWrite(8,HIGH);
}
else {
digitalWrite(8,LOW);
}}
Sensors
Sensors | Introduction

 A sensor is a device whose purpose to sense (i.e. to detect) changes in


physical environment. It detect events or changes in quantities and provides a
corresponding output, generally as an electrical or optical signal.
 Example:

A temperature sensor converts temperature to an output voltage.


Sensors | Types

 There are many types of sensor available for different purpose.

 Most common sensors i.e. use for educational purpose.


IR (infrared) Sensor

Sound Sensor

Temperature Sensor
What is an IR Sensor?

• IR sensor is an electronic device, that emits the light in order to sense some
object of the surroundings.
• An IR sensor can measure the heat of an object as well as detects the
motion.
• Usually, in the infrared spectrum, all the objects radiate some form of
thermal radiation.
• These types of radiations are invisible to our eyes, but infrared sensor can
detect these radiations.
• The emitter is simply an IR LED (Light Emitting Diode) and the
detector is simply an IR photodiode .
• Photodiode is sensitive to IR light of the same wavelength which is
emitted by the IR LED. When IR light falls on the photodiode, the
resistances and the output voltages will change in proportion to the
magnitude of the IR light received.
• There are five basic elements used in a typical infrared detection
system: an infrared source, a transmission medium, optical
component, infrared detectors or receivers and signal processing.
Infrared lasers and Infrared LED’s of specific wavelength used as
infrared sources.
Types of IR Sensor
• There are two types of IR sensors are available and they are,
• Active Infrared Sensor
• Passive Infrared Sensor

Active Infrared Sensor


Active infrared sensors consist of two elements: infrared source and infrared detector.
Infrared sources include the LED or infrared laser diode. Infrared detectors include
photodiodes or phototransistors. The energy emitted by the infrared source is reflected by
an object and falls on the infrared detector.

Passive Infrared Sensor


• Passive infrared sensors are basically Infrared detectors. Passive infrared sensors do not
use any infrared source and detector. They are of two types: quantum and thermal.
Thermal infrared sensors use infrared energy as the source of heat. Thermocouples,
pyroelectric detectors and bolometers are the common types of thermal infrared detectors.
Quantum type infrared sensors offer higher detection performance. It is faster than
thermal type infrared detectors. The photo sensitivity of quantum type detectors is
wavelength dependent.
IR Sensor Working Principle
• The emitter is an IR LED and the detector is an IR photodiode. The IR
photodiode is sensitive to the IR light emitted by an IR LED. The photo-
diode’s resistance and output voltage change in proportion to the IR light
received. This is the underlying working principle of the IR sensor.

When the IR transmitter emits radiation, it reaches the object and some of
the radiation reflects back to the IR receiver. Based on the intensity of the
reception by the IR receiver, the output of the sensor defines.
IR Sensor | Working Principle
 An IR sensor is used to detect obstacles in front of the robot or to differentiate
between colour depending on the configuration of the sensor.

No object present – No IR light detected by sensor Lightly coloured objects reflect max. IR light

object present – reflected IR light detected by sensor Dark coloured objects reflect less IR light
IR Sensor | LM358 Comparator

 LM358 is a comparator IC which compares two voltages or currents and


switch it at output to indicate which is larger.
 It is an Op-amp.
IR Sensor | LM358 Pin

Output 1 Vcc

Input 1 ( - ) Output 2

Input 1 ( + ) Input 2 ( - )

GND Input 2 ( + )
IR Sensor | Circuit Diagram
Practical Based On Sensor
 Taking Input from IR Sensor as Digital Input and Controlling the LED
 Components Required:
Node MCU Development Board
USB Cable
LED
Breadboard
Jumper Wires
IR Sensor
Program for IR Sensor
void setup() {

pinMode(D1,INPUT);

Serial.begin(9600); // baud rate

pinMode(D2,OUTPUT);

void loop() {

int data = digitalRead(D1);

digitalWrite(D2,data);

Serial.println(data);

delay(1000);

}
LDR
Circuit connection
void setup() { Code for LDR
Serial.begin(9600);
pinMode(A0, INPUT);
pinMode(3,OUTPUT);
}
void loop() {
int data = analogRead(A0);
if(data<50){
digitalWrite(3,HIGH);
}
else
{
digitalWrite(3,LOW);
}
Serial.println(data);
// delay(500);
}
Temp. Using LM 35 and LCD
Alternate Code for LM35 using Serial Monitor
const int sensor=A1; // Assigning analog pin A1 to variable 'sensor'

float tempc; //variable to store temperature in degree Celsius

float tempf; //variable to store temperature in Fahreinheit

float vout; //temporary variable to hold sensor reading

void setup() { pinMode(sensor,INPUT); // Configuring pin A1 as input

Serial.begin(9600); }

void loop()

{ vout=analogRead(sensor);

vout=(vout*500)/1023;

tempc=vout; // Storing value in Degree Celsius

tempf=(vout*1.8)+32; // Converting to Fahrenheit

Serial.print("in DegreeC=");

Serial.print("\t");

Serial.print(tempc);

Serial.println();

Serial.print("in Fahrenheit=");

Serial.print("\t"); Serial.print(tempf);

Serial.println();

delay(1000); //Delay of 1 second for ease of viewing

}
Alternate Code for LM35 using LCD
#include<LiquidCrystal.h> void loop()
LiquidCrystal lcd(12, 11, 5, 4, 3, 2); { vout=analogRead(sensor);
const int sensor=A1; // Assigning analog pin A1 to variable vout=(vout*500)/1023;
'sensor' tempc=vout; // Storing value in Degree
float tempc; //variable to store temperature in degree Celsius
Celsius tempf=(vout*1.8)+32; // Converting to
float tempf; //variable to store temperature in Fahreinheit Fahrenheit
float vout; //temporary variable to hold sensor reading lcd.setCursor(0,0);
void setup() lcd.print("in DegreeC= ");
{ pinMode(sensor,INPUT); // Configuring pin A1 as input lcd.print(tempc);
Serial.begin(9600); lcd.setCursor(0,1);
lcd.begin(16,2); lcd.print("in Fahrenheit=");
delay(500); lcd.print(tempf);
} delay(1000); //Delay of 1 second for ease
of viewing
}
ULTRASONIC SENSOR

https://www.circuitbasics.com/how-to-set-up-an-ultrasonic-range-finder-on-
an-arduino
https://create.arduino.cc/projecthub/abdularbi17/ultrasonic-sensor-hc-sr04-
with-arduino-tutorial-327ff6
https://www.tinkercad.com/things/5blUxBuOaij-copy-of-ultrasonic-distance-
sensor-led-bar-graph-blocks/editel?tenant=circuits
• Ultrasonic rangefinders use sound waves to bounce off objects
in front of them, much like bats using echolocation to sense
their environment. The proximity sensor sends out a signal and
measures how long it takes to return. The Arduino program
receives this information and calculates the distance between
the sensor and object.
What is Ultrasonic Sensor

 The Ultrasonic Sensor is a Transceiver Module (Transmitter + Receiver)

 It transmits High Frequency Ultrasonic Waves of frequency greater than 20


KHz.
 Intercepts the waves reflected by an obstacle.
HC-SR04

 Operating Voltage : 5V

 Working Frequency : 40 KHz

 Trigger Input Signal : 10μs TTL pulse

Transmitter

Receiver
Working Principle
Pin Configuration
Technical Specifications

• Power Supply − +5V DC


• Quiescent Current − <2mA
• Working Current − 15mA
• Effectual Angle − <15°
• Ranging Distance − 2cm – 400 cm/1″ – 13ft
• Resolution − 0.3 cm
• Measuring Angle − 30 degree
Applications

Ultrasonic sensors can measure the following parameters, without even getting
in contact with the medium which is to be measured :
Distance

Level

Presence

Diameter

Position
Obstacle
Avoider
Robot
ADVANCED
PARKING
ASSISTANCE
Let’s Measure the Distance !
• For example, if the object is 20 cm away from the sensor, and the speed of
the sound is 340 m/s or 0.034 cm/µs the sound wave will need to travel
about 588 microseconds. But what you will get from the Echo pin will
be double that number because the sound wave needs to travel
forward and bounce backward. So in order to get the distance in cm we
need to multiply the received travel time value from the echo pin by 0.034
and divide it by 2
Ultrosonic sensor
Code for Distance Measurement using Ultrosonic
sensor
#define echoPin 2
#define trigPin 3
long duration;
int distance;
void setup()
{ Serial.begin(9600);
pinMode(trigPin,OUTPUT);
pinMode(echoPin,INPUT); }
void loop()
{ digitalWrite(trigPin,LOW); delayMicroseconds(2);
digitalWrite(trigPin,HIGH); delayMicroseconds(10);
digitalWrite(trigPin,LOW);
duration=pulseIn(echoPin,HIGH);
distance=(duration*0.034/2); Serial.print("Distance : "); Serial.print(distance);
Serial.println(" cm ");
delay(1000); }
DHT Sensor Module

https://microcontrollerslab.com/dht11-interfacing-arduino-code/
https://www.electronicwings.com/arduino/dht11-sensor-interfacing-with-arduino-uno
https://www.circuitbasics.com/how-to-set-up-the-dht11-humidity-sensor-on-an-
arduino/
What is DHT ?
• It stands for Digital Humidity and Temperature which used to
measure humidity and temperature.

• We have two variants for DHT sensor


• DHT 11
• DHT 22

DHT 11 DHT 22
HOW THE DHT11 MEASURES HUMIDITY AND
TEMPERATURE

• The DHT11 detects water vapor by measuring the electrical resistance


between two electrodes. The humidity sensing component is a moisture
holding substrate with electrodes applied to the surface. When water vapor
is absorbed by the substrate, ions are released by the substrate which
increases the conductivity between the electrodes. The change in resistance
between the two electrodes is proportional to the relative humidity. Higher
relative humidity decreases the resistance between the electrodes, while
lower relative humidity increases the resistance between the electrodes.
TYPES
• There are two different versions of the DHT11 you might come across. One
type has four pins, and the other type has three pins and is mounted to a
small PCB. The PCB mounted version is nice because it includes a surface
mounted 10K Ohm pull up resistor for the signal line. Here are the pin outs
for both versions:
Comparison
CONNECTING A THREE PIN DHT11:
DISPLAY HUMIDITY AND TEMPERATURE
ON THE SERIAL MONITOR

• Before you can use the DHT11 on the Arduino,


you’ll need to install the DHTLib library. It has all the
functions needed to get the humidity and temperature
readings from the sensor. It’s easy to install, just
download the DHTLib.zip file below and open up the
Arduino IDE. Then go to Sketch>Include
Library>Add .ZIP Library and select the DHTLib.zip file
Program
#include <dht.h>

dht DHT;

#define DHT11_PIN 7

void setup()

{ Serial.begin(9600); }

void loop()

{ int chk = DHT.read11(DHT11_PIN);

Serial.print("Temperature = ");

Serial.println(DHT.temperature);

Serial.print("Humidity = ");

Serial.println(DHT.humidity);

delay(1000); }
DISPLAY HUMIDITY AND TEMPERATURE ON AN
LCD
#include <dht.h>

#include <LiquidCrystal.h>

LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

dht DHT;

#define DHT11_PIN 7

void setup(){ lcd.begin(16, 2); }

void loop()

{ int chk = DHT.read11(DHT11_PIN);

lcd.setCursor(0,0); lcd.print("Temp: ");

lcd.print(DHT.temperature);

lcd.print((char)223); lcd.print("C");

lcd.setCursor(0,1); lcd.print("Humidity: "); lcd.print(DHT.humidity); lcd.print("%");


delay(1000); }
Practical
Library - #include <DHT.h>

DHT dht(pinName, Type of sensor)

dht.readTemperature() – returns temperature in Celsius

dht.readTemperature(True) – returns temperature in Fahrenheit

dht.readHumidity() – returns humidity


Code for DHT
#include <LiquidCrystal.h>
#include <dht11.h>

LiquidCrystal lcd(12, 11, 5, 4, 3, 2);


#define DHT11_PIN 7
dht11 DHT;
int G = 8;
int R = 9;

void setup()
{
lcd.begin(16,2);
Serial.begin(9600);
Serial.println("Humidity and temperature measurement ");
Serial.print("Lib. version: ");
Serial.println(DHT11LIB_VERSION);
Serial.println();
pinMode (G, OUTPUT);
pinMode (R, OUTPUT);
}

void loop()
{
DHT.read(DHT11_PIN);
lcd.clear();
lcd.setCursor(0,0);
lcd.print("Humidity = ");
lcd.print(DHT.humidity);
lcd.setCursor(0,1);
lcd.print("Temperature = ");
lcd.print(DHT.temperature);
int chk;
;
// check for errors
chk = DHT.read(DHT11_PIN);
switch (chk){
case DHTLIB_OK:
break;
case DHTLIB_ERROR_CHECKSUM:
Serial.println("Checksum error, \t");
break;
case DHTLIB_ERROR_TIMEOUT:
Serial.println("Time out error, \t");
break;
default:
Serial.println("Unknown error, \t");
break;
}
// temperature and humidity data on LCD screen
Serial.print("Humidity = ");
Serial.print(DHT.humidity, 1);
Serial.print(", Temp = ");
Serial.println(DHT.temperature,1);

//set you own measurement data range


if (DHT.humidity >40){
digitalWrite (G, LOW);
}
else{
digitalWrite (G, HIGH);
}
if (DHT.temperature >30){
digitalWrite (R, HIGH);
}
else{
digitalWrite (R, LOW);
}

if (DHT.humidity >40){
digitalWrite (R, HIGH);
}

if (DHT.temperature >30){
digitalWrite (G, LOW);
}
//play with "delay" parameter achieve best result
delay(500);
•}

You might also like