You are on page 1of 89

Chapter 6

HARDWARE INTERFACING

Chapter Objectives

Serial Port Programming


Interrupt Programming
LCD interfacing
Keypad interfacing
ADC, DAC and sensor interfacing
Relay interface and Motor Control

Serial port programming


The two most basic types of communication are serial and parallel.
They are so common that even the cabling use the name serial
cable and parallel cable.
Since electricity behaves according to the laws of physics, it is
impossible to get the electrical signal to go any faster.
There are two ways to get the data from one place to the other
faster. The first is to squish the data bits tighter together (leave less
distance between them when they travel down the wire). The
second way is to transmit more bits simultaneously.

Two ways of computer data transfer:


1.

Parallel
- 8 or more wire line used to transfer data. E.g.
Printers & hard disk

2.

Serial
- data sent one bit at a time. E.g. data communication
between 2 computer.

Serial Vs. Parallel


Parallel

Serial

More wire use

Less wire used

8 bit data transfer

1 bit data transfer

Fast data transmission

Slow data transmission

Expensive

Cheaper

Serial versus Parallel Data Transfer

Serial Port Basics (Synchronous vs.


asynchronous communication)
2 methods, asynchronous and synchronous
synchronous method transfers a block of data
(characters) at a time
asynchronous method transfers a single byte at a time
Uses special IC chips called UART (universal
asynchronous receiver-transmitter) and USART
(universal synchronous-asynchronous receivertransmitter)
PIC chips has a built-in UART

Fundamental of serial communication

Simplex transmission
- Data is transmitted from the sender to receiver only
- The communication can only take place in one direction
and it is not possible for the receiver to send data back.

Half-Duplex
&
Full-Duplex

Half- and full-duplex transmission


if the data can be transmitted and received, it is a
duplex transmission
simplex transmissions the computer only sends data
duplex transmissions can be half or full duplex
depends on whether or not the data transfer can be
simultaneous
If one way at a time, it is half duplex
If can go both ways at the same time, it is full duplex
full duplex requires two wire conductors for the data
lines (in addition to the signal ground)

Asynchronous serial communication and


data frame
data coming in 0s and 1s
to make sense of the data sender and
receiver agree on a set of rules
Protocol
how the data is packed
how many bits/character
when the data begins and ends

Start and stop bits


asynchronous method, each character is
placed between start and stop bits
called framing
start bit is always one bit
stop bit can be one or two bits
start bit is always a 0 (low)
stop bit(s) is 1 (high)
LSB is sent out first
Framing ASCII A (41H)

in modern PCs one stop bit is standard


when transferring a text file of ASCII characters
using 1 stop bit there is total of 10 bits for each
character
8 bits for the ASCII code (1 parity bit), 1 bit each for
the start and stop bits
for each 8-bit character there are an extra 2 bits,
which gives 20% overhead

Data transfer rate


rate of data transfer bps (bits per second)
widely used terminology for bps is baud
rate
baud and bps rates are not necessarily
equal
baud rate is defined as the number of
signal changes per second

RS232 standard
RS232 standard using DB25
connector

RS232 standard using DB9 connector

RS232 standards
most widely used serial I/O interfacing standard
input and output voltage levels are not TTL compatible

1 bit is represented by -3 to -25 V


0 bit is +3 to +25 V
-3 to +3 is undefined
to connect RS232 to a microcontroller system must use voltage
converters such as MAX232 to convert the TTL logic levels to the
RS232 voltage levels, and vice versa
MAX232 IC chips are commonly referred to as line drivers

Data communication classification

DTE (data terminal equipment)


DCE (data communication equipment)
DTE - terminals and computers that send and receive data
DCE - communication equipment responsible for
transferring the data
simplest connection between a PC and microcontroller
requires a minimum of three pins, TxD, RxD, and ground

Null Modem
Connection

The use of MAX232 chips

MAX232

converts from RS232 voltage levels to TTL voltage


levels
uses a +5 V power source
MAX232 has two sets of line drivers for transferring
and receiving data
line drivers used for TxD are called T1 and T2
line drivers for RxD are designated as R1 and R2
T1 and R1 are used together for TxD and RxD of the
PIC
second set is left unused

RS232 handshaking signals


Examining RS232 hand-shaking signals
many of the pins of the RS-232 connector are
used for handshaking signals
they are not supported by the 8051 UART chip

Connection PIC18 to RS232

Baud Rate in PIC18


The USART (Universal Synchronous Asynchronous Receiver) in
PIC18 has both synchronous and asynchronous features.
The asynchronous mode can be used to connect the PIC18-based
system to serial port for the purpose of full-duplex serial data
transfer.
6 major registers are associated with the UART are:
- SPBGR ( serial port baud rate generator)
- TXREG (transfer register)
- RCREG (receiver register)
- TXSTA (transmit status and control register)
- RCSTA (receive status and control register)
-PIR1 (peripheral interrupt request register 1)

Serial Programming in C
Programming in C programming
a. To transfer data serially
b. To receive data serially
c. To transmit and receive connected to pc com port

using hyper terminal

a. To transfer data serially

b. To receive data serially

Interrupt Programming
Interrupts are mechanisms which enable instant
response to events such as counter overflow, pin
change, data received, etc.
In normal mode, microcontroller executes the main
program as long as there are no occurrences that
would cause an interrupt.
Upon interrupt, microcontroller stops the execution of
main program and commences the special part of the
program(ISR) which will analyze and handle the
interrupt.

PIC can serve multiple devices using


mechanisms of
Polling
PIC continuously monitors the status of each
device
Each device get the attention of the CPU as the
same level of priority
Wastes u-Controllers time by polling devices that
do not need service.

Interrupt
Devices get the attention of the CPU only when it
needs a service
Can service many devices with different level of
priorities

Why interrupts over polling? Because polling


Ties up the CPU in one activity
Uses cycles that could be used more effectively
Code cant be any faster than the tightest polling
loop

Bottom line: an interrupt is an asynchronous


subroutine call (triggered by a hardware event) that
saves both the return address and the system status

Interrupt service routine (ISR)


When an interrupt is
invoked the uC runs the
Interrupt Service
Routine(ISR)
Interrupt vector table
holds the address of ISRs
Power-on Reset 0000h
High priority interrupt 0008h
Low priority interrupt 0018h

When an Interrupt Occurs


Finish the current instruction
Save minimal state information on stack
Transfer to the interrupt handler, also known as the interrupt

service routine (ISR)

Steps in executing Interrupts

Steps in executing Interrupts (simplified)


Upon activation of interrupt the microcontroller
Finishes executing the current instruction
Pushes the PC of next instruction in the stack
Jumps to the interrupt vector table to get the address of ISR
and jumps to it
Begin executing the ISR instructions to the last instruction of
ISR (RETFIE)
Executes RETFIE
Pops the PC from the stack
Starts to execute from the address of that PC

PIC18 Interrupt Sources


External sources
Three pins of PORTB
RB0/INTO, RB1/INT1,and RB2/INT2
Can be used to connect external interrupting sources
Keypads or switches

PORTB Interrupt (RBI)


Change in logic levels of pins RB4-RB7

Internal peripheral sources


Examples

Timers
A/D Converter
Serial I/O
CCP (compare capture pulse-width-modulation)

Special Function Registers (SFRs)


RCON
Priority Enable

INTCON
External interrupt sources

IPR, PIE, and PIR


Internal peripheral interrupts

Valid interrupt
Interrupt request bit (flag)
Interrupt enable bit
Priority bit

INTERUPT
LABEL

REGISTER
CODE

INTERRUPT
SOURCE

INT_EXT

0x0B10

External interrupt has been detected

INT_RB

0x0B08

Change on Port B has been detected

INT_RTCC

0x0B20

Timer 0 has overflowed (same as TIMER0

INT_TIMER0

0x0B20

Timer 0 has overflowed (same as RTCC)

INT_TIMER1

0x8C10

Timer 1 has overflowed

INT_CCP1

0x8C04

Timer 1 matches preset value?

INT_TIMER2

0x8C02

Timer 2 has overflowed

INT_CCP2

0x8D01

Timer 2 matches preset value?

INT_AD

0x8C40

Analogue to digital converter has finished

INT_SSP

0x8C08

Serial data has been received

INT_PSP

0x8C80

Data ready at parallel serial port

INT_EEPROM

0x8D10

Data EEPROM write completed

Enabling and disabling interrupt


Set the GIE bit from
INTCON REG
Set the IE bit for
that interrupt
If the interrupt is
one of the
peripheral (timers
1,2 , serial,etc ) set
PEIE bit from
INTCON reg

INTCON ( interrupt
control register)

In general, interrupt sources have three bits to control


their operation. They are:
Flag bit
to indicate that an interrupt event occurred
Enable bit
that allows program execution to branch to the
interrupt vector address when the flag bit is set
Priority bit
to select high priority or low priority

Interrupt priority in PIC18


What happens when 2 interrupt are
activated at the same time?
Which of these 2 interrupt activated first?

2 level of interrupt priority:


1. low level
2. high level
Interrupt vector level

Interrupt priorities
High-priority interrupt vector 000008H
Low-priority interrupt vector 000018H
A high-priority interrupt can interrupt a low-priority
interrupt in progress.
Interrupt priority enable
Bit7 (IPEN) in RCON register

RCON

Multiple Interrupt Sources


All interrupt requests are directed to one of two
memory locations (interrupt vectors)
000008H (high-priority)
000018H (low-priority)

When there are multiple requests


The interrupt source must be identified by checking
the interrupt flags

Determine Interrupts in Timer programming


Interrupt

Flag Bit

Register

Enable Bit Register

Timer0

TMR0IF

INTCON

TMR0IE

INTCON

Timer1

TMR1IF

PIR1

TMR1IE

PIE1

Timer2

TMR2IF

PIR1

TMR3IE

PIE1

Timer3

TMR3IF

PIR3

TMR3IE

PIE2

Timer Interrupt Flag Bits and Associated Registers

INTCON Register with Timer0 Interrupt Enable and Interrupt Flag

ORG
GOTO

0000H
MAIN

ORG
MAIN

ORG
0008H
BTFSS INTCON,TMR0IF
RETFIE
GOTO T0_ISR
Timer0 Interrupt

OVER

00100H
T0_ISR
BCF TRISB,5
ORG 200H
CLRF TRISD
MOVLW 0xFF
SETF TRISC
MOVWF TMR0H
MOVLW 0x08
MOVLW 0xF2
MOVWF T0CON
MOVWF TMR0L
MOVLW 0xFF
BTG
PORTB,5
MOVWF TMR0H
BCF
MOVLW 0xF2
INTCON,TMR0IF
MOVWF TMR0L
RETFIE
BCF INTCON,TMR0IF
END
BSF T0CON,TMR0ON
BSF INTCON,TMR0IE
BSF INTCON,GIE
MOVFF PORTC,PORTD
BRA OVER

External Hardware Interrupt programming


INTCON Register
INTCON2 Register

INTCON3 Register

ORG 0000H
GOTO MAIN
ORG 0008H
BTFSS INTCON,INT0IF
RETFIE
GOTO INT0_ISR
ORG 00100H
MAIN

OVER

BCF TRISB,7
BSF TRISB,INT0
CLRF TRISD
SETF TRISC
BSF INTCON,INT0IE
BSF INTCON,GIE
MOVFF PORTC,PORTD
BRA OVER
INT0_ISR
ORG 200H
BTG PORTB,7
BCF INTCON,INT0IF
RETFIE
END

Interrupt in Serial communication programming


Interrupt

Flag Bit

Register

Enable Bit Register

TXIF
(Transmit)

TXIF

PIR1

TXIE

PIE1

RCIF
(Receive)

RCIF

PIR1

RCIE

PIE1

Serial Port Interrupt Flag Bits and Associated Registers

PIE1 Register Bits Holding TXIE and RCIE

Serial Interrupt Enable Flags

8 bit switch is connected to port.D. the PIC18 reads data from PORTD and
writes it to TXREG.
ORG
00100H
MAIN SETF TRISD
ORG
0000H
MOVLW 0x20
GOTO MAIN
MOVWF TXSTA

ORG
0008H
BTFSC PIR1,TXIF
BRA TX_ISR
RETFIE
ORG 0040H

MOVLW D'15'
MOVWF SPBRG

Serial Port Interrupt

TX_ISR
MOVWFF
PORTD,TXREG
RETFIE

BCF TRISC, TX
BSF RCSTA, SPEN
BSF PIE1,TXIE
BSF INTCON,PEIE
BSF INTCON,GIE

OVER

BRA OVER
END
Enable peripheral Interrupt

LCD interfacing & Keypad


interfacing

LCD Interfacing
Driver HD44780
8-bit data bus (RD7-RD0)
Three control signals
RS Register Select
(RA3)
R/W Read/Write
(RA2)
E Enable (RA1)
Three power connections
Power, ground, and
variable resistor to
control brightness

Interfacing LCD
Can be interfaced either in 8-bit mode or 4-bit mode
In 8-bit mode, all eight data lines are connected
In 4-bit mode, only four data lines are connected
Two transfers per character (or instruction) are needed

Driver has two 8-bit internal registers


Instruction Register (IR) to write instructions to set up
LCD
Data Register (DR) to write data (ASCII characters)

LCD Operation
When the MPU writes an instruction to IR or data to
DR, the controller:
Sets DB7 high indicating that the controller is busy
Sets DB7 low after the completion of the operation

The MPU should always check whether DB7 is low


before sending an instruction or a data byte

Writing to or Reading from LCD (Table 9-4)


The MPU:

Asserts RS low to select IR


Asserts RS high to select DR
Reads from LCD by asserting the R/W signal high
Writes into LCD by asserting the R/W signal low
Asserts the E signal high and then low (toggles) to latch a
data byte or an instruction

Timing diagram: writing to LCD

Software
To write into the LCD
Send the initial instructions to set up the LCD
4-bit or 8-bit mode

Continue to check DB7 until it goes low


Write instructions to IR to set up LCD
parameters
Number of display lines and cursor status

Write data to display a message

Sending commands and data to LCD with time delay

Sending commands and data to LCD busy flag

Matrix Keypad Interfacing

Software
To recognize and encode the key pressed,
the program should:
Ground all the columns by sending zeros.
Check each key in a row for logic zero.
Ground one column at a time and check all the
rows in that column.
Once a key is identified, it is encoded based on its
position in the column.

ADC and sensor interfacing


Introduction
Analog to digital converters widely used for data
acquisition
Digital computers use binary values (discrete) but
physical world everything is analog (continuous).
Temperature, pressure, humidity and velocity are all in
analog.
A physical quantity is converted to electrical signals
using transducer or called as sensor
ADC is use to translate the analog signals to digital
numbers so that the microcontroller can read and
process them

ADC (analog to digital converter)


Most signals we want to process are analog
i.e.: they are continuous and can take an
inifinity of values
x(t)

Digital systems require discrete digital data


ADC converts an analog information into a
digital information

Analog

Digital

Digital System

Resolution & Conversion time


Resolution
ADC has n-bit resolution (n = 8,10,12,16 or even 24 bits)
Higher ADC resolution, a smaller step size (step size smallest step
change can be discerned by ADC).
Step size can be change with the help of Vref.

Conversion time
Define as the time it takes the ADC to convert the analog input to
digital (binary) number.
Dictated by:
Clock source connected to the ADC
Technology used in the fabrication of the ADC chips (CMOS or
TTL)

Digital data output


Dout
digital data output in decimal
Vin
analog input voltage
Step size smallest change, Vref/256 for
8 bit ADC

ADC program using assembly language

ADC program using C language

ADC and temperature sensor interfacing

Relay interface and Motor Control


Relay
an electrically operated switch.
Many relays use an electromagnet to operate a switching
mechanism mechanically, but other operating principles are also
used.
Relays are used where it is necessary to control a circuit by a lowpower signal (with complete electrical isolation between control and
controlled circuits), or where several circuits must be controlled by
one signal.
Two types of relay:
1. Electromechanical relay
2. Solid state relay

The following designations are commonly encountered:


SPST Single Pole Single Throw.
SPDT Single Pole Double Throw.
DPST Double Pole Single Throw.
DPDT Double Pole Double Throw.

Electromchanical sensor
A simple electromagnetic relay consists of a coil of wire wrapped
around a soft iron core, an iron yoke which provides a low
reluctance path for magnetic flux, a movable iron armature, and one
or more sets of contacts .
Other relays may have more or fewer sets of contacts depending on
their function.

Solid state relay


A solid state relay (SSR) is a solid state electronic component that
provides a similar function to an electromechanical relay but does
not have any moving components, increasing long-term reliability.
Every solid-state device has a small voltage drop across it. This
voltage drop limits the amount of current a given SSR can handle.
Solid-state relays rated to handle as much as 1,200 Amperes have
become commercially available.
Compared to electromagnetic relays, they may be falsely triggered
by transients.

Driving a relay

circuit to drive relay from I/O port using transistor and ULN2803

program code to drive relay

Optoisolator
also called an optocoupler, photocoupler, or optical isolator
"an electronic device designed to transfer electrical signals by
utilizing light waves to provide coupling with electrical isolation
between its input and output".
The main purpose of an opto-isolator is "to prevent high voltages or
rapidly changing voltages on one side of the circuit from damaging
components or distorting transmissions on the other side.
Commercially available opto-isolators withstand input-to-output
voltages up to 10 kV and voltage transients with speeds up to
10 kV/s.

Stepper Motor
A stepper motor (or step motor) is a brushless DC electric motor
that divides a full rotation into a number of equal steps.
The motor's position can then be commanded to move and hold at
one of these steps without any feedback sensor (an open-loop
controller), as long as the motor is carefully sized to the application.
There are many kind of stepper motors. Unipolar type, Bipolar type,
Single-phase type, Multi-phase type...
* 2-phase unipolar PM type stepper motor

Driving a stepper motor

DC Motor
Motors come in many sizes and types, but their basic function is the
same. Motors of all types serve to convert electrical energy into
mechanical energy.
They can be found in VCR's, elevators, CD players, toys, robots,
watches, automobiles, subway trains, fans, space ships, air
conditioners, refrigerators, and many other places.
D.C. motors are motors that run on Direct Current from a battery or
D.C. power supply.

DC motor interface to control direction with H-Bridge motor


configuration

program code to control DC motor direction with H-Bridge


configuration

PWM ( Pulse Width Modulation )


Pulse width modulation (PWM) is a powerful technique for
controlling analog circuits with a microprocessor's digital outputs.
PWM is employed in a wide variety of applications, ranging from
measurement and communications to power control and conversion
PWM is a way of digitally encoding analog signal levels. Through
the use of high-resolution counters, the duty cycle of a square wave
is modulated to encode a specific analog signal level.
The PWM signal is still digital because, at any given instant of time,
the full DC supply is either fully on or fully off.
The voltage or current source is supplied to the analog load by
means of a repeating series of on and off pulses.
The on-time is the time during which the DC supply is applied to the
load, and the off-time is the period during which that supply is
switched off. Given a sufficient bandwidth, any analog value can be
encoded with PWM.

PWM comparison

PWM motor control with CCP

Program code

You might also like