BME 367 - Manual
BME 367 - Manual
BME 367 - Manual
_________________________________________
BME 367
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
Analog to digital convertor (ADC) in PIC16f877a and interfacing Liquid crystal Display
39
LCD to PIC 16f877a
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]
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).
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:
(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:
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
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
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.
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.
OR – Using NAND
7
OR – Using NOR
Procedure:
For modules: Logic Gates (DB01), Universal Gate- NAND/NOR (DB02), EX-
OR Gate Implementation (DB03), Demorgan's Theorem (DB04)
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
X Y S C
0 0
0 1
1 0
1 1
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
Y0 X0 Y1 X1 C0 S1 S0
0 0 0 0
0 1 0 1
10
0 1 1 1
1 0 1 1
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.
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.
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:
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.
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:
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
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:
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.
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 (10) 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 10
2 1 1 10
3 1 1 10
4 1 1 10
5 1 1 10
6 1 1 10
7 1 1 10
8 1 1 10
9 1 1 10
10 1 1 10
11 1 1 10
12 1 1 10
13 1 1 10
14 1 1 10
15 1 1 10
- Q0 is LSB
18
5- 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
Down Counter
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.
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 01 1
1 01 0
1 01 1
1 01 0
8 to 3 Line Encoder
Provides three bits of binary coded output representing the position of the highest
order active input.
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
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.
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.
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.
27
Figure 1: PIC 16f877a
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;
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}
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
- 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)
- 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.
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.
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)
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
32
Figure 3: Proteus graphical interface
Selecting Components
- 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.
33
Figure 5: Virtual terminal mode icon.
Note: Be sure that you chose the device component not the simple.
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.
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.
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
- 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.
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
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.
- 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);
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(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
- Set ADC channel : to set which ADC channel do you want to read use:
set_adc_channel(channel ID);
- Read ADC channel: to read the analog value of the selected channel
previously as digital use:
x = read_adc();
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).
42
- Interface PIC 16f877a to LCD: listed in table (4).
- 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);
- Escape Sequences used to manage the display are listed in table (6)
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);
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:
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.
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.
47
Interrupts in 16F877A
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.
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
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);
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:
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.
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.
Example 2:
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){}
}
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).
- Pins Description
Communication methods
There are two methods for serial communication, Synchronous &
Asynchronous:
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.
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.
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.
55
o TXSTA register: pin25 (RC6) set as transmitter in asynchronous
Slave mode.
o SPBRG register
This is the register which holds the baud rate generator value.
# 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:
# 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);
}}
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
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).
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.
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)
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
# 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
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);
}}
63
Figure 3: Example 1 circuit diagram.
64