BME 367 - Manual

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

Yarmouk University

Hijjawi Faculty for Engineering Technology


Department of Biomedical Systems and Informatics Engineering

_________________________________________
BME 367

Programmable Circuits &


Microcontrollers Lab.
_________________________________________
Eng. Ayat Al-nemrawi

Eng. Shefa M.Tawalbeh


Table of Content

Experiment page

Table of Content
1

Introduction to Logic Gates and universal gates – AND, OR, NOT, NOR, NAND, XOR
2

Binary Addition, Binary Subtraction, Flip Flops and 4 Bit Binary Counter
9

Shift Register, 8 to 3 line Encoder, 3 to 8 line Decoder and Multiplexer and De-
21
multiplexer Circuits

Introduction to programming the Microchip PIC Microcontroller using CCS C Compiler


27
and PROTEUS Simulation

Analog to digital convertor (ADC) in PIC16f877a and interfacing Liquid crystal Display
39
LCD to PIC 16f877a

Interrupts and serial interface using PIC 16f877a 47

Pulse width modulation (PWM) in PIC16F877A 59

1
Exp 1: Introduction to Logic Gates and Universal Gates – AND, OR,
NOT, NOR, NAND, XOR

  Objective
- To study and investigate AND, OR, NOT, NAND and NOT gate
operation.
- To study some fundamental laws of Boolean algebra.
- To become familiar with Universal Gates and implement basic gates
using universal gates.

 Introduction
Logic gates are the building blocks of digital circuits. Combinations of logic
gates form circuits designed with specific tasks in mind. For example, logic
gates are combined to form circuits to add binary numbers (adders), set and
reset bits of memory (flip flops), multiplex multiple inputs, etc.
Keep in mind that computers work on an electrical flow where a high voltage
is considered a 1 and a low voltage is considered a 0. Using these highs and
lows, data are represented. Electronic circuits must be designed to manipulate
these positive and negative pulses into meaningful logic. [1]

a) Basic Logic Gates:


a) AND gate
AND gate requires two inputs and has one output. AND gate only produces an
output of 1 when BOTH the inputs are a 1, otherwise the output is 0.

Truth
AND Gate
Table
Input Output
A B Y
0 0 0
0 1 0
1 0 0
A.B=Y 1 1 1
Figure 1: AND gate

b) OR gate
OR gate has two input lines and one output line. Basically, if either or both of
the inputs are a 1, the resulting output value is a 1. Note in the truth table, the
only time the output is 0 is when both inputs are 0.

2
OR Gate Truth Table
Input Output
A B Y
0 0 0
0 1 1
1 0 1
A+B=Y 1 1 1
Figure 2: OR gate

c) NOT gate
NOT gate is also known as an inverter, simply because it changes the input to
its opposite (inverts it). NOT gate accepts only one input and the output is the
opposite of the input. In other words, a low-voltage input (0) is converted to a
high-voltage output (1).

NOT Gate Truth Table


Input Output
A out
0 1
1 0
A'=out
Figure 3: NOT gate

A common way of using the NOT gate is to simply attach the circle to the
front of another gate. This simplifies the circuit drawing and simply says:
"Invert the output from this gate." Note the addition of the circle to the front of
the gate. This simply means "invert the output."

Example 1:

For NAND gate shown below fill the truth table:

AND Gate Truth Table


3
Input Output
A B Q
0 0
0 1
1 0

(A.B)'=Q 1 1

NAND and NOR gates are called universal functions since with either one
the AND and OR functions and NOT can be generated.

Example 2:

For NOR gate shown below fill the truth table

Truth
NOR Gate
Table
Input Output
A B Y
0 0
0 1
1 0
1 1
(A+B)'=Y
Figure 4: NOR gate

d) XOR gate
X in the XOR gate stands for "exclusive." This means that the output from this
gate will be a 1 ONLY when one or the other of the inputs is a 1. Notice in the
truth table that the output is a 0 if both the inputs are 1 or 0. In other words,
this is an either-or gate.
A⊕B = A.B'+A'.B

XOR Gate Truth Table


Input Output
A B Y
0 0 0
0 1 1
1 0 1

4
A B=Y 1 1
⊕ 0
Figure 5: XOR gate

Example 3:

For XNOR (AΘB) gate shown below fill the truth table

Truth
XNOR Gate
Table
Input Output
A B Y
0 0
0 1
1 0
1 1

(A⊕ B)'=Y Figure 6: XNOR gate

e) Laws of Boolean Algebra

 Commutative Law
A+B=B+A
AB=BA

 Associate Law
(A + B) + C = A + (B + C)
(A B) C = A (B C)

 Distributive Law
A (B + C) = A B + A C
A + (B C) = (A + B) (A + C)

 Identity Law
A+A=A
AA=A

5
 Redundance Law
A+AB=A
A (A + B) = A
0+A=A
0A=0
1+A=1
1A=A

 Demorgan’s Theory





Example 4:

Proof that:

(A⊕B)' = (AΘB)

The most important logic theorem for digital electronics, this theorem says
that any logical binary expression remains unchanged if we:
1. Change all variables to their complements.
2. Change all AND operations to ORs.
3. Change all OR operations to ANDs.
4. Take the complement of the entire expression.

A practical operational way to look at DeMorgan's Theorem is that the


inversion bar of an expression may be broken at any point and the operation at
that point replaced by its opposite (i.e., AND replaced by OR or vice versa).

e) Realization of Basic Gates using Universal Gates


Universal gates are the ones which can be used for implementing any gate like
AND, OR and NOT, or any combination of these basic gates; NAND and
NOR gates are universal gates.

6
 Theory
Any logic function can be implemented using NAND gates. To achieve this,
first the logic function has to be written in Sum of Product (SOP) form. Once
logic function is converted to SOP, then is very easy to implement using
NAND gate. In other words any logic circuit with AND gates in first level and
OR gates in second level can be converted into a NAND-NAND gate circuit.

Any logic function can be implemented neither using NOR gates. To achieve
this, first the logic function has to be written in Product of Sum (POS) form.
Once it is converted to POS, then it's very easy to neither implement using
NOR gate. In other words any logic circuit with OR gates in first level and
AND gates in second level can be converted into a NOR-NOR gate circuit.

 NOT – Using NAND

 AND – Using NAND

 OR – Using NAND

 NOT – Using NOR

7
 OR – Using NOR

 AND – Using NOR

 Procedure:
For modules: Logic Gates (DB01), Universal Gate- NAND/NOR (DB02), EX-
OR Gate Implementation (DB03), Demorgan's Theorem (DB04)

1. Connect +5 V and ground


2. Connect the inputs of the modules to the 8 bits data switches.
3. Switch on the Scientech Digital Lab ST2611.
4. Observe output of Gate on 8 bits LED display.
5. Verify Truth Table for different input combination.

8
Exp 2: Binary Addition Binary Subtraction, Flip Flops and 4 Bit Binary Counter

  Objective
- To study operation of adders, binary subtraction and 4 Bit Binary
Counter.
- To become familiar different types of flip flops.

1- Binary Addition
A half adder has two inputs for the two bits to be added and two outputs one
from the sum ‘ S’ and other from the carry ‘ c’ into the higher adder position.
- 2 Bit Binary Half Adder

Figure 1: 2 Bit Binary Half Adder

X Y S C

0 0

0 1

1 0

1 1

- 3 Bit Binary full Adder

Figure 2: 3 Bit Binary full Adder

9
X Y Z Cf Sf

0 0 0

0 0 1

0 1 0

0 1 1

1 0 0

1 0 1

1 1 0

1 1 1

- 2 Bit Binary Parallel Adder

Figure 3: 2 Bit Binary Parallel Adder

Y0 X0 Y1 X1 C0 S1 S0

0 0 0 0

0 1 0 1

10
0 1 1 1

1 0 1 1

2- 2 Bit Binary Subtractor (Half Subtractor)


The half Subtractor is constructed using X-OR and AND Gate. The half
Subtractor has two input and two outputs. The outputs are difference and
borrow. The difference can be applied using X-OR Gate, borrow output can be
implemented using an AND Gate and an inverter .

Figure 4: 2 Bit Binary Subtractor (Half Subtractor)

- Verify Truth Table for different input combination:

X Y B D

0 0

0 1

1 0

1 1

 Procedure:
For module (DB08):
1. Connect +5 V and ground to their indicated position on DB08 from
external DC
2. Power Supply or from DC power block of Digital Lab ST -2611.
3. Switch on the Power Supply.
4. Connect inputs X, Y as per Truth Table to 2 bit binary Half Adder.
5. Observe output Sh, Ch on multimeter or on LED display of Digital Lab
ST2611 and prove Truth Table.
6. Switch Off the Power Supply.

11
7. Connect output Sh, CH of 2 bit binary Half Adder to input Sh, Ch of 3 bit
binary Full Adder.
8. Connect input X, Y, Z to 3 bit binary Full Adder as per Truth Table
shown.
9. Observe output Sf, Cf on multimeter or on LED display of Digital Lab
ST2611 and prove Truth Table.
10. Repeat above steps and prove Truth Table for 2 bit binary parallel Adder
and 2 bit binary Half Subtractor.

3- Flip Flops

a- RS Flip Flops
RS flip-flop is also called Synchronous flip-flop. That means that this flip-flop
is concerned with time. Digital circuits can have a concept of
time using a clock signal. The clock signal simply goes from low-to-high and
high-to-low in a short period of time.

Figure 5: RS Flip Flop

 Procedure:
For module (DB11):
1. Connect +5V and ground to their indicated position on DB11 experiment
board from external DC power supply or from DC power block of Digital Lab
ST2611.
2. Switch on the power supply.
3. Connect inputs 0, 0, 0 to S, R, CP pins of R-S flip-flop.
4. Measure output Q (Present state).
5. Connect input 1 to CP.
6. Measure output Q. It is next state Q (t + l) for input 0, 0.
7. Repeat above steps for remaining inputs. (Before transition of clock pulse
from
8. 0 to 1, output is present state and after transition output is next state)
9. Verify Truth Table for different input combination:

12
Present state Input 1 Input 2 Next state

Q S R Q(t+1)

0 0 0

0 0 1

0 1 0

0 1 1

1 0 0

1 0 1

1 1 0

1 1 1

b- J-K Flip-Flop
The JK flip- flop is another modification of the RS flip-flop which has its own
way of dealing with the RS flip-flop’s undesirable input combination
(when S= 1 and R= 1). The JK flip-flop has 2 inputs J and K, each ANDed
with the clock pulse and it's corresponding NOR output. The schematic for the
JK flip- flop is shown below.

Figure 6: J-K Flip Flop

 Procedure:
For module (DB11):
1. Connect +5V and ground to their indicated position on DB11 experiment
board from external DC power supply or from DC power block of Digital Lab
ST2611.
2. Switch on the power supply.

13
3. Connect 1, 0 to pins SD and CD of JK flip-flop to clear the Output Q.
4. Connect inputs as per Truth Table of JK Flip Flop and prove it.
5. Connect input 1, 1 to J, K pins of JK flip-flop and 1, 1 to SD, CD.
6. Connect a TIL clock pulse of 2 KHz to CP input.
7. Observe output Q on Oscilloscope. It will be 1 KHz.
8. Verify Truth Table for different input combination:

Present state Input 1 Input 2 Next state

Q J K Q(t+1)

0 0 0

0 0 1

0 1 0

0 1 1

1 0 0

1 0 1

1 1 0

1 1 1

c- T Flip-flop
The toggle, or T, flip-flop is a bi-stable device that changes state on command
from a common input terminal.

Figure 7: T Flip Flop

14
 Procedure:
For module (DB11):
1. Connect +5V and ground to their indicated position on DB11 experiment
board from external DC power supply or from DC power block of Digital Lab
ST2611.
2. Switch on the power supply.
3. Connect a TIL clock pulse of 2 KHz to CP input.
4. Observe output Q on Oscilloscope. It will be 1 KHz.
5. Verify Truth Table for different input combination:

Present state Input Next state

Q T Q(t+1)

0 0

0 1

1 0

1 1

d- D Flip-flop
The D flip-flop is widely used. It is also known as a data or delay flip-flop

Figure 8: D Flip Flop

 Procedure:
For module (DB11):

15
1. Connect +5V and ground to their indicated position on DB11 experiment
board from external DC power supply or from DC power block of Digital Lab
ST2611.
2. Switch on the power supply.
3. Connect 1, 0 to pins SD and CD of D flip-flop to clear the output Q.
4. Connect 1, 1 to pins SD and CD of D flip-flop.
5. Connect inputs as per Truth Table for D flip-flop and prove Truth Table.
6. Connect output Q to Input D of D Flip-flop.
7. Connect a TIL clock pulse of 2 KHz to CP input.
8. Observe output Q on Osci1loscope. It win be 1 KHz.
9. Verify Truth Table for different input combination:

Present state Input Next state

Q D Q(t+1)

0 0

0 1

1 0

1 1

Note that:
- Indeterminate state of RS flip-flop is determined in JK flip-flop.
- Toggle state in JK flip-flop is eliminated in master slave flip-flop.

4- 4 Bit Synchronous Binary Up Counter


Counter (Up-Counter) Synchronous counting operation is provided by having
all flip-flops clocked simultaneously so that the outputs change coincidentally
with each other when instructed by the steering logic.

16
Figure 9: 4 Bit Synchronous Binary up Counter

 Procedure:
For module (DB13):
1. Connect +5 V and ground to their indicated position on DB13 experiment
board from external DC power supply or from DC power block of Digital Lab
ST2611.
2. Switch ‘On’ the power supply.
3. Connect logic 1(+5 V) to CP and MS input.
4. Clear the outputs Q0-Q3 by Connecting logic 0 (Gnd or 0V) to MCD input of
4 bit synchronous counter of figure 1 as per truth table.
5. Observe output on multimeter or on LED display of Digital Lab ST2611. It
will be 0 0 0 0.
6. Connect logic 1 to MCD and MS inputs.
7. Connect logic 1 to MCD input.
8. Observe output on multimeter or on LED display of Digital Lab ST2611. It
will be 0 0 0 0.
9. Connect logic 0 to CP input.
10. Observe output on multimeter or on LED display of Digital Lab ST2611. It
will be 0 0 0 1.
11. Make CP terminal to transit from 1 to 0 (10) and observe next state of
counter as shown in truth table for counter and prove truth table.
12. Repeat step 10 until last state 1111 appear.

17
S.no Ms MCd CP Q3 Q2 Q1 Q0

0 1 0 1

1 1 1 10

2 1 1 10

3 1 1 10

4 1 1 10

5 1 1 10

6 1 1 10

7 1 1 10

8 1 1 10

9 1 1 10

10 1 1 10

11 1 1 10

12 1 1 10

13 1 1 10

14 1 1 10

15 1 1 10

- Q0 is LSB

18
5- 4 Bit Binary Ripple Counter (Up-Down Counter)

Figure 10: 4 Bit Binary Ripple Counter (Up-Down Counter)

 Procedure:
For module (DB14):
1. Connect +5 V and ground to their indicated position on DB14 experiment
board from external DC power supply or from DC power block of Digital Lab
ST2611.
2. Switch ON the power supply.

UP Counter

1. Connect normal output of flip-flop to Cp input of next flip-flop.


2. Connect logic 1 to Cp and SD input.
3. Clear the outputs Q0-Q3 by connecting logic 0 to CD input.
4. Observe output on LED display of Digital Lab ST2611. It will be 0 0 0 0.
5. Connect logic 1 to MCD and MS inputs.
6. Give logic 1 to 0 transition (+5 V to Gnd.) to Cp input.
7. Observe output on LED display of Digital Lab ST2611. It will be 0 0 0 1.
8. Repeat step 6 and observe output and write the truth table.

Down Counter

1. Connect complement output of flip-flop to Cp input of next flip-flop.


2. Connect logic 1 to Cp and SD input.
3. Set the outputs Q0-Q3 by connecting logic 0 to SD input.
4. Observe output on LED display of Digital Lab ST2611. It will be 1 1 1 1.
5. Connect logic 1 to CD and SD inputs.
6. Give logic 1 to 0 transition (+5 V to Gnd.) to Cp input.
7. Observe output on LED display of Digital Lab ST2611. It will be 1 1 1 0.
8. Repeat step 7 and observe output and write the truth table.

19
Q to Q0
No. SD CD Cp Q3 Q2 Q1
Cp
0 short 1 0 1
1 
1 Short 1 1
0
1 1 
2 Short 1
0
1 1 
3 Short 1
0
1 1 
4 Short 1
0
1 1 
5 Short 1
0
1 1 
6 Short 1
0
1 1 
7 short 1
0
1 1 
8 short 1
0
1 1 
9 Short 1
0
1 1 
10 Short 1
0
1 1 
11 Short 1
0
1 1 
12 Short 1
0
1 1 
13 Short 1
0
1 1 
14 short 1
0
1 1 
15 short 1
0

- Q0 is LSB

20
Exp 3: Shift Register, 8 to 3 line Encoder, 3 to 8 line Decoder and Multiplexer
and De-multiplexer Circuits

  Objective
- To study operation of Shift registers, Encoders and Decoders.
- To study operation of Multiplexer and De-multiplexer.

 4 Bit Serial in Parallel out Shift Register


For this kind of register, data bits are entered serially once the data are stored,
each bit appears on its respective output line, and all bits are available
simultaneously.

Figure 1: 4 Bit Serial in Parallel out Shift Register

 Procedure:
For module (DB12):
1. Connect +5 V and ground to their indicated position on DB12 experiment
board from external DC power supply or from DC power block of Digital
Lab ST2611.
2. Switch on the power supply.
3. Clear the outputs Q0-Q3 by connecting + 5 V (logic 1) to MC input and
ground or 0 V (logic 0) to MR input of Shift Register of figure 1 as per truth
table.
4. Observe output on multimeter or on LED display of Digital Lab ST2611. It
will be 0 0 0 0.
5. Connect logic 1 to MR input and logic 0 to MC input.
6. Connect input 1 to Shift Register as per truth table 1.
7. Connect logic 1 to MC input.
8. Observe output on multimeter or on LED display of Digital Lab ST2611. It
will be 1 0 0 0.

21
9. Repeat step 5, 6, 7 for different inputs as per truth table 1 and verify truth
table.

MR MC Input Q0 Q1 Q2 Q3

0 1 1 or 0

1 01 1

1 01 0

1 01 1

1 01 0

- Continue the truth table for Shift Register.

 8 to 3 Line Encoder
Provides three bits of binary coded output representing the position of the highest
order active input.

Figure 2: 8 to 3 Line Encoder

22
 Procedure:
For module (DB09):
1. Connect +5 V and ground.
2. Connect the inputs of the modules to the 8 bits data switches.
3. Switch on the instrument.
4. Observe output of Gate on 8 bits LED display.
5. Verify Truth Table for different input combination.

D0 D1 D2 D3 D4 D5 D6 D7 x y z

1 0 0 0 0 0 0 0

0 1 0 0 0 0 0 0

0 0 1 0 0 0 0 0

0 0 0 1 0 0 0 0

0 0 0 0 1 0 0 0

0 0 0 0 0 1 0 0

0 0 0 0 0 0 1 0

0 0 0 0 0 0 0 1

 3 to 8 Line Decoder
It decodes the number represented by a stream of binary digits. The 3-to-8 line
decoder is so named because it takes three input signals and converts them
into the correct output signal, choosing from the eight possible values.

23
Figure 3: 3 to 8 Line Decoder

- Verify Truth Table for different input combination:

x y z D0 D1 D2 D3 D4 D5 D6 D7

0 0 0

0 0 1

0 1 0

0 1 1

1 0 0

1 0 1

1 1 0

1 1 1

24
 4 To 1 line Multiplexer
Selects one of four analog or digital input signals and forwards the selected
input into a single line.

Figure 4: 4 to 1 line Multiplexer

 Procedure:
For module (DB10):
1. Connect +5 V and ground.
2. Make connections as shown in figure.
3. Apply inputs 1 or 0 to input lines 11, 12, 13, 14.
4. Connect 0 to selection lines A and B as shown in Truth Table.
5. Switch on the instrument.
6. Observe output of Gate on 8 bits LED display.
7. Verify Truth Table for different input combination.

D0 D1 D2 D3 S0 S1 Z

1 0 1 0 0 0

1 0 1 0 0 1

1 0 1 1 1 0

1 0 1 0 1 1

25
 1 To 4 Line De-multiplexer
Taking a single input signal and selecting one of 4 data-output-lines, which are
connected to the single input.

Figure 5: 1 to 4 Line De-multiplexer

- Verify Truth Table for different input combination:

Input Selection Selection Output Output Output Output


D line S0 line S1 line D0 line D1 line D2 line D3

0 0 0

0 0 1

0 1 0

0 1 1

26
Exp 4: Introduction to programming the Microchip PIC in CCS C Compiler and
PROTEUS Simulation

  Objective
- To be familiar with the software used in the laboratory which are PIC C
Compiler and PROTEUS
- To be familiar with PIC 16f8771a pin connection.
- How to create a new project using PIC C, naming the file, choosing the
PIC device, choosing Oscillator type and frequency, writing a simple
program and Compiling the program to create the Hex file.
- Simulating your program using PROTEUS

 Introduction
 PIC Microcontroller:
Microcontroller is a relatively low cost single chip Microcomputer, This
Indicates that the complete Microcomputer system lays within the confines of
the integrated circuit chip. Microcontrollers are capable of storing and running
the program that was written, compiled and downloaded onto it. The
microcontroller's ability to store and run unique programs makes it fairly
flexible. For example, one can program a microcontroller to perform functions
based on predetermined situations (I/O-line logic) and selections. The
microcontroller's capability to carry out mathematical and logic functions
allows it to imitate complicated logic and electronic circuits. Other programs
can make the microcontroller behave like a neural circuit or a fuzzy logic
controller.

- Main parts of a microcontroller


Central Processing Unit (CPU), Random Access Memory (RAM), Read Only
Memory (ROM), input/output lines (I/O lines), serial and parallel ports, timers
and other peripherals such as an analog to digital (A/D) converter and a digital
to analog (D/A) converter.

27
Figure 1: PIC 16f877a

  Input /output pins (I/O):


A connection pin can be configured as input or output; it can be digital, analog
and special functions. It is used to communicate, control, read information and
show the output of the microcontroller.

  Simulator
A software environment that has its own built-in functions allows access to
some of the internal operation of the microcontroller. By this way you can test
and try your code and design and check if the expected results will be valid
after built your design. One of simulator that allows professional engineers to
run interactive simulations of real designs is PROTEUS VSM.

  Software and programming languages
The main information that allows the microcontroller to run, these information
could be written in a programming languages specified to do this job; i.e. C,
 Pascal or Assembler.
Your code (Source file, .c format) will be written then it may be processed
(compiled) before the microcontroller can understand it (Object File, .hex
format).


Example 1:
In order to program a microcontroller that used to calculate the impedance as a function of voltage and current ( = ), you may need:
1- Tow input for voltage and current.

28
2- A program that carry out mathematical operation; division.
3- One output for impedance.

Figure 2: Example 1

 C programming Standards

- Variables

o Name: make them fit their function according to the following rules:
Every variable name in C must start with a letter; the rest of the name
can consist of letters, numbers and underscore characters. You cannot use
any of C's keywords like main, while, switch etc as variable names.
o Type: table 1 shows some of C data type.

Type Explanation
Int1 or short Defines a 1 bit number
Int8 or int Defines an 8 bit number
Long or int16 Defines a 16 bit number
int32 Defines a 32 bit number
Float Defines a 32 bit floating point
number
Char Defines a 8 bit character
Void Indicates no specific type
Table 1: C data type

Syntax:

int a;
float b=6.1;

- Braces : can be used in a traditional way in C programming;

If (expression)
{ -- statement --
---------------- }

29
- Semicolon operator: each C statement must end with semicolon operator (;).
- Comment: To add a comment just use (//) to comment one line, in order to
comment a paragraph you must use (/*) before the paragraph and (*/) at the
end of it.
- If statement: if statement controls conditional branching. The body of an if
statement is executed if the value of the expression is nonzero. The syntax for
the if statement has two forms :

If (expression)
{Statement}

if (expression)
{Statement}
else
{Statement}

- Condition Format and operators: see table 2.

Operator Syntax
Equal to a ==b
Not equal to a != b
Greater than a>b
Less than a<b
Greater than or equal to a >= b
Less than or equal to a <= b
Logical and a&b
Logical OR a|b
Bitwise logical and a && b
Bitwise logical OR a || b
Table 2: Condition Format and operators

 The Structure of C Program

- Hardware Compatibility:
o Include device: to includes the text of an external file into a program. Thus to
include PIC 16f877a you must include it in your code, this to tell your code
about what you talk about as the pin names for example.
o Set fuses: the high speed oscillator (crystal) and no watch dog timer.
o Set delay use function: to tell the compiler what the oscillator speed is. The
speed is constant 1-100 MHz it is the same speed of the crystal used in
hardware connection.

30
# include < 16f877a.h >
# fuses xt, nowdt
# use delay (clock = 4000000)

Note: your code must start with these three lines.

- Define your global variables according to the variable name and types rules.
Note: it is preferred to define your variables as global when you do a
hardware connection.

- Main: to write your code within it.

# include < 16f877a.h >


# fuses xt, nowdt
# use delay (clock = 4000000)
int x;
int y;
void main ()
{
Z=x/y;
}

 Port programming
Every port consists of 8 pins, you can use all port at once or use separately:
- Port interface: Decide port as input or output, Output a value on the port, Read
a value from the port.
- Pin interface: Decide pin as input or output, Output high, Output low.
- Parallel port commands: First of all you must know that there is (at most)10
ports in PIC microcontroller that may be used as parallel input or output, they
are A,B,C,D,E,F,G,H,I and K.

 Input and output programming mode

- To set a port as input or output use:


set_tris_port name(data); thus :
o Port name: represents the port that you want to set as input or output. o
Data: an 8 bit integer with each bit representing a bit of the I/O port.
Data value shown in table 3.

data description
0x00 set the port as output
0xff set the port as input
0xf0 set half of them output (pin 0-3) and the others input (pin 4-7 )
0x0f set half of them input (pin 0-3) and the others output (pin 4-7 )
1 set the port as input
0 set the port as output
Table 3: set tris data value

31
- Output high or low directly to the pin using:
output_high(pin name)

- Take Input directly from a port or pin using


Input

- Output data directly to a port


output_port name(data)

set_tris_a(1); // set port a as input


set_tris_b(0); // set port b as output
Output_high(pin_a0); // output high at pin a0
Output_low(pin_c2); // output low at pin c2
X=input_a(); // take input from port a and save it in a variable
Y=input(pin_b0); (); // take input pin b0 and save it in a variable

Note: you take input directly from the port if and only if it is a digital input
else you must use analog to digital converter

 Proteus Schematic Design and Simulation (ISIS)

A range of simulator models for popular micro-controllers and a set of animated


models for related peripheral devices such as LED and LCD displays, keypads, an
RS232 terminal and more. It is possible to simulate complete micro-controller
systems and thus to develop the software for them without access to a physical
prototype.

32
Figure 3: Proteus graphical interface

 Selecting Components

- To select the components, click on Library Pick Device/Symbol or just


press “P”.
- To find the component just writ the keyword on the search tab. Table 4 shows
some of commonly used keyword in “Pick Devices” Window.

Parts Keywords in “Pick Devices”


Window
PIC 16 microcontroller 16f877a
capacitor CAP
resistor RESISTOR
quartz crystal CRY
animated led model LED-BLUE
switch SW-SPST
push button BUTTON
16×2 alphanumeric LCD LM016L

Table 4: commonly used keyword in “Pick Devices” Window

- The selected component can be located on the left side window of the design
diagram. To put the component to the design sheet, drag it to the sheet.
- To move the components, simply right click on the component (the
component will be red-lighted), and left click and drag the component to the
desired location.
- For power terminal and ground, the component is NOT selected from the
library. To add it just Select the "Terminals mode" icon at the left-side toolbar.

Figure 4: Terminal mode icon.

- To add virtual terminal or oscilloscope the component is NOT selected from


the library. To add it just Select the "Virtual terminal mode" icon at the left-
side toolbar.

33
Figure 5: Virtual terminal mode icon.

Note: Be sure that you chose the device component not the simple.

 Component Parameter Settings

Each component need to be set according to the specifications. For example the
resistor or capacitor value need to define before any simulation can be done.

- To edit the component (change its value or name), right-click in the device
then chose edit component dialog (or just double click in the component). The
dialog box is different according to the devices.

Note: be sure that no two components have the same name.

 PIC16F877a Parameter Settings

The most important part of Proteus simulation is setting up the microcontroller. The
configuration needs to be correct to cross out any setting error in time for program
simulation. To edit the parameter for PIC right-click in the PIC then chose edit
component dialog (or just double click in the component)

34
Figure 6: PIC 16f877a edit component dialog box.

- Program file: file location that contains the program you want to upload it in
the PIC. Click the folder icon, select the directory where you compiled your
source code then select the corresponding hex file.
- Processor clock frequency: The oscillator frequency (crystal frequency) that
you used in your code.

 Simulation

After completing the circuit assembly and configuration, now it's time to verify
whether the source code compiled is virtually accurate or not. This is where the fun
comes. Proteus offer a whole lot of variety virtual devices. In fact, simulation using
oscilloscope and function generator can be done using Proteus. Even virtual
HyperTerminal is provided to demonstrate how your code performs in real world
without really doing the hardware section yet.
- To start simulation presses the play button at the bottom toolbar. To stop the
simulation, press the stop button or press ESC.

Figure 7: play and stop button at the bottom toolbar.

 Creating Bill of Material (BOM) Files

Bill of materials (BOM) the term used to describe the "parts list" of components
needed to complete a saleable end-item. It generates a list of components needed to
assemble the project (as report about your design). The file can be outputted in HTML
or ASCII files.

35
- To create it click on tool Bill of martial  ASCII output

Example2:

- Write a PIC C code to turn 4 LED on once the user hits 4 switches using PIC
16f877a.
- Try your code with proteus.

I- PICC code:

- You are to use PIC 16f877a with 4 input pins (say A0, A1, A2 and A3) and 4
output pins (say B0,B1,B2,and B3).
- Using switches means that the input may be high or low only (digital input).
- To turn the led on just output high to the pin that you want to

# include < 16f877a.h >


# fuses xt, nowdt // xt :to use the crystal
# use delay (clock = 4000000) // The frequency of the crystal
/* define 4 global variable to use them later to store the input
Value */
int x0;
int x1;
int x2;
int x3;
void main ()
{
set_tris_a(1); // define port A as input
set_tris_b(0); // define port C as output
// for the first input

while(1) // while true to ensure a continuous running for the code


{
x0=input(pin_a0); // read a0 pin value and store it in x0 variable
if(x0){output_high(pin_b0);} // if the switch on (the input high)
else {output_low(pin_b0);}
}}

Continue writing the code for the other 3 input

II- Proteus simulation


Every IC has its own pin connection that included in the data sheet if IC from
its manufacturer. The pin connection for PIC 16f877a shown in figure 1. That:

- Pin-1: connect to the power (connect a resistor in series with the power to
prevent short circuit).
- Pin-12 and pin 13: connect to the terminal of the crystal.
- Crystal used with a frequency same as that mentioned in PICC code.
- Crystal with 4MHz frequency terminals connects to tow capacitor value
ranges 15-68 pF (commonly 22 pF).
- Edit the PIC (upload hex file and change the frequency of the PIC).

36
Figure 8: crystal and power connection to the PIC.

- Connect to the input (port A) 4 switches select between two states high
(power) and low (ground).
- And the output (port b) to 4 LEDs (connect a resistor in series with the power
to prevent short circuit).

37
Figure 9: Example 2 circuit diagram.

Continue connecting to the 3 other inputs

38
Exp 5: ADC and LCD using PIC 16f877a as controller

  Objective
- Understand the principles of Analog Digital Conversion (ADC) in
Microcontrollers.
- How to use the ADC in PIC16F877A .
- Interface PIC 16f877a to LCD

 Introduction

In almost in all digital systems, there is a frequent need to convert analog


signals generated by peripheral devices such as continuous voltage or current
into digital values that can be stored and processed. There are various types of
analog to digital converters: high speed ones, precisions, and economical ones
and so on. Most of them can be directly connected to any processor as shown
in the figure (1).

Figure 1: ADC connected directly to the processor

From the Processor-ADC interface shown in the figure (1), we conclude that
an activation signal is required to be generated by the processor to prompt the
ADC to start conversion. When the ADC finishes conversion, it should
generate a "Conversion Complete" signal to tell the processor that is the
conversion is done. This signal can interrupt the processor or be polled by the
processor.

39
 Resolution

The resolution of the converter indicates the number of discrete values it can
produce over the range of analog values. The values are usually stored
electronically in binary form, so the resolution is usually expressed in bits.
Inconsequence, the number of discrete values available, or "levels", is usually
a power of two. For example, an ADC with a resolution of 10 bits can encode
an analog input to one in 1024 different levels, since 210 = 1024. The values
can represent the ranges from 0 to 1023 (i.e. unsigned integer) or from -512 to
511 (i.e. signed integer), depending on the application.
Resolution can also be defined electrically, and expressed in volts. The voltage
resolution of an ADC is equal to its overall voltage measurement range
divided by the number of discrete intervals as in the formula:
= −
2

Where:
- Q: is resolution in volts per step (volts per output code)
- Vrh: High voltage reference.
- Vrl: Low voltage reference.
- N: number of bits.

 ADC Module in Microcontroller PIC16F877A

The Microcontroller PIC16F877A has a built in ADC Module with 8 input


pins, and we can access this module from ADCON1 Register, as follow:

Figure 2: ADCON1 Register

To working with the built in ADC Module in microcontroller:

- Setup ADC ports: to configure one or more of pins that used as built in
ADC of the PIC to start work as ADC use:
setup_adc_ports(port name);

Where port name is the ADC channel; see table1.

40
ADC channel Corresponding PIN
AN0 PIN2 : A0
AN1 PIN3: A1
AN2 PIN4: A2
AN3 PIN5: A3
AN4 PIN7: A5
AN5 PIN8: E0
AN6 PIN9: E1
AN7 PIN10: E2
Table 1: PIC 16f877a ADC channel

You can setup multiple channel even though all ADC channel at the same
time. The used channel follow a certain criteria ; if you want to configure
three ADC channel you can't use A0, A1, A2 instead use A0, A1, A3 (see
analog PIC wizard).

setup_adc_ports(AN0); // setup A0
setup_adc_ports(AN0_AN1_AN3); //setup A0, A1, A3
setup_adc_ports(ALL_ANALOG); //setup all valid ADC channel

- Setup ADC clock : to configure the clock for ADC use :

setup_adc(ADC_CLOCK_mode);

mode Explanation
INTERNAL Crystal clock
DIV_2 Crystal clock divided by 2
DIV_8 Crystal clock divided by 8
DIV_32 Crystal clock divided by 32

Table 2: ADC clock mode

- Set ADC channel : to set which ADC channel do you want to read use:

set_adc_channel(channel ID);

Where channel ID is the channel number; for AN3 ID = 3.

- Read ADC channel: to read the analog value of the selected channel
previously as digital use:
x = read_adc();

It recommended taking delay for awhile after selecting the channel.

41
setup_adc_ports(ALL_ANALOG); //setup all valid ADC channel
setup_adc(ADC_CLOCK_INTERNAL) // setup ADC clock
set_adc_channel(0); // select the channel
delay_ms(100 ); // delay for a while
x = read_adc(); //read ADC channel

 LCD
LCDs (liquid crystal display) are widely used devices that come in different
forms that differ in size and shapes and many other features. However almost
all LCDs conform to a standard interface specification. In our lab we will
consider LM016L LCD with size 2×16 (32 characters) that shown in
Figure(3).

Figure 3: LM016L LCD

- Pin configuration: listed in table (3).

Pin Symbol I/O Description


1 VSS -- Ground
2 VCC -- +5 V power supply
3 VEE -- Power supply to control contrast
4 RS I RS=0 to select command register
RS=1 to select data register
5 R/W I R/W=0 for write
R/W=1 for read
6 E I/O Enable
7 DB0 I/O 8 bit data bus
8 DB1 I/O 8 bit data bus
9 DB2 I/O 8 bit data bus
10 DB3 I/O 8 bit data bus
11 DB4 I/O 8 bit data bus
12 DB5 I/O 8 bit data bus
13 DB6 I/O 8 bit data bus
14 DB7 I/O 8 bit data bus

Table 3: LM016L pin configuration

42
- Interface PIC 16f877a to LCD: listed in table (4).

PIC 16f877a pin LCD


pin
D0 E
D1 RS
D2 RW
D4 D4
D5 D5
D6 D6
D7 D7

Table 4: Interface PIC 16f877a to LCD

- Include LCD in CCS code: to include LCD use :


#include<lcd.c>

- Initialize LCD: LCD display will not work properly unless you initialize it.
To initialize LCD use:
lcd_init();
lcd_init() Must be called before any other function.
- Define the position where you want to write on it: LCD character position
looks like a matrix with a size of LCD size. To define the position use :
lcd_gotoxy(x,y);
Where x, y is the position where you want to print at it. If you want to
write in the most upper left of the display use (x,y) = (1,1)
- Print to LCD: to print the data to LCD display use :
printf(lcd_putc,"text % format",argument_list);
Where:
o Lcd_putc: write to the position specified previously using
lcd_gotoxy.
o Text: any combination of letters, numbers and symbols can be
used o Argument list: can be composed of constants and variables.
o Format: data format that you want to display.
- Format: depending on the type of data being displayed.

Format Description
%c single character
%d signed decimal integer
%f floating point (decimal notation must include)
%e floating point (exponential or scientific
notation)
%u unsigned decimal integer
%x unsigned hexadecimal integer (lower case)
%X unsigned hexadecimal integer (upper case)
l prefix used with %d, %u, %x to specify long

43
integer
Table 5: Interface PIC 16f877a to LCD
The format specification can also be shown as:
%[ width].[ precision]
So to print a variable (V) with width 4 and precision 3 (number of decimal
point) and volt unit:
printf(lcd_putc,“V = %4.3f volt”,V);

A 0 (zero) following a % character within a format string forces leading


zeros to be printed out. The number following specifies the width of the
printed field. Thus:
printf(lcd_putc “The Hex of decimal 10 is %02x”, a);

This would be print out as:


The Hex of decimal 10 is 0a

- Escape Sequences used to manage the display are listed in table (6)

Escape Description Escape Description


horizontal
\n Newline \t
tab
\r carriage return \f form feed
\' single quote \" double quote
\\ Backslash %% percent sign
\? question mark \b backspace
\0 null character \v vertical tab
Table 6: Escape Sequences

For print more than one variable at the same time with a single print
statement you may need to print each one at a line:
printf(lcd_putc," x = %f ",x ," y = %f\n", y);

- To clean the display use:


lcd_putc('\f')

# include < 16f877a.h >


# fuses xt, nowdt
# use delay (clock =
4000000) #include<lcd.c>
int x = 10.235;
void main ()
{
lcd_init(); // initialize LCD
lcd_gotoxy(1,2); // print position
printf(lcd_putc," the value of x = %2.3f ",x);
delay_ms(10000); // delay for 10 seconds
lcd_putc('\f');
}

44
Example 1:

- Write a CCS code to read a voltage across a variable resistor and display it
in LM016L LCD at the second row.
- Try your code with proteus.
- Measure the input voltage with DC voltmeter and compare it with the
result on LCD.

I- PICC code:

- You are to use PIC 16f877a with 1 input channel.


- Since you are dealing with analog signal, you must use ADC module of PIC
16f877a.
- You must include LCD display in your code.

# include <16f877a.h >


# fuses xt, nowdt
# use delay (clock = 4000000)
#include<lcd.c>
float voltage;
void main ()
{
setup_adc_ports(AN0);
setup_adc(ADC_CLOCK_INTERNAL);
lcd_init(); // initialize LCD
while (1)
{
set_adc_channel(0);
delay_ms(100);
voltage = read_adc();
lcd_gotoxy(1,2); // print position
printf(lcd_putc," Voltage = %1.5f ",voltage);
delay_ms(10000); // delay for 10 seconds
lcd_putc('\f');
}
}

II- Proteus simulation


- Connect the power and crystal to the PIC as we do at last lab.
- Connect the input to A0.
- Connect LCD to the PIC.

45
Figure 5: Example 1 circuit diagram.

LCD will display a result differ from the voltmeter value. You must scale
the result according to the resolution value.

Scale the result and try it with proteus

46
Exp 6: Interrupts and serial interface using PIC 16f877a

 Objective

- To be familiars to the different Interrupt sources inside the PIC16F877A
microcontroller. Understand the basics of serial interface in PIC16F877A.
- Send and receive different data using the serial port of PIC16F877A.

 Introduction
Interrupts are situations that the CPU can't predict when they will happen, they
can happen any time, so the CPU does not wait for them. So the CPU keeps on
doing its normal job unless and interrupt occurs.
It allows a microcontroller to respond to some events at the moment they
occur, regardless of what the microcontroller is doing at the time. This
provides a connection between a microcontroller and the external
environment. Generally, each interrupt changes the program flow, interrupts it
and after executing an interrupt service routine continues on from that same
interrupt point. Figure (1) illustrates this.

Figure 1: RB0 Interrupt process.

Without interrupts you would have to do loops in order to check if one or


another event occurred. This routine checking is called as polling .Polling has
disadvantages like consuming valuable microcontroller resources and time.
These resources may be used for other data processing tasks. This is why
microcontroller comes with built in interrupt support. Instead of checking
events microcontroller has ability to interrupt normal program flow on event
and jump to interrupt service subroutine (ISR).

47
 Interrupts in 16F877A 

The interrupt sources in PIC can be broadly classified into:


1. External interrupts: they provide a means for external hardware to generate
interrupts. Like if you connect a touch screen controller to your PIC then the
touch screens can be connected to INT0 (or any other (RB0/INT0). Then
whenever the pen touches the screen it will interrupt the CPU.
2. Internal interrupts: Internal interruptions are generated by certain events which
come up during the execution of a program. This type of interruptions is
managed on their totality by the hardware and it is not possible to modify
them.

- sources of interrupts in PIC16F877A


There are totally 14 sources of interrupts in PIC16F877A:
1. Timer0 overflow interrupt.
2. Timer 1 interrupts.
3. Timer 2 interrupts.
4. Capture compares interrupt ccp1.
5. Capture compares interrupt ccp2.
6. Comparator Interrupt.
7. USART Transmitter interrupts.
8. USART Receiver Interrupt.
9. Synchronous Serial Port interrupts.
10. EEPROM Write Interrupt.
11. Analog to Digital Converter interrupt.
12. Parallel slave port read write interrupt.
13. Bus collision interrupts.
14. External interrupt (RB0/INT0):
15. RB Port Change Interrupt Flag bit: This flag is set if at least one of
the RB7:RB4 pins changed state. In order to enable this interrupt,
pins RB7: RB4 must be defined as input.

 Interrupt Control Register


The interrupt control register (INTCON) records individual interrupt requests
in flag bits it also has individual and global interrupt enable bits.

Figure 1: Interrupt Control Register

48
 Global Interrupt Enable
A global interrupt enable bit, GIE (INTCON<7>) enables (if set) all unmasked
interrupts or disables (if cleared) all interrupts:

- When bit GIE is enabled, and an interrupt’s flag bit and mask bit are set,
the interrupt will vector immediately.
- Individual interrupts can be disabled through their corresponding enable
bits in various registers.
- Individual interrupt bits are set, regardless of the status of the GIE bit.

The GIE bit is cleared on RESET. The “return from interrupt” instruction,
RETFIE, exits the interrupt routine, as well as sets the GIE bit, which re
enables interrupts.

 CCS interrupts programming



- Define the interrupts sub routine
#INT_xxx

Name ()
{
………………………………
… Your code …
………………………………
}
Where xxx is the interrupts source listed in table (1).

Interrupt Description
#INT_TIMER0 Timer 0 (RTCC) overflow
#INT_TIMER1 Timer 1 overflow
#INT_TIMER2 Timer 2 overflow
#INT_CCP1 Capture or Compare on unit 1
#INT_CCP2 Capture or Compare on unit 2
#INT_COMP Comparator detect
#INT_TBE RS232 transmit buffer empty
#INT_RDA RS232 receive data available
#INT_EEPROM Write complete
#INT_AD Analog to digital conversion complete
#INT_PSP Parallel Slave Port data in
#INT_BUSCOL Bus collision
#INT_EXT External interrupt
#INT_RB Port B any change on B4-B7
Table 1: interrupts source

- Enable global interrupt:


enable_interrupts(GLOBAL);
- Enable interrupt subroutine:
enable_interrupts(INT_xxx);

49
- Another variables related to the interrupts: for external interrupts you must
the condition(edge) at which the interrupt will detect :
o To detect the change from high to low:
ext_int_edge(H_to_L);

o To detect the change from low to high:


ext_int_edge(L_to_H);

 External Interrupt
This is universal external interrupt flag bit. The external interrupt can appear
through the pin RB0 of port B, when port B set as an input.

Example 1:

- Write CCS code to turn a LED on at C0 for 1 second if the voltage at B0


changes from high to low using external interrupt.
- Try your code with PROTEUS.

I.PICC code:
- You are to use PIC 16f877a with port B as input (it is necessary to
enable external interrupts) and port C as output.
- The input changes from high to low meaning that the input is a
digital.
- To turn the led on just output high to the pin that you want to
connect the LED to.

# include < 16f877a.h >


# fuses xt, nowdt // xt :to use the crystal
# use delay (clock = 4000000) // The frequency of the crystal
// define the interrupt subroutin
#int_EXT
EXT_isr()
{
output_high (pin_c0);
delay_ms(1000);
output_low (pin_c0);
}
void main ()
{
set_tris_b(1); // define port b as input
set_tris_c(0); // define port C as output
output_c(0); //initialize port c with 0 value
enable_interrupts(GLOBAL);
enable_interrupts(INT_EXT);
ext_int_edge(H_to_L);
while(1)
{}
}

50
II. Proteus simulation
- Connect the power and crystal to the PIC as we do at previous lab.
- Connect the input to pin B0.
- Connect a LED to pin C0.

Figure 1: Example 1 circuit diagram.

 RB Port Change Interrupt Flag bit


This flag is set if at least one of the RB7:RB4 pins changed state. In order to
enable this interrupt, pins RB7: RB4 must be defined as input.

Example 2:

- Write CCS code to turn a LED on at C1:


o For 0.1 second twice if a switch at B4 closed.
o For 1 second twice if a switch at B5 closed.
Using RB interrupt.

- Try your code with PROTEUS.

I.PICC code:
- You are to use PIC 16f877a with port B as input (it is necessary to
enable RB interrupts) and port C as output.
- Using the switch meaning the input is a digital.
- To turn the led on just output high to the pin that you want to
connect the LED to.

51
# include < 16f877a.h >
# fuses xt, nowdt // xt :to use the crystal
# use delay (clock = 4000000) // The frequency of the crystal
// define the interrupt
subroutine #int_RB
RB_isr()
{
int x; // define tow variables to read the switch value
int y;
x=input(pin_B4);
y=input(pin_B5);
if(x & !y)
{
output_high(pin_c1);
delay_ms(100);
output_low(pin_c1);
delay_ms(100);
output_high(pin_c1);
delay_ms(100);
output_low(pin_c1);
}
if(!x & y)
{
output_high(pin_c1);
delay_ms(1000);
output_low(pin_c1);
delay_ms(1000);
output_high(pin_c1);
delay_ms(1000);
output_low(pin_c1);
}
if(!x & !y) { output_low(pin_c1);}
}
void main()
{
set_tris_b(0xff);
set_tris_c(0x00);
output_c(0x00);
enable_interrupts(GLOBAL);
enable_interrupts(INT_RB);
while (1){}
}

III. Proteus simulation


- Connect the power and crystal to the PIC as we do at previous lab.
- Connect the input to pin B4 and B5.
- Connect a LED to pin C1.

52
Figure 2: Example 2 circuit diagram

 Serial Interface
Serial communication is a way enables different equipments to communicate
with their outside world. It is called serial because the data bits will be sent in
a serial way over a single line. A personal computer has a serial port known as
communication port or COM Port used to connect a modem for example or
any other device, there could be more than one COM Port in a PC. Serial ports
are controlled by a special chip called UART (Universal Asynchronous
Receiver Transmitter). Different applications use different pins on the serial
port and this basically depend of the functions required. If you need to connect
your PC for example to some other device by serial port, then you have to read
instruction manual for that device to know how the pins on both sides must be
connected and the setting required.
In serial communication we are transmitting the data/information bit after bit
(only one bit goes through in a particular moment), but parallel
communication we are transmitting a number of bits at once from one
computer to the second computer.
Serial communication has some advantages over the parallel communication
one of the advantages is transmission distance, serial link can send data to a
remote device more far then parallel link. Also the cable connection of serial
link is simpler then parallel link and uses less number of wires. Serial link is
used also for Infrared communication, now many devices such as laptops &
printers can communicate via inferred link.

53
 Types of connectors
There are two sizes of connectors 9 pin and 25 pin, both they called D-Type
plug. D-Type plug could be either Mail or Female. Fig (1) shows photos for
these types. See figure (1).

Figure 1: 9 pin and 25 pin, D-Type plug connector.

- Pins Description

Function Pin Symbol 9 pin no. 25 pin no.


Receive Data (Serial data input) RD 3 2
Transmit Data (Serial data output) TD 2 3
Request to send (acknowledge to
modem that UART is ready to RTS 7 4
exchange data)
Clear to send (Modem is ready to
CTS 8 5
exchange data)
Data ready state (UART
DSR 6 6
establishes a link)
Signal ground SG 5 7
Data Carrier detect (This line is
active when modem detects a DCD 1 8
carrier
Data Terminal Ready. DTR 4 20
Ring Indicator (Becomes active
when modem detects ringing signal RI 9 22
from PSTN

Table 1: Pin description of 25 and 9 pin D-Type plug.

 Communication methods
There are two methods for serial communication, Synchronous &
Asynchronous:

- Synchronous serial communication:


In Synchronous serial communication the receiver must know when to
“read” the next bit coming from the sender, this can be achieved by sharing
a clock between sender and receiver.
In most forms of serial Synchronous communication, if there is no data
available at a given time to transmit, a fill character will be sent instead so

54
that data is always being transmitted. Synchronous communication is
usually more efficient because only data bits are transmitted between
sender and receiver; however it will be more costly because extra wiring
and control circuits are required to share a clock signal between the sender
and receiver.

- Asynchronous serial communication:


Asynchronous transmission allows data to be transmitted without the
sender having to send a clock signal to the receiver. Instead, special bits
will be added to each word in order to synchronize the sending and
receiving of the data.
When a word is given to the UART for Asynchronous transmissions, a bit
called the "Start Bit" is added to the beginning of each word that is to be
transmitted. The Start Bit is used to alert the receiver that a word of data is
about to be sent, and to force the clock in the receiver into synchronization
with the clock in the transmitter.

 Baud rate
Baud rate is a measurement of transmission speed in asynchronous
communication; it represents the number of bits that are actually being sent
over the serial link. The Baud count includes the overhead bits Start, Stop and
Parity that are generated by the sending UART and removed by the receiving
UART.

 PIC 16f877A serial connection

Serial communication is very important for micro devices. By using the serial
communication one can communicate with computers (via COM port, USB,
etc), peripheral devices or some ICs (such as EEPROM, A/D converters, etc.).
The process of serial communication can be done by low level coding. You
need to have a look at timing specification of the protocol and write a code to
meet the requirements. However, most PIC microcontrollers come with build
in serial communication protocols such as USART, I2C, and SPI. You only
need to configure it and start receiver and/or transmitter. Built in USART
module of PIC micro. The word USART is the acronym of Universal
Synchronous Asynchronous Receive Transmit. Standard PC COM port (RS-
232) uses asynchronous receiver and transmitter. In this mode there are Tx
(transmit) and Rx (receive) lines. It can transmit and receive information at the
same time from these lines.

- USART – is used for transmitting or receiving information. USART uses


(0v) and (5v) signals to represent logical level.
- RSR232 - is a transmission protocol. RSR232 uses voltages lower than (-
5v) and higher than (+5v) levels for the logical representation. The logical
representation is opposite of voltage levels.
- To configure USART module we use TXSTA, RCSTA, and SPBRG:

55
o TXSTA register: pin25 (RC6) set as transmitter in asynchronous
Slave mode.

Figure 2: TXSTA register.

o RCSTA register: pin26 (RC7) set as receiver in asynchronous


Slave mode.

Figure 3: RCSTA register.

o SPBRG register
This is the register which holds the baud rate generator value.

To working with the built in USART Module in microcontroller:


- To communicate through RS-232 port using CCS, we have to define the
port as follows:
#use rs232(baud= value, xmit=PIN_C6,rcv = PIN_C7)
Where:
o value is the baud rate value.
o xmit: the transmitter pin (C6 for pic 16f877a)
o rcv: the receiver pin (C7 for pic 16f877a)
- To output the data to the hyper terminal
The printf function is a standard library function which allows the
programmer to send printable information. The general format for a
printf(“control_string”, argument_list);

# include <16f877a.h>
# fuses xt, nowdt // xt :to use the crystal
# use delay (clock = 4000000) // The frequency of the crystal
// define RS232 port
#use rs232(baud=9600, xmit=PIN_C6,rcv=PIN_C7)
void main()
{
while (1){
printf(" Welcom to PIC 16f877a serial interface \n");
delay_ms(2000);
}}

56
Note: see LCD printf function.

Example1

- Write a CCS code to read a voltage across a variable resistor and send it
serially to the hyper terminal although turn a LED at PIN B0 on if the
reading exceed the half of the full scale value.
- Try your code with proteus.

I- PICC code:

- You are to use PIC 16f877a with 1 input channel.


- Since you are dealing with analog signal, you must use ADC module of PIC
16f877a.
- You must include RS-232 in your code.

# include <16f877a.h>
# fuses xt, nowdt // xt :to use the crystal
# use delay (clock = 4000000) // The frequency of the crystal
// define RS232 port
#use rs232(baud=9600, xmit=PIN_C6,rcv=PIN_C7)

void main()
{
setup_adc(ADC_CLOCK_INTERNAL);
setup_adc_ports(ALL_ANALOG);
set_adc_channel(0);
while (1)
{
voltage=read_adc();
delay_ms(100);
voltage=voltage*5/255;
if (voltage >= 2.5) {output_high
(PIN_B0);} else {output_low (PIN_B0);}
printf("The Voltage value =
%f\t",voltage); delay_ms(100);
}}

II- Proteus simulation


- Connect the power and crystal to the PIC as we do at last lab.
- Connect the input to A0.
- Connect virtual hyper terminal to the PIC (RXDRC6).

57
Figure 4: Example 1 circuit diagram.

Complete connecting:
- Analog input (variable resistor) to PIN A0.
- A LED to PIN B0.

58
Exp 7: Pulse width modulation (PWM)

 Objective

- To know what is pulse width modulation.
- Use capture compare PWM module in Microcontroller PIC16F877A

 Introduction

Pulse-width modulation (PWM) is a very efficient way of providing


intermediate amounts of electrical power between fully on and fully off. A
simple power switch with a typical power source provides full power only,
when switched on. PWM is a comparatively-recent technique, made practical
by modern electronic power switches. The term duty cycle describes the
proportion of on time to off time; a low duty cycle corresponds to low power,
because the power is off for most of the time. Duty cycle is expressed in
percent, 100% being fully on. PWM works well with digital controls, which,
because of their on/off nature, can easily set the needed duty cycle.

Figure1: pulse with a different width (duty cycle)


Pulse-width modulation uses a rectangular pulse wave whose pulse width
is modulated resulting in the variation of the average value of the

59
waveform. If we consider a pulse waveform f(t) with a low value ymin, a
high value ymax and a duty cycle D shown in figure 1 , the average value
of the waveform is given by:

This latter expression can be fairly simplified in many cases where ymin = 0
as:

From this, it is obvious that the average value of the signal ( ) is directly
dependent on the duty cycle D.

- Duty cycle:
The duty cycle is the percent of the period in which the signal is high (ON)
relative to the total period of the signal (low+high).

 CAPTURE/COMPARE/PWM MODULES in Microcontroller


PIC16F877A

The CCP module is a peripheral which allows the user to time and control
different events:
- Capture Mode: allows timing for the duration of an event. This circuit
gives insight into the current state of a register which constantly changes
its value. In this case, it is the timer TMR1 register.
- Compare Mode compares values contained in two registers at some point.
One of them is the timer TMR1 register. This circuit also allows the user
to trigger an external event when a predetermined amount of time has
expired.
- Pulse Width Modulation (PWM) can generate signals of varying
frequency and duty cycle.

The PIC16F887 microcontroller has two such modules - CCP1 and CCP2.
Both of them are identical in normal mode, with the exception of the
Enhanced PWM features available on CCP1 only.

60
Figure2: CCP1CON/ CCP2CON REGISTERS

The CCP1 and CCP2 modules are identical in its operation except in its
special event trigger operation. In each CCP modules, the capture,
compare and PWM modes using different timer resources. The table below
shows the different CCP modes and its timer resources.

CCP mode Timer resource


Capture Timer1
Compare Timer1
PWM Timer2
Table 1: CCP modes and its timer resources

 CCP1 in PWM mode


The figure below shows the block diagram of the CCP1 module setup in PWM
mode. In order to generate a pulse of arbitrary form on its output pin, it is
necessary to determine only two values- pulse frequency and duration.

Figure2: PWM module

61
To working with the built in CCP1 Module in microcontroller:
- Chose what do you want to use CCP1 as (capture, compare or PWM) :
setup_ccp1 (CCP_PWM)

- To set the frequency of the pulse (set timer 2):


setup_timer_2(mode, period, postscale)

The frequency of the square wave that generated given by:


=1= 1 ×4× 2 ×( + 1)

Where:
o mode : may be one of :
i. T2_DISABLED
ii. T2_DIV_BY_1
iii. T2_DIV_BY_4
iv. T2_DIV_BY_16

o Period: is an offset value between 0 and 255 before the timer


resets.
o Postscale : is a value between 0 and 16 to determine the times
before an interrupt occurs.

- To set The duty cycle:


set_pwm1_duty (Duty);
Where Duty an 8 bit number used to set the duty cycle of the pulse in the
range 0 to period.

# include <16f877a.h>
# fuses xt, nowdt // xt :to use the crystal
# use delay (clock = 4000000) // The frequency of the crystal

void main()
{
setup_ccp1 (CCP_PWM);
setup_timer_2(T2_DIV_BY_1, 255, 1);
set_pwm1_duty(x);
}

Example1

- Write a CCS code control :


o The frequency of the pulse generated by CCP1 as a switch to select
between tow values.
o The duty cycle of the pulse generated by CCP1 as potentiometer.

- Try your code with proteus.

62
I- PICC code:

- You are to use PIC 16f877a with 1 input channel for the digital input to
control the frequency.
- You are to use PIC 16f877a with 1 ADC channel for to control the duty.
# include <16f877a.h>
# fuses xt, nowdt // xt :to use the crystal
# use delay (clock = 20000000) // The frequency of the crystal
int x;
void main()
{
setup_ccp1 (CCP_PWM);
set_tris_b(0xff);
setup_adc_ports(ALL_ANALOG);
setup_adc(ADC_CLOCK_INTERNAL);
set_adc_channel(0);
while (1)
{
if(input(pin_b0)){setup_timer_2(T2_DIV_BY_1, 255, 1);}
else{setup_timer_2(T2_DIV_BY_16, 255, 1);} x =
read_adc();
set_pwm1_duty(x);
}}

II- Proteus simulation


- Connect the power and crystal to the PIC as we do at last lab.
- Connect the analog input to A0 (potentiometer) to control the duty.
- Connect the digital input to select between two cases to select the frequency
values.
- Connect oscilloscope to pin RC2-CCP1 to plot the pulse signal.

63
Figure 3: Example 1 circuit diagram.

64

You might also like