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

United International University

Dhaka, Bangladesh

Course Title: Microprocessor,


Microcontroller and Interfacing Lab
Course Code : CSE 426
TABLE OF CONTENTS

Experiment no. PAGE


Experiment 1: Experiment on how to store an assembly language equivalent machine language
code (Hex code) in 8086 microprocessor, check the code step by step and reprogram it ...............3
Experiment 2: Microcontroller configuration and LED interfacing with ATmega 32 ..................11
Experiment 3: Microcontroller Input Output Operation ................................................................22
Experiment 4: Multiple 7 segment display interfacing with ATmega 32 ......................................27
Experiment 5: LCD display interfacing with ATmega 32 .............................................................32
Experiment 6: Introduction to Arduino Uno board........................................................................42
Experiment 7: Analog input-output ...............................................................................................57
Experiment 8: Receive Humidity and Temperature update from one Arduino board to another
Arduino board using I2C communication protocol……………………………………………...70
Experiment 9: Transmit and receive distance measurement to an object from one Arduino board
to another Arduino board using RF 433MHz Transmitter/Receiver module……………………80
Experiment 10: Led interfacing with Raspberry pi........................................................................89
CSE 426 Experiment 1: Experiment on how to store an assembly
language equivalent machine language code (Hex code) in 8086
microprocessor, check the code step by step and reprogram it

Objective
After completing this experiment, student will be able to
 understand the internal architecture of 8086 microprocessors
 explain the memory segmentation of 8086 microprocessor
 use MDA-8086 kit to solve arithmetical problem

Introduction to MDA-8086 kit


MDA-8086 has high performance 64K-byte monitor program. It is designed for easy
function. After power is on, the monitor begins to work. In addition to all the key
function the monitor has a memory checking routine. The following is a simple
description of the key functions.

Basic operation
On a power-up, following message will be displayed on a LCD.
To select the Machine Code and Serial monitor mode with P1 switch.

Whenever RES is pressed, the display becomes FIGURE 1-1 or FIGURE 1-2.

N. M. 4
N. M. 5
When the power is on or press the RES key, following message will be displayed on
LCD.

N. M. 6
N. M. 7
8086 Assembly Language
MOV Command
MOV is a basic command to assign a number to a variable. For example following word
can be converted to a MOV command as,
x = 33;

MOV AX, 33d (d stands for decimal)


Here AX stands for x. In this way we can declare variables. MOV can also be used to
assign another registers value.
x = 33
y=x

MOV AX, 33
MOV BX, AX

MOV can also be used to assign some value to a memory location or from a
memory location.

MOV AX, [1000H] Storing value to AX from memory location 1000H. MOV
[1000H], AX Storing value to memory location 1000H from AX. MOV [BX], AX
Storing value of memory location that has address given by the value of BX, from
AX.

More about MOV


MOV command must be used with registers of equal size.

MOV AX, BL is not correct as AX is of 16bits and BL is of 8 bits. Similarly


MOV BL, 1652h is not correct as 1652h is 16 bit number and available space for BL
is only 8 bits.

Remember if you write ‘h’ after a number then it is hexadecimal number. If nothing
is written then default type is decimal.

NEG command:
NEG command is used to get the 2’s complement of any number. MOV AL,
30h NEG AL

N. M. 8
Exercise Part 1
Write following codes and perform indicated operations. Take help from previously
stated operations for loading and executing the program.

a)
MOV AX, 3012
Observe content of AX register.

MOV BX, AX
Observe content of BX register.

Which operation happened here

b)
MOV AX, 30h
MOV [2010], AX
MOV BX, [2010]

Observe content of BX register.

Which operation happened here

c)
MOV SI, 1256h;
MOV [SI], 3251h;
MOV AX, [SI];
Observe content of AX register.

Which operation happened here

d)
MOV AL, 87h ;
NEG AL ;
NEG AL;

Write value of AL for every step.

Arithmetic Commands
ADD, SUB, DIV, MUL are all arithmetic commands. ADD is used to add two numbers.
For example following lines can be converted to,
x = 1236H ; y = 1438H ; z = x + y
MOV AX, 1236H ; MOV BX,1438H ; ADDAX, BX
N. M. 9
This command adds AX and BX content and stores it to AX register.
Similarly SUB command is used for subtraction of two numbers. For example, x = 1236H ;
y = 1438H ; z = x – y
MOV AX, 123H ;
MOV BX, 1438H ;
SUB AX, BX
AX holds the subtraction result.

Exercise Part 2:
Write following codes and perform indicated operations.

A.

MOV AX, 1782H ;


MOV BX,1278H ;
ADD AX, BX ;
Examine register contents

B.
MOV AX,1782H ;
MOV BX,1278H ;
SUB AX, BX ;
Examine register contents

C.
MOV AX, 2782H ;
MOV BX, 1278H ;
MUL BX;
Examine register contents

D.
MOV AX, 57F2H
MOV BX, 1375H
DIV BX
Examine register content

Exercise
1. What is a Microprocessor?
2. Write down the full-name of the General purpose registers of 8086 microprocessor.
3. Write down the full-name of the Segment registers of 8086 microprocessor.
4. Write and explain the code using 8086 assembly language to add the last three digits
of your student ID in hexadecimal. Write down the Hex code from Emu8086
software.
5. Write and explain the code to Multiply the result from Question 4 with your first three
digits of your student ID. Write the hex code from emu8086 software.
6. Suppose AH contains result from Question 4, AL contains result of Question 5. Now
write an assembly code to store the difference of AH and AL in CL. Store the value of
10 in BL. Now divide the value of BL by CL. Explain the code line by line. You don’t
need to write the hex code.

N. M. 10
CSE 426 Experiment 2: Microcontroller configuration and LED
interfacing with ATmega 32

Objective
After completing this experiment, student will be able to
• understand Input/Output Pin and Port in microcontroller
• identify the Atmel ATmega32 microcontroller pin configuration, AVR trainer kit, and
associated hardware.
• understand how to create a new project in CodeVisionAVR and use AVR Programmer
to write Hex code into the ATmega32 microcontroller. Additionally, simulate a project in
the Proteus.

Equipment needed
• AVR trainer kit
• ATMEGA 32 Microcontroller
• CodeVisionAVR (Compiler)
• AVR Programmer (To write Hex code)
• Proteus software (Simulator)

Introduction
A microcontroller often serves as the “brain” of a mechatronic system. Like a mini, self-
contained computer, it can be programmed to interact with both the hardware of the system
and the user. Even the most basic microcontroller can perform simple math operations,
control digital outputs, and monitor digital inputs. As the computer industry has evolved, so
has the technology associated with microcontrollers. Newer microcontrollers are much faster,
have more memory, and have a host of input and output features that dwarf the ability of
earlier models. Most modern controllers have analog-to-digital converters, high-speed timers
and counters, interrupt capabilities, outputs that can be pulse-width modulated, serial
communication ports, etc.

ATmega32 microcontroller
Atmel’s ATMega32 8-Bit Processor. 32K of program space, 32 I/O lines, 8 of which are
10bit Analog to Digital converter capable. Runs up to 16MHz with external crystal.

N. M. 11
Figure. Pinout ATmega32

Digital Input/Output ports (PORTA ~ PORTD) of Atmel ATmega32


 A port serves as an interface between the microcontroller and other peripheral
devices.
 8 pins are grouped together as ports. Generally, there are 4 or more ports in an AVR.
The ports are named in in alphabetic letters, such as PORTA, PORTB, PORTC and
PORTD etc. Each port has 8 pins, from 0 to 7. For example, the pins of port B are
PB7, PB6, PB5, PB4, PB3, PB2, PB1, PB0
 The Atmega32 has 4 ports, A, B, C and D, each of them have 8 pins. Most of the pins
have some additional bracketed name, (for example (RXD) on PD0. This means that
this pin is also an RXD pin).

The configuration of the port operation is defined in software using the following registers-
DDRx (Data direction register)
 Read/write 8-bit registers;
 Selects the direction of the corresponding I/O pin
 DDRx configuration:
o Bit = 1: The port pin is set up as an output
o Bit = 0: the port pin is set up as an input

PORTx (Output Registers)


 Each bit of these registers reflects the value written to the
corresponding output pin
 PORTx configuration:
o Bit = 1: The output is high
o Bit = 0: The output is low

PINx (Input Registers)


 Each bit of these read-only registers reflects the input signal at the corresponding I/O
pin
 PINx configuration:
o Bit = 1: The input is high
o Bit = 0: The input is low

N. M. 12
AVR trainer kit
A well designed Trainer board is always essential for smooth development/experimentation
with microcontrollers. Every hobbyist or student must have some kind of development setup.
Some people use breadboard while others use general PCB to fabricate their development
system. Development is not very easy if bread boards or general PCB are used. If bread board
is used, after few days of use the wire will become loose or come out of the hole. While
making large circuit in a general PCB is a tedious job.
Such problems are solved by using AVR Trainer kit. It is a circuit board with basic connection
required to drive the microcontroller and also with features like serial port, LCD display,
seven segment displays, prototyping area, power supply and it supports 40 and 28 PDIP pin
AVR Micro-controllers etc.
A trainer board is very useful as you can program the microcontroller and also check the
outputs using the LEDs or LCD display or even connect it to the rest of the project using
wires or connectors. The power supply provided on the board can be used to supply power to
other circuits. The board also has provision to run DC motors or even stepper motors with the
help of motor driver ICs present on the board.

Figure: AVR trainer kit


A very good advantage of such a trainer board is that all the basic project requirements are
present on the board and it also occupies less space even with all the modules like LCD and
seven segment displays. The AVR trainer kit has features which helps you in making and
testing a project involving a variety of modules like:
 On Board integrated universal Atmel AVR USB Programmer with ZIP Socket
support with ISP connector.
 Power Sources (5V) and Ground.
 24 LED
 LCD Display
 4 Digit 7 Segment Display (Cathode and Anode)
 4*4 Matrix keypad (External connection)

N. M. 13
CodeVisionAVR
CodeVision avr is a C cross-compiler, integrated development and automatic program
generator designed for the Atmel avr family of microcontrollers.

Follow all the steps.

1. Download and open CVAVR. Goto file>new.

2. Select file type Project and click ok.

3. Select your chip type and click ok.

4. Now a window opens for including various functions or header files in your program
automatically. First, select your controller from chip option.

N. M. 14
5. If you used LCD in your project then go to LCD and select LCD port.

6. After including all your requirements go to file>generate, save and exit.

N. M. 15
7. Now this window opens 3 times save your project at the location you want and type the file
name like evm in all 3 windows. All 3 file names must be same.

8. Now a project window opens where code editing needs to be done.

N. M. 16
12. Click the button Build as shown for building your project.

N. M. 17
13. Click the button Compile. You can find your HEX file in EXE folder.

AVR programmer
• Double click on AVR Prog icon.
• A small window opens with options like Program, Read and Verify.
• Click on Browse and select the hex file which is to be written into the microcontroller.
• Then click on Program button.

2. Select HEX file location

3. Write HEX file in the microcontroller

1. Select microcontroller model

Proteus
Proteus has many features to generate both analogue and digital result. However, this lab will
focus on only tools that will be used in digital schematic designs.

N. M. 18
Figure: Example of Proteus software window

N. M. 19
Figure: Select Yellow LED from proteus library

Steps :
 Click New Project to create a new project.
 Select Library to Pick From Libraries
 Add all the required components
 Place the components on the workspace
 Wire up the circuit
 Click on Play Button on the bottom left to start simulation

LED interfacing
In this lab session connect an LED to one of the port pin of Atmega32 and flash it
continuously with 1 sec duration.
One of the most basic features of any microprocessor is to be able to use the pins as general
input and output pin. The Pins as output pins can be used as both source (logic 1) and sink
(logic 0).

This is a better example (red means logic 1, black

N. M. 20
Code
#include <atmega32.h>

void main(void)
{
DDRC = 0b11111111; // pin 0, 1, 2, 3, 4 , 5, 6 , 7 of Port C is set as output
PORTC = 0b11110000; // Pin 7, 6 , 5, 4 of Port C is High; Pin 3, 2 , 1, 0 is Low
}
Code to blink LED after 1 second delay
#include <mega32.h>
#include <delay.h>
// Declare your global variables here
void main(void)
{
DDRB=0b00000001; // pin 0 of Port B is set as output
PORTB=0b0000000; // pin 0, 1, 2, 3, 4 , 5, 6 , 7 of Port B voltage is Low

while (1)
{
PORTB= 0b00000001; // pin 0 of Port B voltage is High
delay_ms(1000);
PORTB=0b00000000; // pin 0 of Port B voltage is Low
delay_ms(1000);
}
}

Figure: Connection diagram of the LED Light Flashing.

Exercise
1. There are eight led on the board. Blink all the even led and odd led. Use 2 second
delay. Write down the code and circuit diagram. Explain the code line by line.
2. Blink all the led one after another. Use 1 second delay. Write down the code and
circuit diagram.
3. Describe the usage of DDRx, PINx and, PORTx registers of ATMega32
microcontroller.
4. What is a microcontroller? Why intel® 8086 is not considered as a micro-controller.

N. M. 21
CSE 426 Experiment 3: Microcontroller Input Output Operation
Objective
After completing this experiment, student will be able to
• understand how to configure a microcontroller pin as an input and output
• explain how to design the pull-up circuit
• explain the switch bounce problem and how to solve it

Equipment needed
• AVR trainer kit
• ATMEGA 32 Microcontroller
• CodeVision AVR(Compiler)
• AVR Programmer (To write Hex code)
• Proteus (Simulator)
• Led
• Button

Pull-up circuit
Pull-up resistors are very common when using microcontrollers (MCUs) or any digital logic
device. Suppose you have an MCU with one pin configured as an input. If there is nothing
connected to the pin and your program reads the state of the pin, will it be high (pulled to
VCC) or low (pulled to ground)? It is difficult to tell. This phenomena is referred to as
floating. To prevent this unknown state, a pull-up or pull-down resistor will ensure that the
pin is in either a high or low state, while also using a low amount of current. Pull-ups are
often used with buttons and switches.

Figure: Pull-up circuit (1)


With a pull-up resistor, the input pin will read a high state when the button is not pressed. In
other words, a small amount of current is flowing between VCC and the input pin (not to
N. M. 22
ground), thus the input pin reads close to VCC. When the button is pressed, it connects the
input pin directly to ground. The current flows through the resistor to ground, thus the input
pin reads a low state. Keep in mind, if the resistor wasn’t there, your button would connect
VCC to ground, which is very bad and is also known as a short.
The value of the pull-up resistor needs to be chosen to satisfy two conditions:
1. When the button is pressed, the input pin is pulled low. The value of resistor R1
controls how much current you want to flow from VCC, through the button, and then
to ground.
2. When the button is not pressed, the input pin is pulled high. The value of the pull-up
resistor controls the voltage on the input pin.

Figure: Pull-up circuit (2)

Figure: Microcontroller PORT C is set as Output, PORT B is set as Input


Steps
1. Draw the circuit in the Proteus.
2. Compile the code using Code vision avr and generate Hex code.
3. Upload the hex code in the Proteus simulator and run the simulation
N. M. 23
Code 1
#include <mega32.h>
#include<delay.h>

// Declare your global variables here

void main(void)
{
// Declare your local variables here
DDRC = 0b00001000; // pin 3 of Port C is set as Output
DDRB = 0b00000000; // pin 0, 1, 2, 3, 4, 5, 6, 7 of Port B is set as Input

while (1)
{
// Place your code here
if (PINB.5 == 0)
{
PORTC = 0b00001000; // pin 3 of Port C voltage is High
delay_ms(200);
}
else
{
PORTC = 0b00000000; // pin 3 of Port C voltage is Low
delay_ms(200);
}
}
}

Switch Bounce

Switch bounce is a common problem associated with mechanical switches. Switch contacts
are made up of spring metals which are forced to contact each other. While they collide each
other there is a possibility of rebounding for some time before they make a stable contact. It’s
similar to case of dropping a bouncing ball or basketball. The ball keeps on bouncing till it
comes to rest. This case can be taken analogous to on/off of a switch. When the ball touches
the ground analogous to on and when it rises to certain level analogous to off of a switch. As

N. M. 24
a result of this effect there will be on/off transitions generated as the contacts rapidly open
and close.
To solve this problem, the following approach can be used:
A software time delay is used that provides a time delay (usually 10-20 ms) longer than the
duration of the switch bouncing action. So if switch goes low, wait for longer than 10ms or
20ms and then test for the switch still being low.

Figure: Flow-chart of the button de-bouncing

Figure: Switch Bouncing in Pull Up Connection

N. M. 25
Figure: Switch Bouncing in Pull Down Connection

Exercise
1. Suppose you want to interface four LED with the micro-controller (ATMEGA32)
PORT C (0, 1, 2, 3). And a push button is connected with the micro-controller
(ATMEGA32) PORT B (3). When button is pressed, LED will be turn on and when
button is released, LED will be turn off. Write down the code and circuit diagram.

2. Draw a pull up switch and a pull down switch configuration.

3. Design a counter using a pull up switch connected with PORTB, 0 pin. When the
switch is pressed, the value of PORTA is incremented by 1 (one) each time. Your
design should include a) circuit diagram, b) C code and, c) explanation of the process.

4. Draw the flowchart based on the code given in code1 (see above).

N. M. 26
CSE 426 Experiment 4: Multiple seven segment display interfacing
with ATmega 32.
Objective
After completing this experiment, student will be able to
• explain the difference between cathode and anode seven segment display
• understand how to interface multiple seven segment display with ATmega32

Equipment needed
• AVR trainer kit
• ATMEGA 32 Microcontroller
• CodeVisionAVR(Compiler)
• AVR Programmer (To write Hex code)
• Proteus (Simulator)
• Multiple 7 segment display

7 segment display
An LED or Light Emitting Diode, is a solid state optical PN-junction diode which emits light
energy in the form of “photons” when it is forward biased by a voltage allowing current to
flow across its junction, and in Electronics we call this process electroluminescence.

The actual colour of the visible light emitted by an LED, ranging from blue to red to orange,
is decided by the spectral wavelength of the emitted light which itself is dependent upon the
mixture of the various impurities added to the semiconductor materials used to produce it.

Figure: 7-segment Display


Light Emitting Diodes have many advantages over traditional bulbs and lamps, with the main
ones being their small size, long life, various colours, cheapness and are readily available, as
well as being easy to interface with various other electronic components and digital circuits.
But the main advantage of light emitting diodes is that because of their small die size, several
of them can be connected together within one small and compact package producing what is
generally called a 7-segment Display.

N. M. 27
The 7-segment display, also written as “seven segment display”, consists of seven LEDs
(hence its name) arranged in a rectangular fashion as shown. Each of the seven LEDs is
called a segment because when illuminated the segment forms part of a numerical digit (both
Decimal and Hex) to be displayed. An additional 8th LED is sometimes used within the same
package thus allowing the indication of a decimal point, (DP) when two or more 7-segment
displays are connected together to display numbers greater than ten.
Each one of the seven LEDs in the display is given a positional segment with one of its
connection pins being brought straight out of the rectangular plastic package. These
individually LED pins are labelled from a through to g representing each individual LED.
The other LED pins are connected together and wired to form a common pin.
So by forward biasing the appropriate pins of the LED segments in a particular order, some
segments will be light and others will be dark allowing the desired character pattern of the
number to be generated on the display. This then allows us to display each of the ten decimal
digits 0through to 9 on the same 7-segment display.
The displays common pin is generally used to identify which type of 7-segment display it is.
As each LED has two connecting pins, one called the “Anode” and the other called the
“Cathode”, there are therefore two types of LED 7-segment display called: Common
Cathode (CC) and Common Anode (CA).
The difference between the two displays, as their name suggests, is that the common cathode
has all the cathodes of the 7-segments connected directly together and the common anode has
all the anodes of the 7-segments connected together and is illuminated as follows.
1. The Common Cathode (CC) – In the common cathode display, all the cathode connections
of the LED segments are joined together to logic “0” or ground. The individual segments are
illuminated by application of a “HIGH”, or logic “1” signal via a current limiting resistor to
forward bias the individual Anode terminals (a-g).

Common Cathode 7-segment Display

2. The Common Anode (CA) – In the common anode display, all the anode connections of
the LED segments are joined together to logic “1”. The individual segments are illuminated
by applying a ground, logic “0” or “LOW” signal via a suitable current limiting resistor to the
Cathode of the particular segment (a-g).

N. M. 28
Common Anode 7-segment Display

In general, common anode displays are more popular as many logic circuits can sink more
current than they can source. Also note that a common cathode display is not a direct
replacement in a circuit for a common anode display and vice versa, as it is the same as
connecting the LEDs in reverse, and hence light emission will not take place.
Depending upon the decimal digit to be displayed, the particular set of LEDs is forward
biased. For instance, to display the numerical digit 0, we will need to light up six of the LED
segments corresponding to a, b, c, d, e and f. Then the various digits from 0 through 9 can be
displayed using a 7-segment display as shown.
7-Segment Display Segments for all Numbers.

Then for a 7-segment display, we can produce a truth table giving the individual segments
that need to be illuminated in order to produce the required decimal digit from 0 through 9 as
shown below.

N. M. 29
Figure: ATmega32 interfacing with multiple 7-segment display
# Code to display digit 8 in 7 segment display
#include <mega32.h>
void main(void)
{
// Declare your local variables here
// Port A initialization
DDRA=0xFF; // Selector
// Port B initialization
DDRB=0xFF; // Data
while (1)
{
// Place your code here
PORTA=0b11111110; // number ‘4’ 7-segment is ON
PORTB=0b11111111; // digit ‘8’
}
}

N. M. 30
Steps
4. Draw the circuit in the Proteus.
5. Compile the code using Code vision avr and generate Hex code.
6. Upload the hex code in the Proteus simulator and run the simulation

7-segment Display Truth Table

Decimal Individual Segments Illuminated


Digit a b c d e f g

0 × × × × × ×

1 × ×

2 × × × × ×

3 × × × × ×

4 × × × ×

5 × × × × ×

6 × × × × × ×

7 × × ×

8 × × × × × × ×

9 × × × × ×

Exercise
1. Show digit ‘14’ on the multi seven segment display.

2. Describe the Common Cathode (CC) and Common Anode (CA) connections for a 7
segment display. Draw block diagram for CA and CC connections.

3. Why the display is called 7 segment display? How we can use the same data port for
all the segments in a multi 7 segment display?

4. Write the code to display the last three digits of your student id in a multiple 7
segment display of Common Cathode connection using ATMega32 microcontroller.
Explain the code line by line.

N. M. 31
CSE 426 Experiment 5: LCD display interfacing with ATmega 32
Objective
After completing this experiment, student will be able to
• understand the configuration of LCD display
• understand how to interface LCD display with ATmega32 and display custom character

Equipment needed
• AVR trainer kit
• ATMEGA 32 Microcontroller
• CodeVisionAVR(Compiler)
• AVR Programmer (To write Hex code)
• Proteus (Simulator)
• LCD display

Lcd display
This component is specifically manufactured to be used with microcontrollers, which means
that it cannot be activated by standard IC circuits. It is used for displaying different messages
on a miniature liquid crystal display. The model described here is for its low price and great
capabilities most frequently used in practice. It is based on the HD44780 microcontroller
(Hitachi) and can display messages in two lines with 16 characters each. It can display all the
letters of alphabet, Greek letters, punctuation marks, mathematical symbols etc. It is also
possible to display symbols made up by the user. Other useful features include automatic
message shift (left and right), cursor appearance, LED backlight etc.

N. M. 32
LCD Display Pins

Along one side of the small printed board of the LCD display there are pins that enable it to
be connected to the microcontroller. There are in total of 14 pins marked with numbers (16 if
there is a backlight). Their function is described in the table below:

LCD Screen

An LCD screen can display two lines with 16 characters each. Every character consists of
5x8 or 5x11 dot matrix. This book covers a 5x8 character display which is most commonly
used.

CGROM Memory

CGROM memory contains a standard character map with all characters that can be displayed
on the screen. Each character is assigned to one memory location:

LCD Connecting

Depending on how many lines are used for connecting an LCD to the microcontroller, there
are 8-bit and 4-bit LCD modes. The appropriate mode is selected at the beginning of the
operation in the process called 'initialization'. The 8-bit LCD mode uses outputs D0- D7 to
transfer data as explained on the previous page.

The main purpose of the 4-bit LCD mode is to save valuable I/O pins of the microcontroller.
Only 4 higher bits (D4-D7) are used for communication, while others may be left
unconnected. Each piece of data is sent to the LCD in two steps- four higher bits are sent first
(normally through the lines D4-D7), then four lower bits. Initialization enables the LCD to
link and interpret received bits correctly.

N. M. 33
N. M. 34
PIN LOGIC
FUNCTION NAME DESCRIPTION
NUMBER STATE
Ground 1 Vss - 0V
Power supply 2 Vdd - +5V
Contrast 3 Vee - 0 - Vdd
D0 – D7 are interpreted as
0
4 RS commands
1
D0 – D7 are interpreted as data
0 Write data (from controller to LCD)
Control of 5 R/W
1 Read data (from LCD to controller)
operating
Access to LCD disabled
0
Normal operating
6 E 1
Data/commands are transferred to
From 1 to 0
LCD
7 D0 0/1 Bit 0 LSB
8 D1 0/1 Bit 1
9 D2 0/1 Bit 2
10 D3 0/1 Bit 3
11 D4 0/1 Bit 4
Data / commands
12 D5 0/1 Bit 5
13 D6 0/1 Bit 6
14 D7 0/1 Bit 7 MSB
15 Back light +5V
16 Back light 0V

N. M. 35
VDD
VSS

VEE

RW
RS

D0
D1
D2
D3
D4
D5
D6
D7
E
1
2
3

4
5
6

7
8
9
10
11
12
13
14
U1
9 22
RESET PC0/SCL
23
PC1/SDA
13 24
XTAL1 PC2/TCK
12 25
XTAL2 PC3/TMS
26
PC4/TDO
40 27
PA0/ADC0 PC5/TDI
39 28
PA1/ADC1 PC6/TOSC1
38 29
PA2/ADC2 PC7/TOSC2
37
PA3/ADC3
36 14
PA4/ADC4 PD0/RXD
35 15
PA5/ADC5 PD1/TXD
34 16
PA6/ADC6 PD2/INT0
33 17
PA7/ADC7 PD3/INT1
18
PD4/OC1B
1 19
PB0/T0/XCK PD5/OC1A
2 20
PB1/T1 PD6/ICP1
3 21
PB2/AIN0/INT2 PD7/OC2
4
PB3/AIN1/OC0
5
PB4/SS
6
PB5/MOSI
7 32
PB6/MISO AREF
8 30
PB7/SCK AVCC
ATMEGA32

Figure: Lcd display interfacing

N. M. 36
Figure: Custom character

N. M. 37
Codevision avr Alphanumeric LCD Functions

void lcd_init(unsigned char lcd_columns)


Initializes the LCD module, clears the display and sets the printing character position at row 0
and column 0. The numbers of columns of the LCD must be specified (e.g. 16). No cursor is
displayed. This is the first function that must be called before using the other high level LCD
Functions.

void lcd_clear(void)
Clears the LCD and sets the printing character position at row 0 and column 0.

void lcd_gotoxy(unsigned char x, unsigned char y)


Sets the current display position at column x and row y. The row and column numbering
starts from 0.

void lcd_putchar(char c)
Displays the character c at the current display position.

void lcd_puts(char *str)


Displays at the current display position the string str, located in RAM.

# Show ‘Hello World’ in the LCD screen


#include <mega32.h>

// Alphanumeric LCD Module functions


#include <alcd.h>
#include <delay.h>

// Declare your global variables here

void main(void)
{
// Declare your local variables here

// Alphanumeric LCD initialization


// Connections specified in the
// Project|Configure|C Compiler|Libraries|Alphanumeric LCD menu:
// RS - PORTB Bit 0
// RD - PORTB Bit 1
// EN - PORTB Bit 2
// D4 - PORTB Bit 4
// D5 - PORTB Bit 5
// D6 - PORTB Bit 6
// D7 - PORTB Bit 7

// Characters/line: 16

N. M. 38
lcd_init(16);

while (1)
{
// Place your code here
lcd_puts("Hello");
delay_ms(1000);
lcd_clear();
delay_ms(1000);
lcd_gotoxy(2,1); // move cursor in col 2 row 1
lcd_puts("World");
delay_ms(1000);
lcd_clear();
}
}

Custom LCD character design


Access this website:
http://www.changpuak.ch/electronics/Lcd_custom_character_designer.php

N. M. 39
#include <mega32.h>

// Alphanumeric LCD functions


#include <alcd.h>

// Declare your global variables here


// DEFINE SPECIAL CHARACTERS
typedef unsigned char byte;
// DATA ---------------------------------------
flash byte char0[8]={
0b000001,
0b000010,
0b000100,
0b001001,
0b010010,
0b000100,
0b001000,
0b010000};
// END OF DATA --------------------------------

void define_char(byte flash *pc,byte char_code)


{
byte i,a;
a=(char_code<<3) | 0x40;
for (i=0; i<8; i++)
lcd_write_byte(a++,*pc++);
}

N. M. 40
void main(void)
{
// Declare your local variables here
// Alphanumeric LCD initialization
// Connections are specified in the
// Project|Configure|C Compiler|Libraries|Alphanumeric LCD menu:
// RS - PORTA Bit 0
// RD - PORTA Bit 1
// EN - PORTA Bit 2
// D4 - PORTA Bit 4
// D5 - PORTA Bit 5
// D6 - PORTA Bit 6
// D7 - PORTA Bit 7

// Characters/line: 16
lcd_init(16);

// STORE IN LCD RAM ---------------------------


define_char(char0,5);
lcd_gotoxy(0,0);
lcd_putchar(5);

while (1)
{
// Place your code here

}
}

Exercise
1. Print a message “Happy Birthday” in the first line. And in the second line print
“John”. Blink the message after 500ms delay. Draw the circuit diagram.
2. Print a message “NewMarket” in the first line. The message will scroll over from left
to right and then right to left in the first line.
3. What is an LCD Display?
4. What is the usage of CGROM memory?
5. What are the different modes of LCD Display one can use? Which mode did we use
in our Lab experiment?
6. Describe the functions of the following pins of LCD Display module Vdd, Vee, RS,
R/W’ and D0-D7 pins.
7. What does void lcd_puts(char *str) and, void lcd_gotoxy(unsigned char x, unsigned
char y) functions do?

N. M. 41
CSE 426 Experiment 6: Introduction to Arduino Uno board
Objective
After completing this experiment, student will be able to
• understand the configuration of digital pins of the Arduino board and simulation in Proteus.
• apply serial communication between the Arduino board and a computer for data
transmission.
• understand how to interface push button with Arduino
• understand how to interface Bluetooth Module HC-05 with arduino

Equipment needed
• Arduino Uno board
• Arduino IDE (Compiler)
• Proteus (Simulator)

Part A: Arduino IDE

Two required functions / methods / routines:


void setup()
{
// runs once
}
void loop()
{
// repeats
}

N. M. 42
Figure: Settings: Tools  Serial Port

Your computer communicates to the Arduino microcontroller via a serial port  through a
USB-Serial adapter. Check to make sure that the drivers are properly installed.

Figure : Settings: Tools  Board

Next, double-check that the proper board is selected under the ToolsBoard menu

pinMode(pin, INPUT/OUTPUT);
ex: pinMode(13, OUTPUT);
N. M. 43
digitalWrite(pin, HIGH/LOW);
ex: digitalWrite(13, HIGH);

digitalRead(pin);
ex: digitalRead(13);

delay(time_ms);
ex: delay(2500); // delay of 2.5 sec.

Code: Turns on an LED on for one second, then off for one second, repeatedly.
// the setup function runs once when you press reset or power the board
void setup()
{
// initialize digital pin 13 as an output.
pinMode(13, OUTPUT);
}

// the loop function runs over and over again forever


void loop()
{
digitalWrite(13, HIGH); // turn the LED on (HIGH is the voltage level)
delay(1000); // wait for a second
digitalWrite(13, LOW); // turn the LED off by making the voltage LOW
delay(1000); // wait for a second
}

How to add Arduino Library into Proteus 8


Download Arduino
https://www.arduino.cc/en/Main/Software

Download Arduino library for Proteus


ELMS course website  Proteus library  Arduino library for proteusARDUINO.LIB

Step 1: Copy ARDUINO.LIB in the in to Library folder


If you are using Proteus 8 then Library folder will be within the data Folder
(Proteus 8 Professional\Data\LIBRARY )

N. M. 44
Step 2: Now open Your Proteus and Search Arduino

N. M. 45
Step 3: Make Hex file

Open Arduino Software and Click on file and then Preference and tick both of the Option
"Compilation and Upload " After writing your code, click on compile then you will get the
Link of Your Hex file at the Output go to that place and get your Hex file.

Step 4: Upload Code


It is Time to upload Code to Arduino.

Figure : Arduino uno in proteus

N. M. 46
Part B: Serial communication with Arduino

Figure: Serial communication from Arduino to PC.

If you use Arduino connected to a sensor (see Fig.1), Arduino produce a series of data that may
be sent to a computer to be stored in a file, displayed or processed in some way. If you use the
Arduino connected to an actuator (see Fig.2), such as a stepper motor, most likely, the computer
will send a series of data to the Arduino. The latter will process the received data by converting
suitably into commands to send to the motor to make it move in the amount of necessary steps.

Figure 1

N. M. 47
Figure 2

1. Once the Arduino sketch has been uploaded to the Arduino. Open the Serial monitor,
which looks like a magnifying glass at the top right section of the Arduino IDE.
Please note, that you need to keep the USB connected to the Arduino during this
process, as the USB cable is your communication link between your computer and the
Arduino.

2. Type anything into the top box of the Serial Monitor and press <Enter> on your
keyboard. This will send a series of bytes to the Arduino. The Arduino will respond
by sending back your typed message in the larger textbox.

Figure: Proterus “virtual terminal” serial communication simulation

N. M. 48
Code: Print a single string
void setup()
{
Serial.begin(9600);
}

void loop()
{
Serial.println("Hello from Arduino !!! ");
delay(300);
}

Code: Read a single character


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

void loop()
{
if(Serial.available()>0)
{
char c = Serial.read(); // read a single 'char'
Serial.print("Reply from Arduino: ");
Serial.println(c);
}

}
Code: Read a string
void setup()
{
Serial.begin(9600);
}

void loop()
{
if(Serial.available()>0)
{
String s = Serial.readString(); // read a single 'string'
Serial.print("Reply from Arduino: ");
Serial.println(s);
}
}

Code: Read a digit from Char


void setup()

N. M. 49
{
Serial.begin(9600);
}

void loop()
{
if (Serial.available()>0)
{
int i = Serial.parseInt(); // returns the integer number from the serial buffer
Serial.println(i);
}
delay(300);
}

Code: Read a digit from String


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

void loop()
{
if(Serial.available()>0)
{
String s = Serial.readString(); // read a single 'string'
int i = s.toInt(); // Converts a valid String to an integer.
Serial.print("Reply from Arduino: ");
Serial.println(i);
}
}

Part C: Push button interfacing with Arduino


Internal to the Arduino are pullup resistors with a value around 50k-ohm. These resistors can
be optionally connected internally using INPUT_PULLUP. This is functionally (and
electrically) equivalent to connecting a 50k-ohm resistor between the pin and +5V, the only
difference is that it requires no external components and you can turn it on and off in
software during the execution of the program.

N. M. 50
Figure : Push button with Arduino

This example demonstrates the use of INPUT_PULLUP with pinMode().

Code:
void setup()
{
//start serial connection
Serial.begin(9600);
//configure pin2 as an input and enable the internal pull-up resistor
pinMode(2, INPUT_PULLUP);
pinMode(13, OUTPUT);
}

void loop() {
//read the pushbutton value into a variable
int sensorVal = digitalRead(2);
//print out the value of the pushbutton
Serial.println(sensorVal);

// Keep in mind the pullup means the pushbutton's


// logic is inverted. It goes HIGH when it's open,

N. M. 51
// and LOW when it's pressed. Turn on pin 13 when the
// button's pressed, and off when it's not:
if (sensorVal == LOW)
{
digitalWrite(13, HIGH);
}
else {
digitalWrite(13, LOW);
}
}

Part D: Bluetooth Module HC-05 interfacing with Arduino.


Bluetooth is a standardized protocol (IEEE 802.15.1) for sending and receiving data via a
2.4GHz wireless link. It’s a secure protocol, and it’s perfect for short-range, low-power, low-
cost, wireless transmissions between electronic devices. The range is approximately 10
Meters (30 feet).

HC-05 Specifications
 2.45Ghz Frequency
 Asynchronous Speed 2.1Mbps (max) .160Kbps
 Security: Authentication
 Profile: Bluetooth Serial Port
 Power Supply: +3.3/5 VDc
 Working Temperature: >20C
 It will communicate at 9600 (zs-040) / 38400 baud rate.
 Default password of the HC-05 Bluetooth Module: 1234

Figure: Smart phone communicating with Arduino board via Bluetooth

N. M. 52
Figure : HC-05 Bluetooth module

Figure : schematic diagram

Code:
char data = 0; //Variable for storing received data
void setup()
{
Serial.begin(38400); //Sets the data rate in bits per second (baud) for serial data
transmission
pinMode(13, OUTPUT); //Sets digital pin 13 as output pin
}

N. M. 53
void loop()
{
if(Serial.available() > 0) // Send data only when you receive data:
{
data = Serial.read(); //Read the incoming data and store it into variable data
Serial.write(data); //Print Value inside data in Serial monitor
Serial.print("\n"); //New line

if(data == '1') //Checks whether value of data is equal to 1


{
digitalWrite(13, HIGH); //If value is 1 then LED turns ON
Serial.write("arduno: message received ");
Serial.write(data);
Serial.print("\n"); //New line
Serial.write("arduno: LED is ON");
}

else if(data == '0') //Checks whether value of data is equal to 0


{
digitalWrite(13, LOW); //If value is 0 then LED turns OFF
Serial.write("arduno: message received ");
Serial.write(data);
Serial.print("\n"); //New line
Serial.write("arduno: LED is OFF");
}
}

N. M. 54
Reference
https://www.arduino.cc/
https://www.arduino.cc/en/Reference/Serial
https://www.arduino.cc/en/Tutorial/InputPullupSerial
http://www.meccanismocomplesso.org/en/arduino-tutorial-serial-data-actuator/

CSE 426 Experiment 7: Analog input-output using Arduino Uno board


Objective
After completing this experiment, student will be able to
• explain the function of microcontroller Analog to Digital Converter (ADC)
• understand how to take read from analog sensor
• explain the function of microcontroller Digital to Analog Converter (DAC)
• understand how to use of analog output (Pulse Width Modulation (PWM)) to fade in/out an
LED

Equipment needed
• Arduino Uno board
• Arduino IDE (Compiler)
• Proteus (Simulator)

Voltage divider circuit:

N. M. 55
The circuit shown consists of just two resistors, R1 and R2 connected together in series across
the supply voltage Vin. One side of the power supply voltage is connected to resistor, R1, and
the voltage output, Vout is taken from across resistor R2. The value of this output voltage is
given by the corresponding formula.

Reading Sensors
Many sensors in the real world are simple resistive devices. A photocell is a variable resistor,
which produces a resistance proportional to the amount of light it senses. Other devices
like flex sensors, force-sensitive resistors, and thermistors, are also variable resistors.
There are two types of sensors: Analog sensor and Digital sensor.
 Analog Sensors
There are different types of sensors that produce continuous analog output signal and
these sensors are considered as analog sensors. Practical examples of various types of
analog sensors are as follows: accelerometers, pressure sensors, light sensors, sound
sensors, temperature sensors, and so on.
 Pros
• Usually simple sensor design

 Cons
• Analog signal produced by the analog sensor could be distorted during
long distance transmission.

Thermistor (temperature LDR (Light sensor) Flex sensor


sensor)

N. M. 56
 Digital Sensors
Electronic sensors or electrochemical sensors in which data conversion and data
transmission takes place digitally are called as digital sensors. These digital sensors
are replacing analog sensors as they are capable of overcoming the drawbacks of
analog sensors. The digital sensor consists of majorly three components: senor, cable,
and transmitter. In digital sensors, the signal measured is directly converted into
digital signal output inside the digital sensor itself then this digital signal is
transmitted through cable digitally.

 Pros
• Digital signal produced by the digital sensor could be transmitted long
distance.
 Cons
• Usually complex sensor design.

PIR sensor – Motion Ultrasonic sensor


detector sensor

Light dependent resistor (LDR)

Light dependent resistor (LDR) is used to detect change in light intensity or as a light sensor.
LDR is basically a variable resistor.

LDR resistance changes with the change in intensity of light. If intensity of light falling on
LDR is high, LDR will have low resistance.

When intensity of light decreases, LDR offer high resistance. Hence there is an inverse
relationship between intensity of light and resistance of LDR.

The LDR is a resistor, and its resistance varies according to the amount of light falling on its
surface.

N. M. 57
Figure: LDR

Light Level R2 (Sensor) R1 (Fixed) Vout


Light 1kΩ 5.6kΩ 0.76 V
Dim 7kΩ 5.6kΩ 2.78 V
Dark 10kΩ 5.6kΩ 3.21 V

LDR makes up half of this voltage divider. The voltage is


measured to find the resistance of the light sensor. As the
light intensity increases, the resistance decrease.

N. M. 58
LDR LED

Micro-controller

Micro-controller has both ADC and DAC capability

Analog to digital conversion


The ADC translates the analog waves of your voice into digital data that the computer can
understand. To do this, it samples, or digitizes, the sound by taking precise measurements of
the wave at frequent intervals.

Microcontrollers are capable of detecting binary signals: is the button pressed or not? These
are digital signals. When a microcontroller is powered from five volts, it understands zero
volts (0V) as a binary 0 and a five volts (5V) as a binary 1. The world however is not so
simple and likes to use shades of gray. What if the signal is 2.72V? Is that a zero or a one?
We often need to measure signals that vary; these are called analog signals. A 5V analog
sensor may output 0.01V or 4.99V or anything inbetween. Luckily, nearly all
microcontrollers have a device built into them that allows us to convert these voltages into
values that we can use in a program to make a decision.

An Analog to Digital Converter (ADC) is a very useful feature that converts an analog
voltage on a pin to a digital number. By converting from the analog world to the digital
world, we can begin to use electronics to interface to the analog world around us.

Not every pin on a microcontroller has the ability to do analog to digital conversions. On the
Arduino board, these pins have an ‘A’ in front of their label (A0 through A5) to indicate these
pins can read analog voltages.

N. M. 59
Pulse-code modulation (PCM)
The most widely used technique for digitizing information signals for electronic data
transmission is pulse-code modulation (PCM). PCM signals are serial digital data.

Figure: Block diagram showing Pulse code modulation process

A. Sampling
• Sample is a single measurement of amplitude.
• The larger sampling rate, the better accuracy of conversion.

1010__________________________________________
1001__________________________________________
1000__________________________________________
0111_________________________________________
0110__________________________________________
0101 __________________________________________
0100 __________________________________________
0011 __________________________________________

Measurement
Sound wave of amplitude

Figure: Sampling

N. M. 60
B. Quantization
The quantizing of an analog signal is done by discretizing the signal with a number of
quantization levels. Quantization is representing the sampled values of the amplitude by a
finite set of levels, which means converting a continuous-amplitude sample into a discrete-
time signal.
 Both sampling and quantization result in the loss of information. The quality of a
Quantized output depends upon the number of quantization levels used.
 The difference between an input value and its quantized value is called
a Quantization Error.

The figure shows how an analog signal gets quantized. The blue line represents analog signal
while the brown one represents the quantized signal.

2-bit resolution with four levels


of quantization

Red line: Actual signal


Blue line: Re-constructed signal

N. M. 61
3-bit resolution with eight levels
of quantization

Red line: Actual signal


Blue line: Re-constructed signal

C. Encoding
After the quantization process, the corresponding level is represented using binary numbers.
Encoded result: 10, 11, 11, 10, 01, 00, 00, 01

Arduino ADC
ADCs can vary greatly between microcontroller. The ADC on the Arduino is a 10-bit ADC
meaning it has the ability to detect 1,024 (210) discrete analog levels. Some microcontrollers
have 8-bit ADCs (28 = 256 discrete levels) and some have 16-bit ADCs (216 = 65,535 discrete
levels).
The way an ADC works is fairly complex. There are a few different ways to achieve this feat
(see Wikipedia for a list), but one of the most common technique uses the analog voltage to
charge up an internal capacitor and then measure the time it takes to discharge across an
internal resistor. The microcontroller monitors the number of clock cycles that pass before the
capacitor is discharged. This number of cycles is the number that is returned once the ADC is
complete.

Relating ADC Value to Voltage


The ADC reports a ratiometric value. This means that the ADC assumes 5V is 1023 and
anything less than 5V will be a ratio between 5V and 1023.

Analog to digital conversions are dependant on the system voltage. Because we


predominantly use the 10-bit ADC of the Arduino on a 5V system, we can simplify this
equation slightly:

N. M. 62
If your system is 3.3V, you simply change 5V out with 3.3V in the equation. If your system is
3.3V and your ADC is reporting 512, what is the voltage measured? It is approximately
1.65V.
If the analog voltage is 2.12V what will the ADC report as a value?

Rearrange things a bit and we get:

The ADC should report 434. No fraction value is allowed. Take either floor or celling value.

Figure : Analog to digital conversion

Arduino ADC Example

Figure: Analog pins of Arduino board

N. M. 63
The analog to digital version by using the analogRead()command:

int x = analogRead(A3); //Reads the analog value on pin A3 into x


The value that is returned and stored in x will be a value from 0 to 1023. The Arduino has
a 10-bit ADC (210 = 1024). We store this value into an int because x is bigger (10 bits) than
what a byte can hold (8 bits).
Let’s print this value to watch it as it changes:

Serial.print(“Analog value: “);


Serial.println(x);
As we change the analog value, x should also change. For example, if x is reported to be 334,
and we’re using the Arduino at 5V, what is the actual voltage? Pull out your digital
multimeter and check the actual voltage. It should be approximately 1.63V.
Code
// the setup routine runs once when you press reset:
void setup()
{
// initialize serial communication at 9600 bits per second:
Serial.begin(9600);
}
// the loop routine runs over and over again forever:
void loop()
{
// read the input on analog pin 0:
int sensorValue = analogRead(A0);
// print out the value you read:
Serial.println(sensorValue); // LDR sensor value

delay(50); //short delay for faster response to light.


}

N. M. 64
Figure: Arduino interfacing with LDR

Digital to Analog conversion


If you were to play your recording back through the speakers, the DAC would perform the
same basic steps in reverse. With accurate measurements and a fast sampling rate, the
restored analog signal can be nearly identical to the original sound wave.

• Pulse Width Modulation, or PWM, is a technique for getting digital to analog


conversion.
• Digital control is used to create a square wave, a signal switched between on and off.
This on-off pattern (duty cycle) can simulate voltages in between full on (5 Volts) and
off (0 Volts) by changing the portion of the time the signal spends on versus the time
that the signal spends off. The duration of "on time" is called the pulse width.
• To get varying analog values, you change, or modulate, that pulse width. If you repeat
this on-off pattern fast enough with an LED for example, the result is as if the signal
is a steady voltage between 0 and 5v controlling the brightness of the LED.
• Arduino digital to analog resolution is 8 bit. (0-255)

N. M. 65
Duty cycle
A duty cycle is the fraction of one period in which a signal or system is active. Duty cycle is
commonly expressed as a percentage or a ratio. A period is the time it takes for a signal to
complete an on-and-off cycle.

In the graphic below, the green lines represent a regular time period. This duration or period
is the inverse of the PWM frequency. In other words, with Arduino's PWM frequency at
about 500Hz, the green lines would measure 2 milliseconds each. A call to analogWrite() is
on a scale of 0 - 255, such that analogWrite(255) requests a 100% duty cycle (always on),
and analogWrite(127) is a 50% duty cycle (on half the time) for example.

Figure: Digital to analog conversion

Code: This example shows how to fade an LED using the analogWrite() function.
int ledPin = 9; // LED connected to digital pin 9

void setup()
{
// nothing happens in setup
}

void loop()
N. M. 66
{
// fade in from min to max in increments of 5 points:
for (int fadeValue = 0 ; fadeValue<= 255; fadeValue += 5)
{
// sets the value (range from 0 to 255):
analogWrite(ledPin, fadeValue);
// wait for 30 milliseconds to see the dimming effect
delay(30);
}

// fade out from max to min in increments of 5 points:


for (int fadeValue = 255 ; fadeValue>= 0; fadeValue -= 5)
{
// sets the value (range from 0 to 255):
analogWrite(ledPin, fadeValue);
// wait for 30 milliseconds to see the dimming effect
delay(30);
}
}

PWM supporting digital pins are: 3, 5, 6, 9, 10, 11

Exercise
1. Explain the steps, how Analog to Digital converter in Arduino work? Draw the block
diagram.
2. What is Duty cycle? Explain with a diagram how duty cycle will be used to control
the brightness of LED.

N. M. 67
CSE 426 Experiment 8: Receive Humidity and Temperature update
from one Arduino board to another Arduino board using I2C
communication protocol
Objective
After completing this experiment, student will be able to
• explain the overview of I2C communication protocol and how to configure in Arduino
board
• explain how to interface DHT11 sensor with Arduino board
• apply I2C communication protocol for transmitting and receiving data

Equipment needed
• Arduino Uno board (two)
• Humidity and Temperature Sensor DHT11
• Arduino IDE (Compiler)
• Proteus (Simulator)

I2C
The Inter-integrated Circuit (I2C) Protocol is a protocol intended to allow multiple “slave”
digital integrated circuits (“chips”) to communicate with one or more “master” chips. Like
the Serial Peripheral Interface (SPI), it is only intended for short distance communications
within a single device. Like Asynchronous Serial Interfaces (such as RS-232 or UARTs), it
only requires two signal wires to exchange information.
I2C requires a mere two wires, like asynchronous serial, but those two wires can support up to
1008 slave devices. Also, unlike SPI, I2C can support a multi-master system, allowing more
than one master to communicate with all devices on the bus (although the master devices
can’t talk to each other over the bus and must take turns using the bus lines).
Data rates fall between asynchronous serial and SPI; most I2C devices can communicate at
100kHz to 400kHz.

Figure: I2C Protocol

N. M. 68
The I2C protocol involves using two lines to send and receive data: a serial clock pin (SCL)
and a serial data pin (SDA) over which data is sent between the two devices.
Each Slave device has to have its own unique address and both master and slave devices need
to take turns communicating over the same data line. In this way, it is possible Arduino
boards to communicate with many device or other boards using just two pins of the
microcontroller, using each device's unique address.

I2C frame format


With I2C, data is transferred in messages. Messages are broken up into frames of data. Each
message has an address frame that contains the binary address of the slave, and one or more
data frames that contain the data being transmitted. The message also includes start and stop
conditions, read/write bits, and ACK/NACK bits between each data frame.

Figure: Instruction sequence data from master to slave

Steps of I2C of data transmission


1. The master sends the start condition to every connected slave by switching the SDA line
from a high voltage level to a low voltage level before switching the SCL line from high to
low.

Figure: Send “Start” frame

2. The master sends each slave the 7 or 10 bit address of the slave it wants to communicate
with, along with the read/write bit.

N. M. 69
Figure: Send “Slave address” frame

3. Each slave compares the address sent from the master to its own address. If the address
matches, the slave returns an ACK bit by pulling the SDA line low for one bit. If the address
from the master does not match the slave’s own address, the slave leaves the SDA line high.

Figure: Receive ACK bit from Slave 3

4. The master sends or receives the data frame.

N. M. 70
Figure: Send and Receive data frame to Slave 3

5. After each data frame has been transferred, the receiving device returns another ACK bit to
the sender to acknowledge successful receipt of the frame.

Figure: Slave 3 send ACK bit

6. To stop the data transmission, the master sends a stop condition to the slave by switching
SCL high before switching SDA high.

N. M. 71
Connection PINs
Connect pin 5 (the clock, or SCL, pin) and pin 4 (the data, or SDA, pin) on the master
Arduino to their counterparts on the slave board. Make sure that both boards share a common
ground. In order to enable serial communication, the slave Arduino must be connected to
your computer via USB.

Schematic diagram

N. M. 72
Scenario 1
Two Arduino board are communicating using I2C protocol. Transmitter is transmitting a
HIGH value for 1 second interval, when the receiver receives the value, it keeps the LED ON
for 1 second to indicate that it successfully received the value.

Master Writer Code - Program for Arduino


#include <Wire.h>

void setup()
{
Wire.begin(); // join i2c bus (address optional for master)
Serial.begin(9600); // start serial for output
}

void loop()
{
Wire.requestFrom(8, 6); // request 6 bytes from slave device #8
while (Wire.available())
{
// slave may send less than requested
char c = Wire.read(); // receive a byte as character
Serial.print(c); // print the character
}

delay(500);
}

N. M. 73
Slave Sender Code - Program for Arduino
#include <Wire.h>

void setup()
{
Wire.begin(8); // join i2c bus with address #8
Wire.onRequest(requestEvent); // register event
}

void loop()
{
delay(100);
}

// function that executes whenever data is requested by master


// this function is registered as an event, see setup()
void requestEvent()
{
Wire.write ("hello "); // respond with message of 6 bytes as expected by master
}

Humidity and Temperature Sensor DHT11


These DHTXX sensors are very popular for measuring temperature and humidity. These
sensors contain a chip that does analog to digital conversion and outputs a digital signal with
the temperature and humidity.

The DHT22 is the more expensive version, which obviously has better specifications. Its
temperature measuring range is from -40 to +125 degrees Celsius with +/- 0.5 degree
accuracy, while the DHT11 temperature range is from 0 to 50 degrees Celsius with +/- 2
degree accuracy. In addition, the DHT22 sensor has better humidity measuring range, from 0
to 100% with 2-5% accuracy, while the DHT11 humidity range is from 20%-80% with 5%
accuracy.

There are two specifications where the DHT11 is better than the DHT22. That is the sampling
rate, which for the DHT11 is 1Hz or one reading every second, while the DHT22 sampling
rate is 0,5Hz or one reading every two seconds and the DHT11 has smaller body size. The
operating voltage of both sensors is from 3 to 5 volts, while the max current used when
measuring is 2.5mA.

Figure : DHT 11 pin configuration

N. M. 74
Comparison between DHT 11 and DHT 22
DHT11 DHT22
 Ultra low cost  Low cost
 3 to 5V power and I/O  3 to 5V power and I/O
 2.5mA max current use during  2.5mA max current use during
conversion (while requesting data) conversion (while requesting data)
 Good for 20-80% humidity readings  Good for 0-100% humidity readings
with 5% accuracy with 2-5% accuracy
 Good for 0-50°C temperature readings  Good for -40 to 80°C temperature
±2°C accuracy readings ±0.5°C accuracy
 No more than 1 Hz sampling rate (once  No more than 0.5 Hz sampling rate
every second) (once every 2 seconds)
 Body size 15.5mm x 12mm x 5.5mm  Body size 15.1mm x 25mm x 7.7mm
 4 pins with 0.1" spacing  4 pins with 0.1" spacing

Adding the DHT11 library


Download DHT.zip from ELMS folder DHT library. In the Arduino IDE, go to Sketch >>
Include Library >> Add ZIP file. Check this video tutorial.
How to add libraries in Arduino software
https://www.youtube.com/watch?v=WfBUi4smztg

Figure : DHT11 sensor interfacing with Arduino board

N. M. 75
Figure: DHT11 sensor data (temperature and humidity) transmitted from one Arduino board
to another Arduino board

Scenario 1
There are two separate Arduino board. Arduino board A (Master) sends a request for
12 byte data to Arduino board B (Slave). Arduino board B process this request and
send a reply.

Master Receiver Code - (Receive DHT11 data update)


#include <Wire.h>

void setup()
{
Wire.begin(); // join i2c bus (address optional for master)
Serial.begin(9600); // start serial for output
}

void loop()
{
Wire.requestFrom(8, 12); // request 12 bytes from slave device #8

while (Wire.available()>0)
{
// slave may send less than requested
String msg = Wire.readString(); // receive a byte as character
Serial.println(msg); // print the character
}
delay(500);

N. M. 76
Slave Sender Code (Transmit DHT11 data update)
#include <Wire.h>
#include <dht.h>

dht DHT;
String Humidity;
String Temparature;

void setup()
{
Wire.begin(8); // join i2c bus with address #8
Wire.onRequest(requestEvent); // register event
}

void loop()
{
delay(500);

DHT.read11(8); // sensor is connected to digital Pin 8,

Serial.print("Current humidity = ");


Serial.print(DHT.humidity);
Humidity = DHT.humidity;
Serial.print("% ");
Serial.print("temperature = ");
Serial.print(DHT.temperature);
Temparature = DHT.temperature;
Serial.println("C ");
}

// function that executes whenever data is requested by master


// this function is registered as an event, see setup()
void requestEvent()
{
Wire.write(Humidity.c_str()); // StringObject Function
}

Exercise
1. In the following experiment Humidity data is transmitted and received. Modify the
code so that Humidity and temperature data is transmitted and received. Complete
simulation and hardware implementation.

Reference
Basics of I2C communication protocol
http://www.circuitbasics.com/basics-of-the-i2c-communication-protocol/
N. M. 77
Complete Guide for DHT11/DHT22 Humidity and Temperature Sensor With Arduino
https://randomnerdtutorials.com/complete-guide-for-dht11dht22-humidity-and-temperature-
sensor-with-arduino/

N. M. 78
CSE 426 Experiment 9: Transmit and receive distance measurement
to an object from one Arduino board to another Arduino board using
RF 433MHz Transmitter/Receiver module
Objective
After completing this experiment, student will be able to
• understand how ultrasonic sensors work
• explain how to interface ultrasonic sensor with Arduino board
• explain how to interface RF 433MHz Transmitter/Receiver module with Arduino board
• apply RF 433MHz module to send data to multiple receiver

Equipment needed
• Arduino Uno board (two)
• Ultrasonic Ranging Module (HC-SR04)
• RF Transmitter Receiver Pair 433 MHz - RXB6
• Arduino IDE (Compiler)
• Proteus (Simulator)

Ultrasonic sensor
It detects the distance of the closest object in front of the sensor (from 3 cm up to 400 cm). It
works by sending out a burst of ultrasound and listening for the echo when it bounces off of
an object. It pings the obstacles with ultrasound. The Arduino board sends a short pulse to
trigger the detection, then listens for a pulse on the same pin using the pulseIn() function.
The duration of this second pulse is equal to the time taken by the ultrasound to travel to the
object and back to the sensor. Using the speed of sound, this time can be converted to
distance.

Figure: HC-SR04 Ultrasonic Sensor (4 pin)

Ultrasonic Sensor Pin Configuration


Pin Pin Description

N. M. 79
Number Name
1 Vcc The Vcc pin powers the sensor, typically with +5V
2 Trigger Trigger pin is an Input pin. This pin has to be kept high for 10us to
initialize measurement by sending Ultrasonic wave.
3 Echo Echo pin is an Output pin. This pin goes high for a period of time which
will be equal to the time taken for the US wave to return back to the
sensor.
4 Echo This pin is connected to the Ground of the system.
pulseIn() function: Reads a pulse (either HIGH or LOW) on a pin. For example,
if value is HIGH, pulseIn() waits for the pin to go from LOW to HIGH, starts timing, then
waits for the pin to go LOW and stops timing. Returns the length of the pulse in
microseconds or gives up and returns 0 if no complete pulse was received within the timeout.
https://www.arduino.cc/reference/en/language/functions/advanced-io/pulsein/

Figure : Ultrasonic Sensor Working Principle

Ultrasonic Sensor Working Principle


 Ultrasonic sensor transmits sound waves.
 These waves are reflected back from the surface of an object.
 Ultrasonic sensors receives the reflected waves.

N. M. 80
 Then it measures the time elapsed during the entire process, from transmission to
receiving, it is known as round trip time.
 This time is equal to the distance between an object and the sensor itself.

Figure: HC-SR04 Ultrasonic Sensor interfacing with Arduino

Proteus Simulation
Download UltrasonicSensor Library for Proteus from ELMS folder Proteus library>>
UltrasonicSensor Library for Proteus, which contains UltraSonicTEP.LIB and
UltraSonicSensor.HEX. Copy UltraSonicTEP.LIB in the Proteus LIBRARY folder.

N. M. 81
Code:
void setup()
{
pinMode(12, OUTPUT); // Sets the trigPin as an Output
pinMode(11, INPUT); // Sets the echoPin as an Input
Serial.begin(9600); // Starts the serial communication
}

void loop()
{
// Clears the trigPin
digitalWrite(12, LOW);
delayMicroseconds(2);

// Sets the trigPin on HIGH state for 10 micro seconds


digitalWrite(12, HIGH);
delayMicroseconds(10);
digitalWrite(12, LOW);

// Reads the echoPin, returns the sound wave travel time in microseconds
long duration = pulseIn(11, HIGH);

// Calculating the distance


long distance= (duration*0.034)/2; //The speed of sound is 340 meter/second or 0.0343
cm/microsecond
// Prints the distance on the Serial Monitor
Serial.print("Distance from the object = ");
Serial.print(distance);
Serial.println(" cm");
delay(1000);
}

HC-SR04 Sensor Features


 Operating voltage: +5V
 Theoretical Measuring Distance: 2cm to 450cm
 Practical Measuring Distance: 2cm to 80cm
 Accuracy: 3mm
 Measuring angle covered: <15°
 Operating Current: <15mA
 Operating Frequency: 40Hz

RF Transmitter Receiver Pair 433 MHz - RXB6


The RF module operates at Radio Frequency. The corresponding frequency range varies
between 30 kHz & 300 GHz. In this RF system, the digital data is represented as variations in
the amplitude of carrier wave. This kind of modulation is known as Amplitude Shift Keying
(ASK).

N. M. 82
Transmission through RF is better than IR (infrared) because of many reasons. Firstly, signals
through RF can travel through larger distances making it suitable for long-range applications.
In addition, while IR mostly operates in line-of-sight mode, RF signals can travel even when
there is an obstruction between transmitter & receiver. Next, RF transmission is more strong
and reliable than IR transmission. RF communication uses a specific frequency unlike IR
signals, which are affected, by other IR emitting sources.

Figure: Transmitter Figure: Receiver

This RF module comprises of an RF Transmitter and an RF Receiver. The


transmitter/receiver (Tx/Rx) pair operates at a frequency of 433 MHz. Generally, the usage of
frequencies is restricted by authorities in each country. The 433 MHz is within industrial,
scientific, and medical radio band (ISM band) which is free to use in many countries
including Bangladesh.

An RF transmitter receives serial data and transmits it wirelessly through RF through its
antenna. The transmission occurs at the rate of 1Kbps - 10Kbps.The transmitted data is
received by an RF receiver operating at the same frequency as that of the transmitter.
JMR-TX1 transmitter pinouts: RXB6 receiver pinouts:
ANT - Antenna Pin 1 = ANT - Antenna
Ground Pin 2 = Ground
Data Pin 3 = Ground
VDD = Power Supply Pin 4 = Power Supply
Transmitter Specs: Pin 5 = Power Supply
Transmitter: JMR-TX1 Pin 6 = DER - Options: 1) Data output-default; 2)
Operating voltage: 3-12V Battery Saving Mode
Operating Pin 7 = Data Output
frequency:433MHZ Pin 8 = Ground
Transmission distance:300-
500m Receiver Specs:
Operating temperature :- Receiver:RXB6
20℃~60℃ Working voltage: 5.0VDC +0.5V
Dimensions:11*16*5.5mm Working current: ≤2.5mA (5.0VDC)
Input signal :TTL level Working principle: superheterodyne
Modulation system :ASK Working method: OOK/ASK
modulate rate:3KB/S Operating frequency: 433MHz
frequency stability:±75KHZ
Transmitted
Power:≥10mw
Pins : 4

N. M. 83
Applications
The 433MHz transceiver/receiver modules are used on a wide variety of applications that
require wireless control.
 Wireless security systems
 Car alarm systems
 Car remote door switch (RKE)
 Remote controls
 Sensor reporting
 Automation systems

Figure: RF Transmitter Receiver module interface with Arduino boards

Proteus Simulation
Download UltrasonicSensor Library for Proteus from ELMS folder Proteus library>>
Module_RF Library for Proteus, which contains LIBRARY, MODELS folder and
Readme.txt. Carefully read Readme.txt file and follow the instruction provided.

Scenario 1
Transmitter and receiver RF module is connected with two separate Arduino module.
Transmitter is transmitting a HIGH value for 1 second interval, when the receiver receives
the value, it keeps the LED ON for 1 second to indicate that it successfully received the
value.
Code: Transmitter is sending HIGH and LOW value on pin 13
void setup()
{
// initialize digital pin LED_BUILTIN as an output.
pinMode(13, OUTPUT);
}

void loop()
{
digitalWrite(13, HIGH); // turn the LED on (HIGH is the voltage level)
delay(1000); // wait for a second
digitalWrite(13, LOW); // turn the LED off by making the voltage LOW
delay(1000); // wait for a second
}

N. M. 84
Code: Receiver receives the value and check if HIGH then LED is ON else OFF.
#define rfReceivePin A0 //RF Receiver pin = Analog pin 0
#define ledPin 13 //Onboard LED = digital pin 13

unsigned int data = 0; // variable used to store received data


const unsigned int upperThreshold = 70; //upper threshold value
const unsigned int lowerThreshold = 50; //lower threshold value

void setup()
{
pinMode(ledPin, OUTPUT);
Serial.begin(9600);
}

void loop()
{
data=analogRead(rfReceivePin); //listen for data on Analog pin 0

if(data>0)
{
digitalWrite(ledPin, HIGH); //If a HIGH signal is received, turn LED ON
Serial.println(data);
delay(500);

}
else
{
digitalWrite(ledPin, LOW); //If a LOW signal is received, turn LED OFF
Serial.println(data);
//delay (500);
}
}

Scenario 2
Transmitter and receiver RF module is connected with two separate Arduino board.
Transmitter of arduino board A is transmitting a string value for 1 second interval, when the
receiver of Arduino board B receives the value, it is visible in the serial monitor.

VirtualWire
VirtualWire is an Arduino library that provides features to send short messages, without
addressing, retransmit or acknowledgment, a bit like UDP over wireless, using ASK
(amplitude shift keying).
Downloading and installation of VirtualWire
Download the VirtualWire distribution from
http://www.airspayce.com/mikem/arduino/VirtualWire/VirtualWire-1.27.zip
In the Arduino IDE, go to Sketch >> Include Library >> Add ZIP file. Check this video
tutorial.
How to add libraries in Arduino software
https://www.youtube.com/watch?v=WfBUi4smztg

N. M. 85
Configuration Functions
vw_set_tx_pin(transmit_pin)
Configure the transmit pin. Default is pin 12.
vw_set_rx_pin(receive_pin)
Configure the receive pin, Default is pin 11. On Teensy 2.0, pin 11 should not be used
because most receiver modules can not work correctly with the orange LED on that pin.
vw_set_ptt_pin(transmit_en_pin)
Configure the transmit enable pin, or "push to talk". Default is pin 10.
vw_set_ptt_inverted(true)
Configure the "push to talk" polarity.
vw_setup(2000)
Begin using all settings and initialize the library. This is similar to the "begin" function of
other libraries. All pins should be configured before calling this function.

Transmission Functions
vw_send(message, length)
Transmit a message. "message" is an array of the bytes to send, and "length" is the number of
bytes stored in the array. This function returns immediately and the message is sent slowly by
an interrupt-based background process.
vw_tx_active()
Returns true if the message is being sent, or false if the transmitter is not active. You can use
this after sending a message to test when it has finished being transmitted.
vw_wait_tx()
Wait for a message to be fully transmitted. Often the simplest approach is to call this after
vw_send.

Reception Functions
vw_rx_start()
Activate the receiver process. You must call this function before any reception can occur. An
interrupt-based background process is started which monitors the reception of data.
vw_have_message()
Returns true if message has been received. This is similar to the "available" function of most
other libraries.
vw_wait_rx()
Wait for a message to be received. This will only return when a message has been received,
otherwise it will wait forever.
vw_wait_rx_max(timeout_ms)
Wait for a message, but give up after "timeout_ms". Returns true if a message was received,
or false if the timeout period elapsed.
vw_get_message(buf, &buflen))
Read the last received message. This should be called only when a message is known to be
received with any of the 3 functions above. "buf" is an array where the message is copied.
"buflen" should have the array's maximum size upon input, and upon return the number of
bytes actually copied is retured. The function itself returns true if the message was verified
correct, or false if a message was received but appears to have been corrupted.

N. M. 86
vw_rx_stop()
Disable the receiver process.
Sender code
#include <VirtualWire.h>

void setup()
{
Serial.begin(9600);
vw_set_ptt_inverted(true);
vw_setup(2000);
vw_set_tx_pin(12);
}

void loop()
{
char msg[7] = {'h','e','l','l','o',' ','#'};
vw_send((uint8_t *)msg, 7);
delay(1000); //delay of 3 seconds
}

Receiver code
#include <VirtualWire.h>
int i;

void setup()
{
Serial.begin(9600);
vw_set_ptt_inverted(true);
vw_setup(2000);
vw_set_rx_pin(11);
vw_rx_start();
}

void loop()
{
uint8_t buf[VW_MAX_MESSAGE_LEN];
uint8_t buflen = VW_MAX_MESSAGE_LEN;
if (vw_get_message(buf, &buflen))
{
Serial.print("Got: ");

for ( i = 0; i < buflen; i++)


{
char ch = buf[i];
Serial.print(ch);
Serial.print(' ');
}
Serial.println();
}
}

N. M. 87
Exercise
1. Suppose two Arduino boards are communicating using RF. Arduino board A has
ultrasonic sensor and it is sending the distance measurement of an object through RF
transmitter. Arduino board B has a RF receiver and receives the update from board B.
Write down the code. Complete simulation and hardware implementation.

2. Send different data from one RF transmitter to multiple receivers using Arduino.
Show simulation and hardware implementation. For demonstration check this video
link. https://www.youtube.com/watch?v=h3OevEdl674

Reference
BRTC
http://www.btrc.gov.bd/sites/default/files/National%20Frequency%20Allocation%20Plan%2
8NFAP%29_1.pdf
Arduino RF Communication Tutorial
https://www.instructables.com/id/Arduino-RF-Communication-Tutorial/
VirtualWire Library
https://www.pjrc.com/teensy/td_libs_VirtualWire.html
433 MHz radio modules using the VirtualWire library
https://www.arduinoslovakia.eu/blog/2017/5/radio-moduly-433-mhz-pomocou-kniznice-
virtualwire?lang=en

N. M. 88
CSE 426 Experiment 10: Led interfacing with Raspberry pi

Objective
After completing this experiment, student will be able to
• understand the configuration of the Raspberry pi and how to interface with Led

Equipment needed
• Raspberry Pi board
• Led

Raspberry pi board
The Raspberry Pi is a low cost, credit-card sized computer that plugs into a computer monitor
or TV, and uses a standard keyboard and mouse. It is a capable little device that enables
people of all ages to explore computing, and to learn how to program in languages like
Scratch and Python. It’s capable of doing everything you’d expect a desktop computer to do,
from browsing the internet and playing high-definition video, to making spreadsheets, word-
processing, and playing games.

Features of Raspberry pi Model 3

 CPU: 4× ARM Cortex-A53, 1.2GHz.


 GPU: Broadcom VideoCore IV.
 RAM: 1GB LPDDR2 (900 MHz)
 Networking: 10/100 Ethernet, 2.4GHz 802.11n wireless.
 Bluetooth: Bluetooth 4.1 Classic, Bluetooth Low Energy.
 Storage: microSD.
 GPIO: 40-pin header, populated.

Operating system installation

1 Downloading Raspbian and Image writer


Download the latest version of Raspbian from here
(https://www.raspberrypi.org/downloads/raspbian/).

You will be needing an image writer to write the downloaded OS into the SD card (micro SD card
in case of Raspberry Pi B+ model). So download the "win32 disk imager" from here.
http://sourceforge.net/projects/win32diskimager/
N. M. 89
2 Writing the image

Insert the SD card into the laptop/pc and run the image writer. Once open, browse and select
the downloaded Raspbian image file. Select the correct device, that is the drive representing the
SD card. If the drive (or device) selected is different from the SD card then the other selected
drive will become corrupted. SO be careful.
After that, click on the "Write" button in the bottom. As an example, see the image below, where
the SD card (or micro SD) drive is represented by the letter "G:\"

Once the write is complete, eject the SD card and insert it into the Raspberry Pi and turn it on. It
should start booting up.

3 Setting up the Pi

Please remember that after booting the Pi, there might be situations when the user credentials
like the "username" and password will be asked. Raspberry Pi comes with a default user name
and password and so always use it whenever it is being asked. The credentials are:

login: pi

password: raspberry

startx

N. M. 90
Figure: Raspberry pi

Raspberry pi pin configuration

GPIO pins
One powerful feature of the Raspberry Pi is the row of GPIO (general purpose input/output)
pins along the top edge of the board.

These pins are a physical interface between the Pi and the outside world. At the simplest
level, you can think of them as switches that you can turn on or off (input) or that the Pi can

N. M. 91
turn on or off (output). Of the 40 pins, 26 are GPIO pins and the others are power or ground
pins. These pins can be configured in two ways.
The GPIO.BOARD option specifies the pins by the number of the pin. For example, the
numbers printed on the board inside the circle (e.g. 1, 2). See GPIO pin out diagram.
The GPIO.BCM option means that the “Broadcom SOC channel” number refers the pins;
these are the numbers after "GPIO" in the rectangle. See GPIO pin out diagram.

Code
import RPi.GPIO as GPIO ## Import GPIO Library
import time ## Import 'time' library (for 'sleep')

GPIO.setmode(GPIO.BOARD) ## Use BOARD pin numbering


GPIO.setup(7, GPIO.OUT) ## Set pin 7 to OUTPUT

for i in range (0, 20): ## Repeat 20 times


GPIO.output(7, GPIO.HIGH) ## Turn on GPIO pin (HIGH)
time.sleep(1) ## Wait 1 second
GPIO.output(7, GPIO.LOW) ## Turn off GPIO pin (LOW)
time.sleep(1) ## Wait 1 second

GPIO.cleanup() ## Cleanup

N. M. 92
DHT11
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.
The DHT11 measures temperature with a surface mounted NTC temperature sensor
(thermistor) built into the unit.

Figure : DHT11 sensor

Here are the ranges and accuracy of the DHT11:


Humidity Range: 20-90% RH
Humidity Accuracy: ±5% RH
Temperature Range: 0-50 °C
Temperature Accuracy: ±2% °C
Operating Voltage: 3V to 5.5V

Code: https://github.com/szazo/DHT11_Python
import RPi.GPIO as GPIO
import dht11

# initialize GPIO
GPIO.setmode(GPIO.BCM)
GPIO.cleanup()

# read data using pin 14


instance = dht11.DHT11(pin = 14)
result = instance.read()

if result.is_valid():
print("Temperature: %-3.1f C" % result.temperature)
print("Humidity: %-3.1f %%" % result.humidity)
else:
print("Error: %d" % result.error_code)

N. M. 93

You might also like