You are on page 1of 192

MICROPROCESSOR APPLICATIONS

EE313

Dr. Utkal Mehta


E: mehta_u@usp.ac.fj

Electrical & Electronics Engineering


School of Engineering & Physics
Faculty of Science & Technology
The University of the South Pacific (USP)

Sem-1, 2015

COURSE DESCRIPTION
Provides knowledge
microprocessors and
operation of digital
techniques to use
applications

of the internal organization of


computer buses, principles of
computers and the interfacing
microprocessors in engineering

Involves elements of
programming for P

assembly

and

language

Rapidity technology of innovations, no specific


microprocessor will be selected at this stage, but an
appropriate device PIC18F6722 will be chosen at the
time of teaching the course.

Main topics week-wise..


Week 1: Introduction to Microprocessor technology, family of P/ C, differences: P Vs C
Week 2: Programming techniques basic C to programme a processor, Complier, debugger, linker, assembler, examples
Week 3: PIC 16Fxx and 18Fxx General purpose microcontroller features, Special function registers, Timers
Week 4: Modules types, Input-Outputs types, methods to program
Week 5: Use of timer control features, clock time application, examples software - hardware
Week 6: Memory types and decoding techniques to interface with processors
Week 7: Writing header, configuring I/O pins, using delay function and switch operator
Week 8: Timer as a counter, declaring new variables, enumerated constants, using relay, sensors interface
Week 9: Example study Using timers TMR0, TMR1 and TMR2. Using interrupts, declaring new function.
Week 10: Example study Using watch-dog timer, Module CCP1 as PWM signal generator, Using A/D converter
Week 11: Example study Two-digit LED counter, multiplexing, Using LCD display
Week 12: RS232 serial communication interfacing- types examples
Week 13: Temperature measurement, speed and position control application examples, calibration
Week 14: Introduction of Advanced processor (PIC32 and ARM); Advantages and Applications

Recommended textbooks:
Embedded C Programming and the Microchip PIC by Richard Barnett, L
OCull and S Cox, Thomson Delmarr learning
Programming and Customizing PIC micro MCU microcontrollers. McGraw
Hill, U.S.A. (Second Edition)
Interfacing PIC Microcontrollers, Embedded Design by Interactive Simulation 2nd edition - By Martin Bates
PICmicroTM Mid-Range MCU Family Reference Manual, Microchip
Programming and Customizing the PIC Microcontroller, Myke Predko - Third
Edition

ASSESSMENT PORTFOLIO and DATES


Activity
Test 1 (50 mins)
Test 2 (50 mins)
Laboratory task- experiments
(3 hours/week)

Hardware project with extensive


programming applications and a short
report- demonstration
Final Exam (3 hours)

Week
7
14
Weekly

%
10%
10%
10%

14

20%

End of Semester

50%

Time table
Timetable

Session

Lecture

Lab

Tutorial

Day

Tue

Wed

Thu

Wed

Thu

Mon

Wed

Mon

Fri

Time

1-2pm

4-5pm

10-11am

1-4pm

3-6pm

2-5pm

11-am

6-7pm

1-2pm

093-207

003-001

014-112

Room

014-112 014-112

014-028

ICT Engg Lab

Introduction
Base-10 number system i.e. Decimal number
system
Because we use ten different digits (0, 1, 2, ... 8, 9)

Base-2 number system i.e .Binary number syst

Continue

One digit (2) is used to write the number 2 in


decimal system, whereas two digits (1 and 0) are
used to write it in binary system !
Do you agree that there are 10 groups of people?
Welcome to the world of binary arithmetic!
Do you have any idea where it is used?
A binary logic where 0 indicates that there is no
voltage and 1 indicates that there is a voltage
In the electronics we are talking about applies mathematics in which
all the numbers are represented by two digits only and where it is only
important to know whether there is a voltage or not.

Of course, we are talking about digital electronics.

Hexadecimal number system:


Four binary digits to represent one hexadecimal digit
Use, 16 different symbols
Consists of the ten digits we are used to (0, 1, 2, 3,... 9) and
six letters of alphabet A, B, C, D, E and F

Largest number that can be represented by 4 binary digits is the number


1111 ( = 15 in decimal) whereas in hexadecimal system, = one digit F
Largest 1-digit number in hexadecimal system = F

BCD Code: a binary code for decimal numbers only


(Binary-Coded Decimal)
Use to enable electronic circuits to communicate either with
peripherals, consist of 4-digit binary numbers which represent the first
ten digits (0, 1, 2, 3 ... 8, 9)

Number system conversion


Binary: most commonly used, Decimal: most understandable, while
Hexadecimal: somewhere between them

Very important to learn how to convert numbers from one number system to
another, i.e. how to turn a sequence of zeros and ones into understandable
values
BINARY TO DECIMAL NUMBER CONVERSION: Eg. (1 1 0)2 = ( )10

HEXADECIMAL TO DECIMAL NUMBER CONVERSION


Eg. (A27E)16 = ( )10

HEXADECIMAL TO BINARY NUMBER CONVERSION


E4 h or 0xE4

Bit (0 or 1)
Byte ( group of 8 bits )
Nibble ( group of 4 bits)
Word ( group of 16 bits)
MSB: The greatest value has the leftmost bit called the most
significant bit (MSB)

LSB: The rightmost bit has the least value and is therefore
called the least significant bit (LSB)

Review Logic Gates:


AND, OR , NOT, Ex-OR

A Basic Microprocessor Systems

Definition of the Microprocessor


The microprocessor is a programmable device
that takes in numbers, performs on them
arithmetic or logical operations according to
the program stored in memory and then
produces other numbers as a result.

Organization:
Arithmetic Logic Unit (ALU)
Control unit,
Registers
Accumulator:
It is 8 bit general purpose register (eg. 8085 processor).
It is connected to ALU.
Most of the operations are done in Acc.

Temporary register:
It is not available for user
All the arithmetic and logical operations are done in the temporary register
but user cant access it.

Flag:
Use to know status of various operations done.
Flag Register along with Accumulator is called PSW or Program Status
Word.

Special purpose Registers (8-bit processor)


There are two special purpose registers commonly;
SP: Stack Pointer: Hold address (16 bit register) of the stack. Stack is
a Temporary storage memory. (why?) Since there are few general
purpose registers, there is a need to reuse them.
Whenever stack is to be used previous values are PUSHED on
stack and then after the program is over these values are POPED
back. (Manually increment-decrement)
PC: Program Counter: It is 16 bit register used to point the location
from which the next instruction is to be fetched.
When a single byte instruction is executed PC is automatically
incremented by 1.
Upon reset PC contents are set to 0000H and next instruction
is fetched onwards.

INSTRUCTION REGISTER, DECODER & CONTROL


Instruction register: When an instruction is fetched , it is executed
in instruction register. This register takes the Opcode value only.
Instruction decoder: It decodes the instruction from instruction
register and then to control block.
Timing and control: This is the control section of P. It accepts
clock input.

Control Unit: Generate predefined signal timed by pulses


derived from a clock
Two groups of Signals: 1. Internal control signals, 2. External control
signals
1: Activation of ALU and opening/closing the data paths between
registers.
2. For memory and I/O purpose, Activation of data transfer, response
to interrupts and I/O

Types of Buses in Microprocessor


1. Address Bus: A group of wires or lines that are used to transfer the addresses of
Memory or I/O devices. It is unidirectional.
Say for example, Intel 8085 P, Address bus = 16 bits, means that it can
transfer maximum 16 bit address which means it can address 65,536 different
memory locations (64KBytes).
Also, this bus is multiplexed with 8 bit data bus (AD0-AD7) --(why?)
2. Data Bus: Used to transfer data within Microprocessor and Memory/Input or
Output devices.
It is bidirectional, as P requires to send or receive data
Give name of preprocessor size (like 8-bit processor..if data bus size = 8)
3. Control Bus:
Control signals are Read, Write and Opcode fetch etc. Various operations
are performed by microprocessor with the help of control bus.
This is a dedicated bus, because all timing signals are generated according
to control signal

Memory Interfacing
Example: Interface 2Kbytes of Memory to P (8-bit) with
starting address 8000H
Initially we realize that 2K memory requires 11 address lines
(2^11=2048). So we use A0-A10 .
Write down A15 A0
A15

14

13

12

11

10 A9 A8 A7 A6 A5 A4 A3 A2 A1

1
---

0
---

0
---

0
---

0 0 0 0
--- --- ---

0 0 0
--- --- ---

0
---

A0

Memory Interfacing
The diagram of 2KB interfacing is shown below:
A15- A11

3:8
DECODER

P IC
CS

A15-A8
ALE

A10- A0
AD7-AD0

WR RD

IO/M

Latch

A7- A0

2K Byte
Memory
Chip

D7- D0
RD

WR

Address lines A0-A10 are used to interface memory


while A11,A12,A13,A14,A15 are given to 3:8 Decoder
to provide an output signal used to select the
memory chip CSor Chip select input.

MEMR and MEMWare given to RDand


WRpins of Memory chip (Need to use digital gate
logic)
Data lines D0-D7 are given to D0-D7 pins of the
memory chip..(To write and read data into and
from memory chip).
In this way memory interfacing can be achieved.

MACHINE, ASSEMBLY AND HIGH-LEVEL LANGUAGE


Machine language:
Computer's natural language, - directly understood by the
system
Machine dependent
A program written in 1s and 0s is called a machine language. A
binary code is used in a machine language for a specific
operation.
Assembly Language:
Programmers Use English-like (mnemonics) words as
commands, Easily interpreted by programmers
Alphanumeric symbols- called mnemonics
Example: ADD, SUB, MUL, DIV, RLC and RAL - Symbols
called mnemonics
Disadvantages:
Time consuming for an assembler to write and then test the program
Assembly language programs are not portable
Necessary to remember the registers of CPU and mnemonic instructions,
very tedious to program in machine language.

High-Level Language:
Because it is not fun to program in Assembly, we have high level
programming languages like C, CPP, Forton etc..
Compilers are used to translate high-level language program to
machine language.
Advantages:
Fast program development.
Testing and debugging a program is easier than in the assembly
language.
Portability of a program from one machine to other.

Program Translation

A translator program converts our instructions to


machine instructions for the target computer
Interpreter Translation line by line
Compiler Translation happens all at once

Basic Types of Memory


READ ONLY MEMORY (ROM)
Use to permanently save the program being executed
Size, if 16-bit addressing lines , which means able to address up to 64 Kb of
memory, i.e. 65535 locations.
Masked ROM (MROM)
A kind of ROM, programmed by the manufacturer
Use for a large-scale production, Reduce price
UV Erasable Programmable ROM (UV EPROM) OR EPROM
Enables data to be erased under strong ultraviolet light
Can reuse the memory, for developing new program

Flash Memory
Similar to UV EPROM.
Content of this memory can be written and cleared practically an unlimited
number of times
Flash ROM are ideal for learning, experimentation and small-scale production

RANDOM ACCESS MEMORY (RAM)


Once the power supply is off the contents of RAM is cleared
Used for temporary storing data and intermediate results created and
used during the operation of C

ELECTRICALLY ERASABLE PROGRAMMABLE ROM


(EEPROM)
Electrical signal is used to erase the content
Remains permanently saved even after the loss of power (similar to
ROM)
Use to store program, values, created during operation, which must
be permanently saved

Introduction
Why we use C?
C is a portable language intended to have minimal modification
when transferring programs from one computer to another.
Main program flow will basically remain unchanged, while the
various setup and port/peripheral control will be micro specific.
An example of this is the port direction registers on a
PICmicroMCU are set 1=Input 0=Output, whereas the H8 is
0=Input and 1=Output
Use of C in C applications: as manufacturers providing larger
program and RAM memory areas in addition to faster operating
speeds
An example quoted to me as a non believer was: to create a stop
clock function would take 2/3 days in C or 2 weeks in assembler.

C fundamentals
Structure of C Programs
All C program contain preprocessor directives, declarations, definitions, expressions,
statements and functions
Preprocessor directive
Two most common preprocessor directives:
#define directive, which substitutes text for the specified identifier, and
#include directive, which includes the text of an external file into a program
Declaration
Variables, functions, and types used in the program
Global variables are declared outside functions
A local variable is declared inside a function
Definition
A definition establishes the contents of a variable or function
Allocates the storage needed for variables and functions
Function
A function is a collection of declarations, definitions, expressions, and statements that
performs a specific task

#include <stdio.h>
/* My first C program */
main()
{
printf(Hello world!);
}
Statement #include <stdio.h> tells the compiler to include the source code from the file
stdio.h into the program.
STandarD Input and Output header file, contains most of the input and output
functions
FunctionName()
{
code
}

if (ThisIsTrue)
DoThisFunction();

A program to ON/OFF LED through Port A Pin#0


#include <18F6722.h>
#device ICD=TRUE
#fuses HS,NOLVP,NOWDT
#use delay (clock=20000000)
#define RED_LED PIN_B5
void main () { //continuous loop
while (TRUE) {
output_low (RED_LED); //on led for 1 sec
delay_ms (1000);
output_high (RED_LED); // off led for 4 sec
delay_ms (4000); }
}//end of prog

The definitions PIN_B5 is found in the header file <18F6722.h>


Similarly, output_low and output_high are function to make pin low or high accordingly
for given pin description.

PIC18F6722 board

PIC18F8722 board

Define variables, Array and constant variable before main program


//
character
0 1 2 3 4 5 6 7 8 9
// array of size 10 type byte
byte const Digit_Map[10] = {0xFC,0x60,0xDA,0xF2,0x66,0xB6,0xBE,0xE0,0xFE,0xE6};
#define BLANK 0 //variable with constant value
#define DASH 11
byte lcd_pos; // variable type byte
void lcd_putc(char c)
{
// Insert code to output one
// character to the LCD here
}
printf(lcd_putc, value is %u, value);

Format Specifiers printf()


%c single character
%d signed decimal interger
%f floating point
%u unsigned decimal integer
%x unsigned hexadecimal integer
(lower case)
%X unsigned hexadecimal integer
(upper case)

Microprocessors vs. Microcontrollers


Microprocessors are single-chip CPU used in microcomputers
Microcontrollers and microprocessors are different in three main
aspects: hardware architecture, applications and instruction set
features
Hardware architecture: A microprocessor is a single chip CPU
while microcontroller in a single IC contains a CPU and much of
remaining circuitry of a complete computer (e.g., RAM, ROM,
serial interface, parallel interface, timer, interrupt handling circuit)

Applications: Microprocessors are commonly used as CPU in


computers while microcontrollers are found in small, minimum
component designs performing control oriented activates

Microprocessors vs. Microcontrollers


Instruction set:
Microprocessor instruction sets are processing intensive.
Their instructions operate on nibbles, bytes, words, or even
double words.
Addressing modes provide access to large arrays of data
using pointers and offsets (use in image processing, data
processing, large files.)
Microcontroller instruction sets cater to control of input and
outputs.
They have instructions to set and clear individual bits and
perform bit operations
Have instructions for input/output operations, event timing,
enabling and setting priority levels for interrupts caused by
external stimuli.

Microprocessors vs. Microcontrollers


Microcontroller = Microprocessor + ROM + RAM + Parallel I/O +
Serial I/O + Counters + Clock Circuit

The prime use of Microcontroller is to control the operation of a machine


using a fixed program that is stored in ROM and that does not change over
the lifetime of the system.

Processing power of a microcontroller is much less than


a Microprocessor

PIC FAMILIES
PIC stands for Peripheral Interface Controller given by Microchip Technology

Single-chip microcontrollers

http://www.microchip.com/stellent/images/mchpsiteimages/en537986.jpg

Baseline
Architecture

Mid-Range
Architecture

Enhanced Mid-Range
Architecture

PIC18 Architecture

Pin Count

6-40

8-64

8-64

Interrupts

No

Single interrupt
capability

Single interrupt
Multiple interrupt capability
capability with
with hardware context save
hardware context save

Performance

5 MIPS

5 MIPS

8 MIPS

Up to 16 MIPS

Instructions

33, 12-bit

35, 14-bit

49, 14-bit

83, 16-bit

Program
Memory

Up to 3 KB

Up to 14 KB

Up to 28 KB

Up to 128 KB

Data Memory

Up to 138 Bytes

Up to 368 Bytes Up to 1.5 KB

Up to 4 KB

Features

Comparator
8-bit ADC
Data Memory
Internal Oscillator

In addition to
Baseline:
SPI/IC
UART
PWMs
LCD
10-bit ADC
Op Amp

In addition to
Mid-Range:
Multiple
Communication
Peripherals
Linear Programming
Space
PWMs with
Independent Time
Base

In addition to
Enhanced Mid-Range:
8x8 Hardware Multiplier
CAN
CTMU
USB
Ethernet
12-bit ADC

Families

PIC10, PIC12, PIC16

PIC12, PIC16

PIC12FXXX, PIC16F1XX

PIC18

8-bit architecture

18-100

Description
PIC Peripheral Interface Controller
Made by Microchip Technology
Most popular by industry developers and hobbyists
o Low cost (cents to dollars)
o Availability
o Extensive application notes
o USB programming

8-bit Core Architecture


Harvard (separate code
and data space)
RISC
One accumulator
W Register

Small addressable data


space (256 bytes)
Banking

RAM
PC, special purpose
registers

http://www.microchip.com/_images/BaselineArch_large.jpg

Advantages & Limitations to 8-bit


Architecture

Small instructions to learn


Built in oscillator with selectable speeds
Development made easy
Inexpensive
Device variants
Wide range of interfaces (I2C, SPI, etc.)

One accumulator
Bank switching
NO multi-tasking

16-bit and 32-bit Architecture

More working registers


No bank switching
Assignable interrupt vector table
More flash memory
Cache (32-bit architecture)

VON-NEUMANN ---Vs ---HARVARD ARCHITECTURE


VON-NEUMANN ARCHITECTURE

Only one memory block and one 8-bit data bus


As all data are exchanged through these 8 lines, the bus is
overloaded and communication is very slow and inefficient
CPU can either read an instruction or read/write data from/to the
memory
Both cannot occur at the same time

HARVARD ARCHITECTURE

Have two different data buses


One is 8 bits wide and connects CPU to RAM. The other
consists of 12, 14 or 16 lines and connects CPU to ROM
CPU can read an instruction and access data memory at the
same time [Separate Program and Data memory]
High speed

RISC ---Vs--- CISC Instruction set


RISC (REDUCED INSTRUCTION SET COMPUTER)
Microcontroller recognizes and executes only basic operations
(addition, subtraction, copying etc.)
This language is easy to learn and also the microcontroller is very
fast
User can only see the final results
More complicated operations are performed by combining
simple/basic operations
CISC (COMPLEX INSTRUCTION SET COMPUTER)
Its opposite to RISC! Microcontrollers designed to recognize more
than 200 different instructions can do a lot of things at high speed
However, one needs to understand how to take all that such a rich
language offers, which is not at all easy...

PIC18F MCU and Memory


MPU Block Diagram
16 bit

2 MB
221

8 bit

4 KB
212

Microprocessor Unit (1 of 3)
Includes Arithmetic Logic
Unit (ALU), Registers,
and Control Unit
Arithmetic Logic Unit
(ALU)
WREG working register
Status register that stores
flags
Instruction decoder when
the instruction is fetched it
goes into the ID

Microprocessor Unit (2 of 3)

Registers

Bank Select Register (BSR)


4-bit register used in direct addressing
the data memory

File Select Registers (FSRs)


16-bit registers used as memory
pointers in indirect addressing data
memory

Program Counter (PC)


21-bit register that holds the program
memory address while executing
programs

Microprocessor Unit (3 of 3)
Control unit
Provides timing and control signals to various Read and Write operations

PIC18F - Address Buses


Address bus
21-bit address bus for
program memory addressing
capacity: 2 MB of memory
12-bit address bus for data
memory addressing capacity:
4 KB of memory

Data Bus and Control Signals


Data bus
16-bit instruction/data bus
for program memory
8-bit data bus for data
memory

Control signals
Read and Write

PIC18F8722 MCU

Program Memory: 128 K


Address range: 000000 to 01FFFFH

Data Memory: 4 K
Address range: 000 to FFFH

Data EEPROM
1K
Not part of the data memory space
Addressed through special function registers

16 total 10bit ADC


Two 8-bit and Three 16-bit timers

Priority Levels for Interrupts


8 x 8 Single-Cycle Hardware Multiplier
Extended Watchdog Timer (WDT): - Programmable period from 4 ms to 131s
Single-Supply 5V In-Circuit Serial Programming (ICSP) via Two Pins
In-Circuit Debug (ICD) via Two Pins
Wide Operating Voltage Range: 2.0V to 5.5V
Programmable Brown-out Reset (BOR) with Software Enable Option

PIC18F8722
Internal
Block diagram

Features of PIC
Brown-out-reset means when the power supply goes below a specified
voltage (say 2V), it causes PIC to reset; hence malfunction is avoided.
Watch dog timer (user programmable) resets the processor if the
software/program ever malfunctions and deviates from its normal
operation.
Sleep Mode: Power consumption of the microcontroller is reduced to
the lowest level in Sleep mode since the main power consumer - the
oscillator - doesnt operate. Set the microcontroller in this mode- by
executing the SLEEP instruction

STACK and Its Operation In PIC18FXX


Stack operates as a 31-word by 21-bit RAM and a 5-bit Stack Pointer,
STKPTR
Stack space is not part of either program or data space
Stack Pointer is readable and writable and the address on the top of the stack
is readable and writable through the top-of- stack Special File Registers.
Data can also be pushed to, or popped from the stack, using these registers.
Stack Pointer (SP) is initialized to 00000 after all Resets.
There is no RAM associated with the location corresponding to a Stack
Pointer value of 00000; this is only a Reset value.
Status bits indicate if the stack is full or has overflowed or has underflowed
Use when a subroutine (CALL instruction) or when an interrupt occurs
Address of the first next instruction to execute is pushed onto the stack, i.e.
one of its registers
So that the microcontroller knows from where to continue regular program
execution upon a subroutine or an interrupt execution
This address is cleared after returning to the program because there is no need
to save it any longer, and one location of the stack becomes automatically
available for further use

CPU registers (registers commonly used by the CPU)


1. W, the working register, is used by many instructions as the source of an operand. This
is similar to accumulator in 8051. It may also serve as the destination for the result of
the instruction execution. It is an 8 - bit register.
2. STATUS Register: a 8-bit register that stores the status of the processor. This also
stores carry, zero and digit carry bits

IRP - Bit selects register bank. It is used for indirect addressing.


1 - Banks 0 and 1 are active (memory locations 00h-FFh)
0 - Banks 2 and 3 are active (memory locations 100h-1FFh)
RP1, RP0 - Bits select register bank. They are used for direct addressing
TO - Time-out bit.
1 - After power-on, which resets the watch-dog timer
0 - After watch-dog timer time-out has occurred
PD - Power-down bit
1 - After power-on, which resets the watchdog timer.
0 - After executing the SLEEP instruction which sets the C into low-consumption mode

Z - Zero bit
1 - The result of an arithmetic or logic operation is zero.
0 - The result of an arithmetic or logic operation is different from zero.
DC - Digit carry/borrow bit is changed during addition and subtraction if an
overflow or a borrow of the result occurs.
1 - A carry-out from the 4th low-order bit of the result has occurred (same as
auxiliary carry)
0 - No carry-out from the 4th low-order bit of the result has occurred
C - Carry/Borrow bit is changed during addition and subtraction if an overflow or a
borrow of the result occurs, i.e. if the result is greater than 255 or less than 0.
1 - A carry-out from the most significant bit (MSB) of the result has occurred.
0 - No carry-out from the most significant bit (MSB) of the result has occurred.
3. OPTION_REG Register

RBPU - Port B Pull up Enable bit.


1 - PortB pull-ups are disabled.
0 - PortB pull-ups are enabled.

3. OPTION_REG Register

INTEDG - Interrupt Edge Select bit.


1 - Interrupt on rising edge of RB0/INT pin.
0 - Interrupt on falling edge of RB0/INT pin.
T0CS - TMR0 Clock Source Select bit.
1 - Transition on TOCKI pin. (external)
0 - Internal instruction cycle clock (Fosc/4) (internal source)
T0SE - TMR0 Source Edge Select bit selects pulse edge (rising or falling) counted by
the timer TMR0 through the RA4/T0CKI pin
1 - Increment on high-to-low transition on TOCKI pin.
0 - Increment on low-to-high transition on TOCKI pin

PSA - Prescaler Assignment bit assigns prescaler (only one exists) to the timer or
watchdog timer.
1 - Prescaler is assigned to watchdog
0 - Prescaler is assigned to a free-run timer TMR0
PS2, PS1, PS0 Prescaler Rate Select bits..will be explained in Timer section

ANSEL and ANSELH register


Use to configure the input mode of an I/O pin to analog or
digital
To configure as Analog input: ANSEL or ANSELH = 1
To configure as Digital input/output: ANSEL or ANSELH = 0

For ADC operation, select the appropriate ports


pins for analog inputs, such a pin configuration
(AN0-AN13).
RA0 = AN0 (determined by the ANS0 bit of the ANSELregister)
RA1 = AN1 (determined by the ANS1 bit of the ANSELregister)
RA2 = AN2 (determined by the ANS2 bit of the ANSELregister)
RA3 = AN3 (determined by the ANS3 bit of the ANSELregister)

RA5 = AN4 (determined by the ANS4 bit of the ANSELregister)

INPUT/OUTPUT PORTS and TRIS register


For practical reasons, many I/O pins are multifunctional, Not only a general-purpose
I/Os(why??)
Configuration decided by TRIS register: TRISA, TRISB, TRISC etc. which determines
the performance of port bits, but not their contents. Pin can be used as Input or Output.

0 = output and 1 = input

PIC C -functions:
SET_TRIS_x()

PORTA and TRISA register

Port A is an 8-bit wide, bidirectional port (but, 6 bit in 16F877 PIC )


Bits of the TRISA and ANSEL registers control the Port A pins
All Port A pins act as digital inputs/outputs. Five of them can also be analog
inputs (denoted by AN)
Aim // The PORTA.2 pin is configured as a digital input.
// All other PORTA pins are digital outputs

ANSEL = ANSELH = 0; // All I/O pins are configured as digital


PORTA = 0; // All PORTA pins are cleared
TRISA = 0b00000100; // All PORTA pins except PORTA.2 are

configured as outputs
...

Port B
Built in pull-up resistors, which make them ideal for connection to push buttons
(keyboard), switches and opto-couplers
In order to connect these resistors to the microcontroller ports, the appropriate
bit of the WPUB register should be set

PIC C function:
PORT_B_PULLUPS()
To enable pins to cause an interrupt, appropriate bit of the
IOCB register should be set

Aim: /* The PORTB.1 pin is configured as a digital input. Any change of its logic state will cause
an interrupt. It also has a pull-up resistor. All other PORTB pins are digital outputs.*/

ANSEL = ANSELH = 0;
// All I/O pins are configured as digital
PORTB = 0;
// All PORTB pins are cleared
TRISB = 0b00000010;
// All PORTB pins except PORTB.1 are configured as outputs
RBPU = 0;
// Pull-up resistors are enabled
WPUB1 = 1;
// Pull-up resistor is connected to the PORTB.1 pin
IOCB1 = 1;
// The PORTB.1 pin may cause an interrupt on logic state change
RBIE = GIE = 1;
// Interrupt is enabled
...

INTERRUPT SYSTEM REGISTERS


1. Mask-able interrupts
2. Unmask-able interrupts

INTCON Register contains various enable and flag bits for TMR0 register overflow,
PORTB change and external INT pin interrupts.

GIE - Global Interrupt Enable bit


1 - Enables all unmasked interrupts.
0 - Disables all interrupts.
PEIE - Peripheral Interrupt Enable bit acts similar to the GIE it, but controls interrupts
enabled by peripherals
1 - Enables and 0 - Disables

Continue..
T0IE - TMR0 Overflow Interrupt Enable bit timer interrupt
1 - Enables the TMR0 interrupt.
0 - Disables the TMR0 interrupt.
INTE - RB0/INT External Interrupt Enable bit external interrupt
1 - Enables the INT external interrupt.
0 - Disables the INT external interrupt.
RBIE - RB Port Change Interrupt Enable bit. - when use PORTB pins as interrupt
1 - Enables the port B change interrupt
0 - Disables the port B change interrupt
T0IF - TMR0 Overflow Interrupt Flag bit registers the timer TMR0 register overflow, when
counting starts at zero.
1 - TMR0 register has overflowed (bit must be cleared from within the software)
0 - TMR0 register has not overflowed
INTF - RB0/INT External Interrupt Flag bit registers the change of the RB0/INT pin logic
state.
1 - The INT external interrupt has occurred (must be cleared from within the software).
0 - The INT external interrupt has not occurred.
RBIF - RB Port Change Interrupt Flag bit registers any change of logic state of some PORTB
input pins.
1 - At least one of the PORTB general purpose I/O pins has changed state. Upon reading
PORTB, the RBIF bit must be cleared from within the software.
0 - None of the PORTB general purpose I/O pins has changed the state.

Concluding notes on PIC16F887 Interrupts

GIE bit enables all unmasked interrupts and disables all


interrupts simultaneously
PEIE bit enables all unmasked peripheral interrupts and
disables all peripheral interrupts

GIE and PEIE have no concern with Timer TMR0 and


PORTB interrupt sources
To enable an interrupt caused by changing logic state on
PORTB, it is necessary to enable it for each bit
separately. In this case, bits of the IOCB register act as
control IE bits

Timers in PIC
PIC18F8722: 5 timer modules - denoted by the symbols TIMER-0(8b or 16b),
TIMER-1(16b), TIMER-2(8b), TIMER-3(16b), TIMER-4(8b)
Modules help to perform various timing and counting functions inside the chip
For examples,
8 bit timers - These can count between between 0-255
16 bit timers - These can count between 0-65536
32 bit timers - These can count between 0-4294967296
PIC ranges from 1 MHz to 40Mhz, this can be sometimes too fast!
Prescaler: Help to divide the CPU clock to obtain a smaller frequency: Gives
large time delay

TIMER 0: TMR0

Timers to generate a time delay


Counters to count events happening outside the C
Easy to use and counting external pulses (events) with almost no limitations
Software selectable operation as a timer or counter in both 8-bit or 16-bit modes
Dedicated 8-bit programmable prescaler
Select clock source (Internal or External)
Interrupt-on-overflow

T0CON: Timer 0 control register

Timer 0 Operation

TIMER0 BLOCK DIAGRAM (8-BIT MODE)

TIMER0 BLOCK DIAGRAM (16-BIT MODE)

TMR0IF flag bit


Part of INTCON

Overflow
An overflow occurs when a timer register has already counted the maximum value it can
count. At overflow the counter value become 0 again. For example when an 8 bit timer
has the value 255 and receive another clock that will set it to 0 and generate an
overflow. An overflow can trigger an interrupt and the ISR can handle it.
TIMER0 is configured as follows.
8 Bit Mode
Clock Source from Prescaler
Prescaler = FCPU/256 (Note: FCPU= Fosc/4)
Over flow INT enabled

1.
2.
3.
4.

For 20 MHz clock frequency, we get, 20MHz/4 =5MHz


Time Period = 1 / 5Mhz = 0.2S (micro sec)
If Prescaler is set to divide frequency by 256, Prescaler Period = 0.2 x 256 = 51.2uS
Overflow Period = 51.2 x 256 = 13107.2 uS (Each over flow takes 256 counts)
= 0.0131072 sec

Now, if we want to get delay of 1 sec, we need 1/0.0131072 Overflows to count =


76.2939 Overflows

Delay = (256 - TMR0_preload) * Prescaler / (0.25*Frequency)

Example: Generate 1 sec delay and on LED for 1 sec using Timer_0. Take 20 MHz clock
frequency
When an over flow occurs the program jumps to ISR, where we increment the counter. And
when counter becomes 76 we toggle RB4 pin. This pin is connected to LED. Therefore we
have a LED which is ON for 1 sec and Off for 1sec.
unsigned char counter=0;//Overflow counter
void main()
{
//Setup Timer0
T0PS0=1; //Prescaler is divide by 256
T0PS1=1;
T0PS2=1;

//Main Interrupt Service Routine (ISR)


void interrupt()
{
//Check if it is TMR0 Overflow ISR
if(TMR0IE && TMR0IF)
{
//TMR0 Overflow ISR
counter++; //Increment Over Flow Counter
PSA=0;
//Timer Clock Source is from Prescaler
if(counter==76)
T0CS=0; //Prescaler gets clock from FCPU (5MHz)
{
T08BIT=1; //8 BIT MODE
//Toggle RB4 (LED)
if(RB4==0)
TMR0IE=1; //Enable TIMER0 Interrupt
RB4=1;
PEIE=1; //Enable Peripheral Interrupt
else
GIE=1;
//Enable INTs globally
RB4=0;
counter=0; //Reset Counter
//Set RB4 as output because we have LED on it
}
TRISB&=0B11101111;
while(1); //Sit Idle Timer will do every thing!

//Clear Flag
TMR0IF=0;
} }

Example: Using PIC C, write a program to generate one second


trigger at the output pin. Say, Port B Pin_4 will be high to low at every
one second. Given maximum crystal frequency = 40 MHz. Show your
calculations.
Ans:
For 4 MHz clock frequency, we get, 40MHz/4 =10MHz
Time Period = 0.1S (micro sec)
if Prescaler is set to divide frequency by 256
Prescaler Period = 0.1 x 256 = 25.6 uS
Overflow Period = 256 x 25.6 = 6563.6 uS (Each over flow takes
256 counts)
Each overflow time = 0.0065536 sec
To get delay for 1 sec, we need 1/0.065536 Overflows to count = 152
Overflows

#include <18F8722.h> //select proper pic header file


#device ICD=TRUE
#fuses HS,NOLVP,NOWDT
#use delay (clock=40000000)
int i=0;
int lowt=0;//toggle led status

Program for Timer 0 application- 8 bit mode


#INT_TIMER0
void interrupt_tim0() // program automatically jump on ISR when overflow occurred
{
i++;
if(i==152) // check for about 1 sec
{if(lowt==1)lowt=0;
else lowt=1;
i=0;
}
if(lowt==0)output_high(PIN_A5); // LED OFF
else output_low(PIN_A5); // LED ON

}
main() {
setup_timer_0(RTCC_INTERNAL|RTCC_DIV_256|RTCC_8_BIT);//Timer 0 setup
enable_interrupts(INT_RTCC);//enable timer0 and global interrupts
enable_interrupts(GLOBAL);
output_low(PIN_A5); // LED ON
while(1); // Wait for the interrupt

}// end of program

Long time delay using Timer0- 16bit mode

Characteristics and operations of 16-bit mode


1. 16-bit timer, 0000 to FFFFH.
2. After loading TMR0H and TMR0L, the timer must be
started.
3. Count up, till it reaches FFFFH, then it rolls over to 0000
and activate TMR0IF bit.
4. Then TMR0H and TMR0L must be reloaded with the
original value and deactivate TMR0IF bit.

Timer 0 : 16-bits module (0000h to FFFFh or 0 to 65535)


Delay = (65535 TMR1_preload) * Prescaler / (0.25*Frequency)
Example: Write

a program to generate a square wave with a


period of 20 Sec on pin PORTB.5 (XALT=20 Mhz)
For 20 MHz clock frequency, we get, 20MHz/4 =5MHz
Time Period = 0.2S (micro sec)
if Prescaler is set to divide frequency by 256 (default PS: 11 = 1/256)
Prescaler Period = 256 x 0.2 = 51.2 S
Overflow Period = 51.2 x 65536 = 3.35 Sec, so Each overflow time = 3.35 Sec
For period square wave of 20 sec, we generate 10 sec delay trigger. For that we
need 10/3.35 Overflows to count = 3 Overflows
20 sec

Solution:
#use delay (clock=20000000)
#INT_TIMER0 //Timer 0 interrupt routine 16 bit mode example
timer0_16bit()
{
i++;
if(i==3) // check for about 10 sec
{if(lowt==1)lowt=0;
else lowt=1;
i=0;
if(lowt==0)output_high(PIN_B5); // LED OFF
else output_low(PIN_B5); // LED ON
}
}
void main() {
setup_timer_0(RTCC_INTERNAL|RTCC_DIV_256);//Timer 0 setup 16 bit mode
enable_interrupts(INT_RTCC);//enable timer0 and global interrupts
enable_interrupts(GLOBAL);
output_low(PIN_B5); // LED ON
while(1); // Wait for the interrupt
}// end of program

Example: Using PIC C, write a program to generate 10 sec trigger at


the output pin. Say, Port D Pin_0 will be high to low at every 10
second. Given maximum crystal frequency = 4 MHz. Show your
calculations. Use Timer 1.
Ans:
For 4 MHz clock frequency, we get, 4MHz/4 =1MHz
Time Period = 1S (micro sec)
if Prescaler is set to divide frequency by 8
Prescaler Period = 1 x 8 = 8 S
Overflow Period = 8 x 65535 sec
Each overflow time = 0.52 sec
To get delay for 10 sec, we need 10/0.52= 19 Overflows to count

#include <18F8722.h> //
int i=0;
Program for Timer 1 , Generate 10 sec delay trigger
#INT_TIMER1
void timer1interrupt() // program automatically jump on ISR when overflow occurred
{
i++; // count for 19 to make 10 sec
if (i==19)
{if (input(PIN_D0)==true)
output_low(PIN_D0);
else
output_high(PIN_D0);
i=0; // reset the count
}
}
main() {
setup_timer_1(T1_INTERNAL | T1_DIV_BY_8);
//Prescaler clock divide by 8
enable_interrupts(INT_TIMER1); // Enable Timer 1 interrupt
enable_interrupts(GLOBAL); // Enable Global interrupt
output_low(PIN_D0); // Set first pin D_0 low
while(1); // Wait for the interrupt
}// end of program

Timer 1 Module
Features:
Software selectable operation as a 16-bit timer or counter
Readable and writable 8-bit registers (TMR1H and TMR1L)
Selectable clock source (internal or external) with device clock or Timer1 oscillator
internal options
Module incorporates its own low-power oscillator to provide an additional clocking
option
Also used to provide Real-Time Clock (RTC) functionality to applications with only a
minimal addition of external components and code overhead
LOW-POWER TIMER1 OPTION
Timer1 oscillator can operate at two distinct levels of power consumption based on
device configuration
When the LPT1OSC Configuration bit is set, the Timer1 oscillator operates in a lowpower mode. When LPT1OSC is not set, Timer1 operates at a higher power level.
Higher power level: Power consumption for a particular mode is relatively constant,
regardless of the devices operating mode. The default Timer1 configuration is the
higher power mode.
Low-power: Timer1 mode tends to be more sensitive to interference, high noise
environments may cause some oscillator instability. The low-power option is, therefore,
best suited for low noise applications where power conservation is an important design
consideration

TIMER TMR1 PRESCALER

Timer TMR1 has a completely separate prescaler which allows


1, 2, 4 or 8 division of the clock input frequency
ADDITIONAL USE OF TIMER TMR1 OSCILLATOR

Power consumption of the microcontroller is reduced to the lowest level in


Sleep mode since the main power consumer - the oscillator - doesnt operate.
Set the microcontroller in this mode- by executing the SLEEP instruction

Problem is how to wake up the microcontroller because only an interrupt can


make it happen. Since the microcontroller 'sleeps', an interrupt must be
triggered by external electronics. It gets incredibly complicated if it is necessary
to wake up the microcontroller at regular time intervals...
In order to solve this problem, a completely independent Low Power quartz
oscillator, capable of operating in sleep mode, is built into the PIC18FXX
microcontroller

TMR1 IN COUNTER MODE


Work as a counter by TMR1CS bit = 1
Counts pulses brought to the PC0/T1CKI pin and is incremented on
the rising edge of the external clock input T1CKI
If T1SYNC= 0 (T1CON register), the external clock inputs will be
synchronized on their way to the TMR1 register. In other words, the
timer TMR1 is synchronized to the microcontroller system clock
and is called a synchronous counter
When the microcontroller, operating in this way, is set in sleep
mode, the TMR1H and TMR1L timer registers are not incremented
even though clock pulses appear on the input pins. Since the
microcontroller system clock doesnt run in this mode, there are no
clock inputs to be used for synchronization. However, the prescaler
will continue to run as far as there are clock pulses on the pins
because it is just a simple frequency divider

Timer 1 COUNTER MODE operation

Note: This counter registers a logic one (1) on input pins


(T1CKI). It is important to know that at least one falling edge
must be registered prior to starting pulse counting.

Aim: Each overflow in the Timer1 register consisting of TMR1H and TMR1L,
causes an interrupt to occur. In every interrupt routine, variable cnt will be
incremented by 1.
unsigned short cnt;

// Define variable cnt

void interrupt() {
cnt++ ;
// Interrupt causes cnt to be incremented by 1
PIR1.TMR1IF = 0;
// Reset bit TMR1IF
TMR1H = 0x80;
// TMR1H and TMR1L timer registers are returned
TMR1L = 0x00;
// their initial values
}
void main() {
ANSEL = ANSELH = 0; // All I/O pins are configured as digital
T1CON = 1;
// Turn on timer TMR1
PIR1.TMR1IF = 0; // Reset the TMR1IF bit
TMR1H = 0x80; // Set initial value for timer TMR1 (1280)
TMR1L = 0x00;
PIE1.TMR1IE = 1; // Enable an interrupt on overflow
cnt = 0; // Reset variable cnt
INTCON = 0xC0; // Enable interrupt (bits GIE and PEIE)
...

Example: Design a logic counter using PIC and Timer 1


Introduction:
A counter is an electronic instrument, or component of one, that
is used for measuring events/objects.
For example, number of boxes pass on conveyor belt, counting
bottles, car in a definite time
Basic operation of the hardware/software logic
Use Timer 1 as counter, which accumulates the number of events
occurring, may or may not within a specific period of time
Each count update, will be displayed on screen say LCD

Schematic Circuit connection with PIC 18F8722

#include <18F8722.h>
#device ICD=TRUE
#fuses HS,NOLVP,NOWDT
#use delay (clock=20000000)

PIC C program to count


Timer-1 as CounterMODE

#include "lcd.c // inbuilt LCD library


unsigned int16 value;
main() {
value=0;
lcd_init(); // Initialise the LCD
lcd_putc('\f'); // clear the screen
lcd_putc("Count Value = ");
while(1)
{
set_timer1(value); //Set timer1 count
setup_timer_1(T1_EXTERNAL|T1_DIV_BY_1);//take external clock input
T1CKI
delay_ms(100);
// wait for some time to settle timer
setup_timer_1(T1_DISABLED); // disable timer 1 to read present count
value=get_timer1(); // //read timer 1 count
lcd_gotoxy(11,4);
printf(lcd_putc,"%LU ",value); //display frequency count
}
}// end of program

Problem of Key debounce


Mechanical switches are used to interface with PIC microcontroller
usually push button type
Keys when pressed, bounces for few times, closing and opening few
times before providing stead state reading
Reading taken during bouncing period may be faulty
Therefore microcontroller has to wait until the key reach to a
steady state, known as key debounce

Method 1: Key Debouncer using Hardware

+5v
Y
A
B

Y
+5 v

Two cross-coupled NAND gates form a very simple SetReset (SR) latch
Design requires a double-throw switch
Two pull-up resistors generate a logic one for the gates;
the switch pulls one of the inputs to ground

Method 2: Key Debouncer using


Software

How to sense a Key through Port pin


Method 1: High

to low transition

int keyread(void){
if(input(PIN_A0)==0)
{while (input(PIN_A0)==0);
return(1); }
}
Call this function in main function

Method 2: Low

to High transition

int keyread(void){
if(input(PIN_A0))
{while (input(PIN_A0));
return(1); }
}
void main(void)
{ Call this function in main function
int keyno=0;

while(1){ // continues read the key input


keyno = keyread();
if(keyno==1){
//say for example ON the motor
}
}
}//end of the program

PIE1 Register : Contains Peripheral Interrupt Enable Bits


Each bit: 1 - Enable and 0 - Disable

ADIE - A/D Converter Interrupt Enable bit.


RCIE - EUSART Receive Interrupt Enable bit.
TXIE - EUSART Transmit Interrupt Enable bit.
SSPIE - Master Synchronous Serial Port (MSSP) Interrupt Enable bit - enables
an interrupt request to be generated upon each data transmission via
synchronous serial communication module (SPI or I2C mode).
CCP1IE - CCP1 Interrupt Enable bit enables an interrupt request to be
generated in CCP1 module used for PWM signal processing.
(Campture/Compare/PWM)

TMR2IE - TMR2 to PR2 Match Interrupt Enable bit


TMR1IE - TMR1 Overflow Interrupt Enable bit enables an interrupt request to
be generated upon each timer TMR1 register overflow, i.e. when the counting
starts from zero

PIR1 Register: Contains the interrupt flag bits

ADIF - A/D Converter Interrupt Flag bit


1 - Conversion - completed (bit must be cleared from within the software)
0 - Not completed or has not started.
RCIF - EUSART Receive Interrupt Flag bit.
1 Receive buffer is full. Bit is cleared by reading the RCREG register.
0 - Not full.
TXIF - EUSART Transmit Interrupt Flag bit.
1 - Tx buffer is empty. The bit is cleared by any write to the TXREG register.
0 - Tx buffer is full
SSPIF - Master Synchronous Serial Port (MSSP) Interrupt Flag bit.
1 - Interrupt conditions during data transmit/receive have occurred
0 - No MSSP interrupt condition has occurred.
CCP1IF - CCP1 Interrupt Flag bit - (CCP1 is unit for capturing, comparing and generating PWM signal)
1 Interrupt condition has occurred
0 - No interrupt
TMR2IF - Timer2 to PR2 Interrupt Flag bit
1 - TMR2 (8-bit register) to PR2 match has occurred
0 - No TMR2 to PR2 match has occurred.
TMR1IF - Timer1 Overflow Interrupt Flag bit
1 - TMR1 register has overflowed
0 - TMR1 register has not overflowed.

Example: Write a PIC C code and design a circuit which can be


used to display the number From 0 9999. Use Common Cathode
type four seven segments.

Port
D

Port
A

Output port as Port D to send hex code to display


One segment is selected at a time from Port A (A0-A3)

PIC C program to display 0-9999 numbers continuously


unsigned char Segments[4]={0,0,0,0};
main(void) {
byte const h_code[10]= {0xBF,0x86,0xDB,0xCF,0xE6,0xED,0xFD,0x87,0xFF,0xEF};
// array of hex code for common cathod type
int i,j,num,thou,hund,tens,units,digits; // variable initialization
while(1){
for(i=0; i<10000; i++){
thou=(i/1000)%10; //extract thousand digit
hund=(i/100)%10; // extract 100th digit
tens=(i/10)%10; // extract 10th digit
units=i%10; // extract units digit
for(j=0;j<20;j++) //should display each ten and unit for 400ms
{
Segments[3]=thou;
Segments[2]=hund;
Segments[1]=tens;
Segments[0]=units; //copy respect segment digits to display
.next slide

output_high(PIN_A0);
output_low(PIN_A1);
output_low(PIN_A2);
output_low(PIN_A3); // select ones segment
output_D(h_code[Segments[0]]); // output 7-seg code from array
delay_ms(5);
output_low(PIN_A0);
output_high(PIN_A1);
output_low(PIN_A2);
output_low(PIN_A3);

//select 10th segment

output_D(h_code[Segments[1]]); // output 7-seg code from array


delay_ms(5);
output_low(PIN_A0);
output_low(PIN_A1);
output_high(PIN_A2);
output_low(PIN_A3);

//select 100th seg

output_D(h_code[Segments[2]]); // output 7-seg code from array


delay_ms(5);
.next slide

output_low(PIN_A0);
output_low(PIN_A1);
output_low(PIN_A2);
output_high(PIN_A3);

//select 1000th seg

output_D(h_code[Segments[3]]); // output 7-seg code from array


delay_ms(5);

}//end display loop


}//end for loop
i=0;
}//repeat while loop continously

}// end of program

Home exercise:
Now our goal is to construct a simple 0-9999 seconds
count down timer with an alarm and a display.
The time is set through two input switches (named INC
and TSET for setting time and turning the timer on)
and the count down seconds are displayed on a 4-digit
seven segment LED display.
Time out condition is to indicate by an audible alarm
from a buzzer

External Interrupt
How we can capture a pulse to generate/ activate an
interrupt in PIC?

PIC18F8722 has four External


RB2/INT2 and RB3/INT3

Interrupt is triggered by an input on INTx pin either (depending on how we


set it up ) as the signal goes from 0 to 1, called the rising edge, or as the
signal goes from 1 to 0, called the falling edge. This sets the interrupt flag,
and if the interrupt is enabled, microcontroller goes to the interrupt
subroutine
Interrupt priority for INT1, INT2 and INT3 is determined by the value
contained in the interrupt priority bits, INT1IP (INTCON3<6>), INT2IP
(INTCON3<7>) and INT3IP (INTCON2<1>)
No priority bit associated with INT0 always a high-priority

interrupts:

RB0/INT0,

RB1/INT1,

Take an Example
Design a digital dice using PIC microcontroller such
that
Continuous display number is not readable to user on
Screen
When user presses a button, exactly same time, display
number is stopped and visible to the user
Make this application real-time
Suggest circuit connection

Push - button

External Interrupt via INT

External Interrupt enable for Digital Dice circuit diagram

PIC C code for Digital Dice


//Digital Dice
#include <18F6722.h>
#int_ext //Set external interrupt on pin RB0- INT0
void int_isr() // program automatically jump on ISR when overflow occured
{
disable_interrupts(GLOBAL); //disable interrupt temper.
output_low(PIN_B4); //indicate interrupt via LED port B_4
delay_ms(1000); //wait to display number to notify
}
main() {
int j=0;
byte const h_code[6]= {0x86,0xDB,0xCF,0xE6,0xED,0xFD}; // Hex code for 1 to 6
output_b(0x00); //clear port B
set_tris_b(0x01); // Set RB0 to input, RB1-7 output
PORT_B_PULLUPS(0); //disable internal pull-ups
ext_int_edge(H_TO_L); // init interrupt triggering for button press
enable_interrupts(INT_EXT); //enable external interrupt
enable_interrupts(GLOBAL); //enable global interrupt
output_high(PIN_B4); //Interrupt indicator LED- off
while(true)
{ for(j=0; j<7;j++) {//display 1-6 digit on segment
output_D(h_code[j]); // output 7-seg code from array
delay_ms(15);
output_high(PIN_B4);// LED off to indicate no interrupt
enable_interrupts(GLOBAL);}}}// end of program

Other external interrupts


External interrupts
INT_EX1 Port B_1
INT_EX2 Port B_2
INT_EX3 Port B_3
Eg.
#int_ext1
void int_isr() {}

PORTB Interrupt-on-Change
An input change on PORTB<7:4> sets flag bit,
RBIF (INTCON<0>)
Interrupt
can
be
enabled/disabled
by
setting/clearing enable bit, RBIE (INTCON<3>).
Interrupt priority for PORTB interrupt-on-change
is determined by the value contained in the
interrupt priority bit, RBIP (INTCON2<0>).

INTCON: INTERRUPT CONTROL REGISTER

INTCON2: INTERRUPT CONTROL REGISTER 2

INTCON3: INTERRUPT CONTROL REGISTER 3

Interfacing Relay with PIC using Transistor

Gnd

Analog-To-Digital Converter
Total 16 separate analog inputs/channels (AD0-AD15) in
18F8722 and 12 in 18F6722
A 10-bit binary ADC
A/D converter converts an analog input signal into a 10-bit binary
number
Method: Successive Approximation Convertor
Store the conversion results into the ADC registers (ADRESL and
ADRESH);
Minimum resolution or quality of conversion may be adjusted to
various needs by selecting voltage references RA2/AN2/Vref- and
RA3/AN3/Vref+.
A/D converter has a unique feature of being able to operate while the
device is in Sleep mode. To operate in Sleep, the A/D conversion
clock must be derived from the A/Ds internal RC oscillator.

ADCON0: A/D CONTROL REGISTER

ADCON1: A/D CONTROL REGISTER 1

ADCON2: A/D CONTROL REGISTER 2

Overall operation and logic diagram for ADC operation

In order to enable the A/D converter to run without


problems as well as to avoid unexpected results, Follow
steps as below:
1. Configure input pins as analog inputs before the process
of conversion starts
2. Voltage measurement in the converter is based on
comparing input voltage with internal scale which has
1024 marks (210 = 1024). The lowest scale mark stands
for the Vref- voltage, whilst its highest mark stands for the
Vref+ voltage.

Temperature sensor
LM35

Commonly use, low cost, linear temperature sensor


LM35 has a Three-Pins (Vcc, Output, GND)
High precision temperature sensor having a resolution of 10mV/C
starting at 0V (i.e. an output of 0V represents a temperature of 0C).
So,
10mV ---> 1C
20mV ---> 2C
370mV ---> 37.0C and so on.
LM35DZ 0 oC to +100oC
LM35CZ -40 oC to +100oC

Use of ADC to measure temperature via PIC Microcontroller


ADC is an internal module used to read analog voltages in the
form of a digital representation
PIC18Fxx has -10Bit resolution ADC module
Set reference voltage (Vref), which is the maximum voltage an
ADC can read, in our case Vref = 5V which is the supply voltage
ADC resolution, which determines the minimum value of analog
voltage can read (ADC Step size).
For example, 10 bits digital number with low voltage reference
(Vref-) 0v and high voltage reference (Vref+) 5V., then
0v = 0 0 0 0.0
5v = 1 1 1 11

Resolution
= (Vref+ Vref-)/(1024-1) (as it is 10 bit ADC)
= 5/1023
= 4.887 mV
An input of 4.887mV would give us a reading of 00--01
An input of 9.776mV would give us a reading of 00--0, and so on.

Converting ADC Reading to Celsius degrees:


Knowing that our ADC has a step size of 4.887mV, converting
our digital reading back to voltage is simply done by multiplying
the digital reading by the step size:

Vin (in Volts) = DigitalReading * 0.004887


Now, we know our sensor's sensitivity is 10mV/C,
converting this voltage to Celsius is simply done by
dividing the input voltage by 0.01, So:
Temperature (oC) = Vin/0.01 = DigitalReading * 0.4887

Circuit connection with PIC 16F877

Important note for ADC to meet specified accuracy

To meet ADC specified accuracy, Necessary to provide a


certain time delay between selecting specific analog input
and measurement itself called acquisition time

If you want the conversion to be accurate, dont forget


this important detail
Mainly depends on the source impedance, this time in the
worst case amounts to approximately 20uSec

//Temperature Sensor - LM35 With LCD-PIC


#include <18F8722.h> //16F877 Pic in use
#include "lcd.c"
int16 digital_reading; // ADC resolution is 10Bit, an 8Bit integer is not enough to
hold the reading float temp;
main() {
lcd_init(); // Initialise the LCD
lcd_putc('\f'); // clear the screen
lcd_gotoxy(1,1);
lcd_putc("Temperature::");

Without
ADC
Interrupt

/* ADC Initialization */
setup_adc(ADC_CLOCK_INTERNAL);
// initialize ADC with a sampling rate of Crystal/4 MHz
setup_adc_ports( ALL_ANALOG );
set_adc_channel(1);
// point ADC to channel 1 (RA1/AN1) for reading
delay_ms(1);
// ADC module is slow, needs some time to adjust.
continue..next slide

while(1) // infinite loop


{
digital_reading = read_adc();
// capture current temperature reading
delay_us(100);
// 0.1ms delay for ADC stabilization
temp = digital_reading * 0.4883; // convert reading to Celsius
lcd_gotoxy(10,2);
// point LCD cursor to col1 row2
printf(lcd_putc,"%2.1f C",temp); // print value on LCD
delay_ms(1000); // 1 second delay between readings
}
}// end of program

Can we modify above program using ADC Interrupt?


main() {
With ADC
//Initialize LCD
Interrupt
/* ADC Initialization */
setup_adc(ADC_CLOCK_INTERNAL);
setup_adc_ports( ALL_ANALOG );
//setup_adc_ports(AN0_VREF_VREF ); //for external
reference // A0 VRefh=A3 VRefl=A2
set_adc_channel(1);
enable_interrupts(INT_AD); //Interrupt ADC enable
enable_interrupts(GLOBAL);
delay_ms(1); // Wait for the required acquisition time to pass.
read_adc(ADC_START_ONLY); //Prime ADC interrupt
while(1);
}

Continue..

// ISR for ADC


#INT_AD
//Analog to Digital Converter - Conversion Done ISR
void ADC_done()
{
digital_reading = read_adc(ADC_READ_ONLY);
// capture current temperature reading
temp = digital_reading * 0.4883; // convert reading to Celsius
lcd_gotoxy(10,2);
// point LCD cursor to col1 row2
printf(lcd_putc,"%2.1f C",temp); // print value on LCD
read_adc(ADC_START_ONLY); //Prime ADC_Done interrupt

Sensors
1. Humidity and Temperature Sensor - RHT03/DHT-22
Low cost humidity and temperature sensor with a single wire digital
interface
Already calibrated and doesnt require extra components so you can get
right to measuring relative humidity and temperature
Features:
3.3-6V Input
1-1.5mA measuring current
40-50 uA standby current
Humidity from 0-100% RH
-40 to 80 degrees C temperature range
+-2% RH accuracy
+-0.5 degrees C

Output from RHT03:


Data is comprised of integral and decimal part, the following is the formula for
data.
DATA=8 bit integral RH data+8 bit decimal RH data+8 bit integral T data+8 bit
decimal T data+8 bit check-sum

2. Ultrasonic Range Finder: TS601-01


Non-contacted ultrasonic measurement, TS601 ultrasonic electric telemeter
module can measure a distance within 0.03-3M effectively
Low-cost, precise and non-contact distance measurement
Perform measurements between moving or stationary objects
Simple pulse in/pulse out communication
Technical Specification

Operation:
Measures distance using sonar; an ultrasonic (well above
human hearing range) pulse is transmitted from the unit
and distance-to-target is determined by measuring the
time required for the echo return.
Output from the sensor is a variable-width pulse that
corresponds to the distance to the target
Applications and Uses
UAV blimps, micro planes and some helicopters
Bin level measurement
Proximity zone detection
People detection
Robot ranging sensor
Autonomous navigation
Multi-sensor arrays
Distance measuring
Long range object detection
Wide beam sensitivity

Principle of operation
TS601 module with a impulse
through SIG, the trailing edge
springs, and transmits a string of
ultrasonic signal of 40KHz when
the module receives it. Then the
electrical level of SIG stitch will
be risen. The duration of high level
T3 will be ensured by the distance
between the object and the
telemeter. After 19.5ms, the high
level descends, when no object is
in a distance of 3M. The host
computes the distance though the
impulse width input by the
electronic
eye
module:
S=(V*T3)/2.

3. Infrared Proximity Sensor Long Range Sensor


It has an analog output that varies from 2.8V at 15cm to 0.4V at 150cm with a
supply voltage between 4.5 and 5.5VDC
Features
Distance measuring range : 20 to 150 cm
Analog output type
Package size : 29.51321.6 mm
Consumption current : Typ. 33 mA
Supply voltage : 4.5 to 5.5 V

Applications
Touch-less switch (Sanitary equipment, Control of illumination, etc. )
Sensor for energy saving (ATM, Copier, Vending machine, Laptop computer, LCD
monitor)
Amusement equipment (Robot, Arcade game machine)

Example of distance measuring


characteristics (output)

Example: (Discuss in class)

A 16-bit PIC hardware timer is driven


from the internal clock signal, and the
MCU is operating with a 20-MHz
crystal. Calculate the preload value
required to produce an interrupt every
10 ms.
With prescaler = 1: preload value in timer1=15535

Example: What should be the value that we


put in register TMR0 so that timer0 will
generate an interrupt after 62 sec given
that fosc=4MHz?
With prescaler=1, Timer0 preload value = 194

Example: A 16-bit PIC hardware timer is driven from the internal


clock signal, and the MCU is operating with a 20-MHz crystal.
What should be the preload value to obtain an interrupt at every
10 ms with prescaler =1

Example:
In the following circuit, the analog input is connected to pin#3 (RA1/AN1). You can vary
the analog input value by varying the resistance of the potentiometer (10K) in the circuit.
The output will be displayed using 10 LEDs, connected common cathodes to Port B and
Port C0-1. Use low voltage reference (Vref-) 0v and high voltage reference (Vref+) 5V.
i. Write a PIC C program to setup for converting input analog signal into equivalent 10-bit
output. Turn on/off LEDs as per the digital output.
ii. Draw the flowchart of operation, to convert continuous analog input into digital output.
iii. Find the resolution of the conversion for the 10 bit digital output.

Motor Interface with PIC Controller


Motor Types
1. DC Motor:
A DC motor usually means a permanent-magnet, direct-current (DC)
motor of the sort used in toys, models, cordless tools, and robots
These motors are particularly versatile because both their speed and
direction can be readily controlled; speed by the voltage or duty cycle of
their power supply, and direction by its polarity
DC motors provide different amounts of torque depending on their
running speed, which is measured in RPM (revolutions per minute)

2. Stepper Motor
Work in a similar way to DC motors, but where DC motors have one
electromagnetic coil to produce movement, stepper motors contain many
Stepper motors are controlled by turning each coil on and off in a
sequence
Every time a new coil is energized, the motor rotates a few degrees,
called the step angle.
For example, a stepper motor with a step angle of 7.5 degrees requires
48 pulses for a complete revolution! (3600)

Interfacing Stepper Motor with PIC

A Stepper Motor is a brushless, synchronous DC Motor


Total rotation of the motor is divided into steps
Angle of a single step is known as the stepper angle of the
motor.

Two types: Unipolar and Bipolar stepper motor


Due to the ease of operation unipolar stepper motor
is commonly used by electronics hobbyists
Easily interfaced with a microcontroller using
driver ICs such as L293, ULN2003 or SN754410

Important to understand the color code of the


stepper motor for identifying the Coils and
Common wire
Use in many
mechatronics

applications:

robotics

and

Unipolar stepper motors can be used in three modes


1. Wave Drive,
2. Full Drive and
3. Half Drive mode.
Each drive has its own advantages and disadvantages, thus we
should choose the required drive according to the application and
power consumption

1. Wave Drive
In this mode only one electromagnet is energized at a
time
Generated torque will be less when compared to full
drive But Power consumption is reduced
It has same number of steps as in the full drive
This drive is preferred when power consumption is
more important than torque (It is rarely used!)
Wave Drive Stepping Sequence
Step

2. Full Drive
In this mode two electromagnets are energized at a
time, so the torque generated will be larger when
compared to Wave Drive
Commonly used, Power consumption will be higher
than other modes
Full Drive Stepping Sequence
Step

3. Half Drive
In this mode alternatively one and two electromagnets are
energized, so it is a combination of Wave and Full drives
This mode is commonly used to increase the angular resolution
of the motor but the torque will be less, about 70% at its full
step position
We can see that the angular resolution doubles when using Half
Drive.
Half Drive Stepping Sequence

Step

Stepper motor interfacing with PIC and Driver IC


+5 vDC

Stepper
Motor
SN754410

void main(void)
{
char st_code[4]= {0x0C,0x06,0x3,0x09}; // clock wise rotation-full wave drive
%char st_code1[4]= {0x08,0x04,0x02,0x01}; // clock wise rotation- wave drive
%char st_code2[4]= {0x01,0x02,0x04,0x08}; // anti-clock wise rotation - wave
int i=0;
while(1)
{
for(i=0; i<4; i++){
output_B(st_code[i]); // output to port B to drive Stepper
delay_ms(10); //delay between two steps
}
}
}

3. Servo Motor
Special geared DC motor equipped with an electronic circuit for
controlling the direction of rotation, as well as the position, of the
motor shaft
Because servo motors allows precise angular positioning of their
output shaft
Very useful in robotics and radio-controlled cars, airplanes, and
boats to control the motion of their various parts.

Basic knowledge about Servo Motor


To achieve precise angular positioning of an object, an instantaneous positioning
information of the output shaft is fed back to the control circuit using a transducer
A simplest way: Attach a potentiometer to the output shaft or somewhere in the
gear train
Electronics compares the feedback signal (which contains the current position of
the shaft) from the potentiometer to the control input signal (which contains
information of the desired position of the shaft), and any difference between the
actual and desired values (known as an error signal) is amplified and used to drive
the DC motor in a direction necessary to reduce or eliminate the error. The error is
zero when the output shaft gets to the desired position
Functioning block diagram of a typical servomotor is shown below

Control input to a servo is a pulse width modulated (PWM) signal, generally of


frequency 50 Hz. This means the pulse should repeat every 20ms. The width of
the pulse determines the angular position of the output shaft
Always refer datasheet of the servo to find the true values of the pulse widths
required for positioning the servo at different angles
Most servos rotate through 180. However, some can rotate through a full 360
or more.
A servomotor has three wires: two are designated for power supply (Vcc and
Ground) and the third wire is for the control signal

Microcontroller is used effectively to control speed/position via


Pulse-Width-Modulation (PWM)
PWM: Its technique in which we change the pulse width to get the
desired duty cycle
DC Motor: Change duty cycle for desired speed
Servo Motor: Change duty cycle for desired position
What is PWM?
A square wave signal is described by three parameters, Amplitude, Frequency and Duty cycle
Term "duty cycle" describes the ratio of the ON state of the signal to the period of that signal,
i.e. Duty = TON/ T = TON/( TON+TOFF)
Duty cycle has no unit, its represented by percentage with 100% describing the fully ON state
and 0% describing the fully OFF state

Issues when Interfacing Motors with PIC


Can not drive a Motor directly with PIC, since it requires high current and high
voltage
PIC usually operates at +5 supply and it I/O pin can provide only up to 25mA
current
Whereas commonly used DC Motors requires 12V and 300mA current
Also, it produces a back EMF, harmful for digital low voltage devices
To solve these problems, we use H-bridge circuits
H-bridge uses Transistors/MOSFETs as switches or better to use ready made
ICs - L293D and L293 or SN754410
One IC: can control two DC Motors in both clock wise and counter clockwise
directions
Useful also to drive bipolar stepping motors, relays and solenoids
All inputs of these ICs are TTL compatible and output clamp diodes for
inductive transient suppression are also provided internally. These diodes protect
our circuit from the Back EMF of DC Motor

Give high to enable

Give high to enable

Interfacing DC Motor with PIC and L293D


Circuit Diagram

DC Motor

L293

PIC18F8722: PWM Module


Total Five PWM modules included in the CCP4,CCP5 modules
(CCP stands for Capture-Compare-PWM), and other three modules
(ECCP1, ECCP2, ECCP3) implement standard Capture and
Compare modes, as well as Enhanced PWM modes
Follow 3 steps to use this module:
1. Set the desired CCP module to PWM mode
2. Setup The TIMER-2 or TIMER-4 module, which controls the
frequency and the base of your PWM signal
3. Set your duty cycle
Step1: Set CCP1 module to PWM mode, Use the code line:
setup_ccp1(CCP_PWM);

Step2: Now set Timer2 module using PIC-C


setup_timer_2(divider, preload, postscalar)
Here, divider and the preload values determines the
frequency of the PWM signal by the following function:
Signal Frequency = (Crystal/4) / (divider * (preload+1))

Divider takes the values : T2_DIV_BY_1, T2_DIV_BY_4, T2_DIV_BY_16


Preload is 8Bits and takes the values 0-255
Let, we have 20MHz crystal and we set Timer2 like this:
setup_timer_2( T2_DIV_BY_1, 255, 1);
So our signal frequency is
= (20MHz/4)/(1 * 256) = 19.531 KHz

Period=51.2 S

Step3: Final step is to set your duty cycle using the


function: set_pwm1_duty(duty_parameter);
Maximum value of duty_paramter (MAX)
= ((preload+1)*4) -1 = ((255+1)*4)-1 = 1023
and it represents a 100% duty cycle
If we need a duty cycle of 50% it would be 1023*0.5
= 512,
set_pwm1_duty(1023L); ---> 100% duty (Full Speed)
set_pwm1_duty(512L); ----> 50% duty
set_pwm1_duty(256L); ----> 25% duty
set_pwm1_duty(0);
----> 0% duty (OFF)

#include <18F6722.h>
#device ICD=TRUE
#fuses HS,NOLVP,NOWDT
#use delay (clock=40000000)
main() {
// PWM Configurations
setup_timer_2(T2_DIV_BY_1,255,1); // Set PWM frequency
setup_ccp1(CCP_PWM); // Configure CCP1 to PWM mode
set_pwm1_duty(512); // 50% duty cycle (Half Speed)
while(1);
}// end of program

Note: CCP1 module gives PWM output at Port C_2

PWM output with 50% duty cycle setting

PWM output with 25% duty cycle setting

PIC 18F6722
Port C_2
Port B_6

Port B_7

Controller

CCP1-out

Driver IC

Speed Control using PWM


Square wave signal is described by three parameters,
Amplitude, Frequency and Duty cycle
Term "duty cycle" describes the ratio of the ON state of
the signal to the period of that signal,
i.e. Duty = TON/ T = TON/( TON+TOFF)

Duty cycle has no unit, its represented by percentage with


100% describing the fully ON state and 0% describing the
fully OFF state

Idea of speed control is to switch the motor ON and OFF


at varying speeds

Say, a 12V DC motor we applied a constant 12V signal to


that motor, the motor would run in its full power (full speed)

Assume, a 50% duty cycle (at several KHz frequency), the


motor will turn ON and OFF continuously and the effective
voltage applied to the motor is 6V, this would decrease
the motor speed by the half, and the motor would be running
at 50% of it's full power

Varying the duty cycle of the applied signal would cause


the speed to vary, a 0% duty cycle signal would turn
OFF the motor, and a 100% one would run the motor at
it's full speed.

Hardware Speed and Direction control logic

Motor connected to OUT1,OUT2 respectively,


and Inputs IN1,IN2 controls the direction of
rotation from Microcontroller
Setting IN1=1 IN2=0 would rotate the motor
clockwise, while setting IN1=0 IN2=1 would
rotate it counter clockwise, and the setting
IN1=0 IN2=0 would turn it OFF
Pin ENA (Enable motor) is used turn ON/OFF
the motor regardless of the inputs IN1 IN2,
thus, our PWM signal could be connected to
ENA to control the speed of the motor.

//DC Motor speed

#include <18F6722.h>
#use delay(clock=4000000) //clock 4Mhz frequency
int16 duty_cycle; // since the value has 10bit
int i;
main() {
// PWM Configurations
setup_timer_2(T2_DIV_BY_1,255,1); // Set PWM frequency
setup_ccp1(CCP_PWM); // Configure CCP1 to PWM mode
set_pwm1_duty(1023L); // default duty cycle = 100% (Full Speed)
//
while(1){
output_low(PIN_B6); // set one direction-clock wise
output_high(PIN_B7);
delay_ms(5000);
output_high(PIN_B6); // set anticlock wise direction
output_low(PIN_B7);
}
}// end of program

To interface TWO DC motor with microcontroller

Example (Final exam S1-2014)


A mobile robot is controlled with two DC motors.
Write a PIC C program which will perform the following operations:
Move the robot forward for 1 s
Take left and run for 1 s
Take left again and run for 1 s
Take left again and run for 1 s
Stop
Set 25% duty cycle in all operations. Also, give a suitable circuit
diagram to drive the motors through PIC.

Example: As shown in Figure below, the automated drilling machine with conveyor belt is
required to stop the motor for two seconds during drilling the plot.
Suppose, plate position is detected with proximity sensor, and then clamp comes down to
hold the plate and driller activated for two seconds. During this process, motor/conveyor
belt suppose to be stopped.
Use PIC18F6722 and develop application real-time.

Interface Matrix Keypad with PIC


Matrix Keypad is a very useful for applications like
Calculator, Telephone, Mobilephone etc.
Made up with push button switches, arranged in rows and
columns
4*4 = 16 keys : 4 rows and 4 columns, 3*3 = 9 keys..

How to detect the particular Key pressed ?


Logic:
Take all column connections (Col1 Col4) as
output pins
All row connections (Row1 Row4) as input pins
In the normal case (not scanning) all column inputs
set in LOW (GND) state

Programming logic to detect pressed key


Scan the keypad in a loop..
1. Set logic HIGH to Col-1 (column no. 1)
2. Then scan each Row output (Row1 Row4) one by
one
If any of the key belongs to first column is pressed, the
Logic high signal from the Col-1 will pass to that row.
Through we can detect the key
3. This process is repeated for all columns if we want to
detect multiple keys.
(Remember: For reading data for the Matrix Keypad,
each column is made high and rows are scanned)

Example:
Write a PIC C program to detect the one key at a time and
display that pressed key number on LCD display. Use 4*4
key pad.
Solution:
Let, Matrix Keypad is connected to the PORT-A and
PORT - C of the PIC Microcontroller as follows
// Pin Assignment
// pin a2 ..... col 1
// pin a3 ..... col 2
// pin a4 ..... col 3
// pin a5 ..... col 4
// pin c0 ..... row 1
// pin c1 ..... row 2
// pin c2 ..... row 3
// pin c3 ..... row 4

//
//
//
//
//
//
//
//

Each column of the Matrix Keypad is connected to RA2


RA5 and configured as output pins
Each row is connected to RC0 RC3 and configured as input
pins

int read_keypad(void)
{ output_a(0x00); // clear the ports
output_c(0x00);
while(1) // Loop to infinity
{
output_high(PIN_a2); // first column high for scanning purposes
if(input(PIN_c0)) // if row 1 goes high then
{while (input(pin_c0));
return(1); // key being pressed is one
}
else if(input(PIN_c1)) // if row 2 goes high then
{while (input(pin_c1));
return(5); // key being pressed is four
}
else if(input(PIN_c2)) // if row 3 goes high then
{while (input(pin_c2));
return(9); // key being pressed is seven
}
else if(input(PIN_c3)) // if row 4 goes high then
{while (input(pin_c3));
return(13); // key being pressed is ten
}
output_a(0x00); // Clear Port A

Continue key detect function


output_high(PIN_a3); // second column high for scanning purposes
if(input(PIN_c0)) // if row 1 goes high then
{while (input(pin_c0));
return(2); // key being pressed is two
}
else if(input(PIN_c1))
// if row 2 goes high then
{while (input(pin_c1));
return(6); // key being pressed is five
}
else if(input(PIN_c2))
// if row 3 goes high then
{while (input(pin_c2));
return(10); // key being pressed is eight
}
else if(input(PIN_c3))
// if row 4 goes high then
{while (input(pin_c3));
return(14); // key being pressed is eleven
}
output_a(0x00); // Clear Port A

output_high(PIN_a4); // third column high for scanning purposes


if(input(PIN_c0)) // if row 1 goes high then
Continue key detect function
{while (input(pin_c0));
return(3); // key being pressed is three
}
else if(input(PIN_c1)) // if row 2 goes high then
{while (input(pin_c1));
return(7); // key being pressed is six
}
else if(input(PIN_c2)) // if row 3 goes high then
{while (input(pin_c2));
return(11); // key being pressed is nine
}
else if(input(PIN_c3)) // if row 4 goes high then
{while(input(pin_c3));
return(15); // key being pressed is tweleve
}
output_a(0x00); // Clear Port A

Continue key detect function


output_high(PIN_a5); // fourth column high for scanning purposes
if(input(PIN_c0)) // if row 1 goes high then
{while (input(pin_c0));
return(4); // key being pressed is fifteen
}
else if(input(PIN_c1)) // if row 2 goes high then
{while (input(pin_c1));
return(8); // key being pressed is fourteen
}
else if(input(PIN_c2)) // if row 3 goes high then
{while (input(pin_c2));
return(12); // key being pressed is thirteen
}
else if(input(PIN_c3)) // if row 4 goes high then
{while (input(pin_c3));
return(0); // key being pressed is zero
}
output_a(0x00); // Clear Port A
} // repeat loop until a key is pressed
}
End of key detection function

Main function to call read_keypad(void)


void main(void)
{
int innum=0;

lcd_init(); // Initialise the LCD


lcd_putc('\f'); // clear the screen
while(1){ // continues read the key input
innum = read_keypad();
printf(lcd_putc,"%d", innum);
}

10

11

12

14

15

}//end of the program

13

Example: Detect Key and Display on 7-Segmement


Columns
As output

Rows
As inputs

Sources: http://www.electrosome.com/

USART
USART: Universal Synchronous Asynchronous Receiver
Transmitter (USART) module is a serial I/O communication
peripheral unit
Modern version: called somewhat differently EUSART:
Enhanced Universal Synchronous Asynchronous Receiver
Transmitter
Also known as Serial Communications Interface (SCI)
Contains all clock generators, shift registers and data buffers
necessary to perform an input/output serial data transfer
independently
Clock for synchronization, this module can also establish
Asynchronous connection, Some of the applications: like, radio or
infrared remote control using asynchronous transmission for data
transfer

PIC18F6722 has the following features:

Master Synchronous Serial Port (MSSP) module is a serial interface, useful for
communicating with other peripheral or microcontroller devices
Two MSSP modules: MSSP1 and MSSP2, each operates independently
Each MSSP module consists of a transmit/receive shift register (SSPxSR) and a
buffer register (SSPxBUF)
SSPxSR shifts the data in and out of the device, MSb first.
SSPxBUF holds the data that was written to the SSPxSR until the received data
is ready.
Once the 8 bits of data have been received, that byte is moved to the SSPxBUF
register. Then, the Buffer Full detect bit, BF (SSPxSTAT<0>) and the interrupt
flag bit, SSPxIF, are set.
Double-buffering of the received data (SSPxBUF) allows the next byte to start
reception before reading the data that was just received
Write Collision Detect bit, WCOL (SSPxCON1<7>), will be set if any write to
the SSPxBUF register during transmission/reception of data will be ignored.

The Buffer Full bit, BF (SSPxSTAT<0>), indicates when SSPxBUF has been
loaded with the received data (transmission is complete).
When the SSPxBUF is read, the BF bit is cleared.

PIC18F6722 has the following features:


Full-duplex asynchronous transmit and receive;(?)
Programmable 8- or 9-bit wide characters;
Half-duplex communication in synchronous mode (?)
Input buffer overrun error detection

USART ASYNCHRONOUS MODE

Doesnt use clock signal

Briefly, each data is transferred in the following way:


In idle state, data line has high logic level (1);
Each data transmission starts with the START bit which
is always a zero (0);
Each data is 8- or 9-bit wide (the LSB bit is transferred
first); and
Each data transmission ends with the STOP bit which is
always a one (1).

Common way of connecting PIC that uses EUSART module


MAX232: Used as a voltage level converter.

MAX232

The bit period is set by the baud rate. A typical value is 9600
baud, which is about 10 k bits per second

SPI clock rate (bit rate) is user programmable to be one of the following:
FOSC/4 (or TCY)
FOSC/16 (or 4 TCY)
FOSC/64 (or 16 TCY)
Timer2 output/2
Allows a maximum data rate (at 40 MHz) of 10.00 Mbps

EUSART ASYNCHRONOUS TRANSMITTER


Necessary to configure EUSART module to operate as a
transmitter
TXEN = 1 - EUSART transmitter is enabled by setting the TXEN
bit of the TXSTA register
SYNC = 0 - EUSART is configured to operate in asynchronous
mode by clearing the SYNC bit of the TXSTA register
Write Data into the TXREG register
This Byte will be immediately transferred to the shift register
TSR;
TXREG register remains empty, which is indicated by setting the
flag bit TXIF (PIR1 register)
If the TXIE bit of the PIE1 register is set, an interrupt will be
generated.
However, the flag is set regardless of whether an interrupt is enabled
or not and it cannot be cleared by software, but by writing new data
to the TXREG register

EUSART ASYNCHRONOUS RECEIVER


Set bit CREN - EUSART receiver is enabled by setting the
CREN bit of the RCSTA register
When START bit is detected, data is transferred to the shift
register RSR through the RX pin
Data is automatically transferred to the RCREG register (if
empty)
Flag bit RCIF is set and an interrupt occurs, if enabled by the
RCIE bit of the PIE1 register
Similarly to the transmitter, the flag bit is cleared by software
only, i.e. by reading the RCREG register

It can take Two character FIFO memory (first in, first-out) which
allows reception of two characters simultaneously

PIC18F6722 and Use of RS232 Port


RS-232 is a popular serial communications standard used

on most PCs and many embedded systems


Two wires are used (in addition to ground), one for outgoing
data and one for incoming data

PIC18F6722 chip has built-in hardware to buffer the serial


data if pins C6 and C7 or G1 and G2 are used
Compiler will allow any pins to be used and will take
advantage of the built-in hardware if you pick those pins
Add following line before main program function
#use rs232 (baud=9600, xmit=PIN _ C6, rcv=PIN _ C7)

Steps to follow during RS232 Communication with the Computer

From Kit Exercise Book

Example:
Wireless communication through Serial Input/Output pins (TX and RX)
- Sample diagram with PIC16F877 for Temperature Display with wireless communication

Tx Pin

Transmitter wireless module TxC1

Rx Pin

Receiver wireless module RxC1

/*WIRELESS TEMPERTURE SENSOR MODULE...CODE FOR TRANSMITTER


#include <16F877.h> //16F877 Pic in use
#device *=16 // This allows auto variables over location 0xFF
#use delay(clock=4000000) //clock 4Mhz frequency
#fuses XT,NoWDT // crystal osc used & no watch dog timer used
#use rs232 (baud = 1200, parity = N, xmit = PIN_c6, rcv = PIN_c7)//RS232 comm
#opt 9
#org 0x1f00, 0x1fff void loader16f877(void) {} //Bootloader program
main()
{
int s=0;
setup_adc_ports(adc_clock_internal); //setup ADC
setup_adc(AN0_AN1_AN2_AN3_AN4);
set_adc_channel(0);
// adc PIN A0 is set as default
while(1) //continuous while loop
{
s = read_adc(); //lm35 reading taken at channel 0 (AN0) and stored at variable 's'
putc(s);
delay_ms(100);
}}

/*WIRELESS TEMPERTURE SENSOR MODULE...CODE FOR RECIEVER


#include <16F877.h> //16F877 Pic in use
#device *=16 // This allows auto variables over location 0xFF
#use delay(clock=4000000) //clock 4Mhz frequency
#fuses XT,NoWDT // crystal osc used & no watch dog timer used
#use rs232 (baud = 1200, parity = N, xmit = PIN_c6, rcv = PIN_c7)//RS232 comm
#opt 9
#org 0x1f00, 0x1fff void loader16f877(void) {} //Bootloader program
#include "lcd.c"
// DECLARITION OF GLOBAL VARIABLES
float temp1;

main(){
int s;
lcd_init();
//lcd initilised
lcd_putc('\f');
//lcd is cleared
lcd_gotoxy(1,1);
//move cursor
lcd_putc("___Temp:");
//print this statement "___Temp:"
lcd_gotoxy(15,1);
//move cursor
lcd_putc("__");
//print this statement "__"
while(1){
s = getc();
//get the value sent from transmitter
temp1 = s * 0.4887;
// value in s is converted to actual temperature
lcd_gotoxy(9,1);
//move cursor
printf(lcd_putc, "%2.1f'C", temp2); //display temp. Rx from Tx and display on lcd
}}

You might also like