PIC Microcontroller in Practice: Educational Engineering Team

You might also like

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

PIC Microcontroller in Practice

Educational Engineering Team


PIC Microcontroller in Practice Educational Engineering Team

Table of Contents

Experiment #1 Introduction to Software Tools MikroC, PROTEUS, and


QL-2006 programmer.
Experiment #2 Introduction to PIC16F84A

Experiment #3 Introduction to MikroC Language

Experiment #4 Some Logic Functions Design

Experiment #5 Delay Loops Applications Flasher & Counter & Push Buttons

7 segment Interface with PIC Microcontroller & Counter


Experiment #6 Application

Experiment #7 LCD Interface with PIC Microcontroller

Experiment #8 Keypad Interface with PIC

Experiment #9 Analog Digital Conversion

Experiment #10 Unipolar Stepper Motor Control

Experiment #11 Dot-Matrix Display

Experiment #12 Serial Interface with PIC Microcontroller

Experiment #13 Interrupt Application Controlling flashing speed of a flasher

Experiment #14 TMR0 Application Counter Using TMR0

Experiment #15 Pulse-width modulation (PWM)

2
PIC Microcontroller in Practice Educational Engineering Team

Experiment #16 EEPROM Memory Application

Application for Interrupt using MikroC Iqama


Experiment #17
System

Application for Keypad and LCD Security


Experiment #18
System

3
PIC Microcontroller in Practice Educational Engineering Team

Lab 1
Introduction to Software Tools
MikroC, PROTEUS, and QL-2006 programmer

Objectives
1. To be familiar with some software tools like MIKROC, PROTEUS, and
IC- PROG.
2. To know how to make a project using MIKROC and then get the hex file
of the software program of the project.
3. How to simulate the hex file using PROTEUS.

Introduction
These programs are the backbone of the microprocessor and microcontroller based
systems; since using MIKROC we can build the software of the project using C or Assembly
language, and then we can simulate the project virtually using PROTEUS, finally we can
download the program on the microcontroller and see the results practically using IC- PROG.
So this experiment includes all the knowledge the student will need to get started to these
programs.

1. MIKROC Program
• What is MIKROC?

MIKROC is a software program that runs on your PC to provide a development


environment for your embedded system design.
In other words, it is a Windows program package that makes writing and developing
a program easier. It could best be described as developing environment for a standard
program language that is intended for programming microcontrollers.

• Get started to MIKROC

1. Open the program by double clicking on its icon on the desktop.


2. From the project menu choose project wizard.
3. Choose PIC 16F84A.
4. Brows and name the project.
5. From view menu choose project; to view the project.
6. Then add a file to the source files by right clicking on source files, and
choose add files and then name the file anyName.asm

4
[Type here ] [Type here ]

2. PROTEUS Program

• What is PROTEUS?

Proteus contains everything you need to develop, test and virtually prototype your
embedded system designs based around the Microchip Technologies™ PIC16 series
of microcontrollers. The unique nature of schematic based microcontroller simulation
with Proteus facilitates rapid, flexible and parallel development of both the system
hardware and the system firmware. This design synergy allows engineers to evolve
their projects more quickly, empowering them with the flexibility to make hardware or
firmware changes at will and reducing the time to market.
Proteus VSM models will fundamentally work with the exact same HEX file as you
would program the physical device with, binary files (i.e. Intel or Motorola Hex files)
produced by any assembler or compiler.

• How to setup PROTEUS?

1. Start-up the Microsoft Windows.


2. Place the Proteus Software CD into CD ROM drive.
3. Double click on the software tools folder and then choose Proteus Simulator after
that double click Proteus folder and run the setup.
4. Press next until you reach the window which ask for the key.
5. From browse for key; browse until you reach the same folder where the setup
exists, and then open the second folder and chose the MAXIM_LICENCE folder.
6. Then click on the top icon which is MAXIM and then press install.
7. Then choose yes and then close the window, after that browse and install the
program.
8. After that run the patch which exist in the same folder where the
MAXIM_LICENCE exists.
9. Then browse for c:\Program files\Labcenter electronics \Proteus.
10. Finally chose next, and then finish.

• Get started to PROTEUS

1. From start menu chose the PROTEUS, and then chose ISIS(blue).
2. To get a part click on Devices ( P ).
3. Write the name of the PIC16F84A.
4. To get LED write led then chose green led.
5. To get a resistor write 1k and chose the first part

5
[Type here ] [Type here ]

3. QL-2006 programmer

QL-2006 programmer is the high-speed programmer designed specially for


development and production programming of PIC single chip
microcomputer (SCM) by Shenzhen Qianlongsheng Electronic Technology
Co., Ltd. The product is featured with small volume, low power
consumption, high reliability as well as easy and convenient operation.
QL-2006 is applicable for almost all PIC10/12/16/18 series SCMs except
16C5X. It also supports memories in 24XX series and 93XX series.

• Hardware Installation
There is no special requirement for installation of this programmer. Connect
programmer to PC through serial port cable or USB cable and power up,
then the programmer works. (This programmer supports direct USB power
supply. If USB cable is connected, you may not connect external power.
However, if current through USB interface is very low – less than 200MA and
insufficient to drive programmer, connection to external power is required to
enable the programmer to work regularly.)

• Software Installation

Find file QL-PROGvXXen.EXE under root directory of CD, double click


this file to access installation interface of application software, and operate
according to prompts to finish the installation. Its shortcut will appear on
desktop automatically after installation.

• Running of Software
After proper installation, shortcut of this software will appear on desktop.
We can double click it to run the software.

6
Lab 2
Introduction to PIC16F84A

Objective
To get familiar with programming and using PIC16F84 microcontroller.

Tools
PIC16F84 Microcontroller, IC programmer, MIKROC software.

Theory
A microcontroller (or MCU) is a computer-on-a-chip. It is a type of
microprocessor emphasizing self-sufficiency and cost-effectiveness, in contrast
to a general-purpose microprocessor (the kind used in a PC).
A microcontroller is a single integrated circuit, commonly with the following
features:
• Central processing unit - ranging from small and simple 4-bit
processors to sophisticated 32- or 64-bit processors
• input/output interfaces such as serial ports (UARTs)
• Other serial communications interfaces like I²C, Serial Peripheral
Interface and Controller Area Network for system interconnect
• Peripherals such as timers and watchdog
• RAM for data storage
• ROM, EPROM, EEPROM or Flash memory for program storage
• clock generator - often an oscillator for a quartz timing crystal, resonator
or RC circuit
• many include analog-to-digital converters

PIC16F84 microcontroller
PIC16F84 belongs to a class of 8-bit microcontrollers of RISC
architecture. Its general structure is shown on the following map
representing basic blocks.

PIC16F84 has a total of 18 pins. It is most frequently found in a DIP18 .

7
[Type here ] [Type here ]

It can also be found in SMD case which is smaller from a DIP. DIP is an abbreviation
for Dual In Package. SMD is an abbreviation for Surface Mount Devices suggesting
that holes for pins to go through when mounting aren't necessary in soldering this type
of a component.

Pins on PIC16F84 microcontroller have the following meaning:

• Pin no.1 RA2 Second pin on port A. Has no additional function


• Pin no.2 RA3 Third pin on port A. Has no additional function.
• Pin no.3 RA4 Fourth pin on port A. TOCK1 which functions as a timer is
also found on this pin
• Pin no.4 MCLR Reset input and Vpp programming voltage of a
microcontroller
• Pin no.5 Vss Ground of power supply.
• Pin no.6 RB0 Zero pin on port B. Interrupt input is an additional function.
• Pin no.7 RB1 First pin on port B. No additional function.
• Pin no.8 RB2 Second pin on port B. No additional function.
• Pin no.9 RB3 Third pin on port B. No additional function.
• Pin no.10 RB4 Fourth pin on port B. No additional function.
• Pin no.11 RB5 Fifth pin on port B. No additional function.
• Pin no.12 RB6 Sixth pin on port B. 'Clock' line in program mode.
• Pin no.13 RB7 Seventh pin on port B. 'Data' line in program mode.
• Pin no.14 Vdd Positive power supply pole.
• Pin no.15 OSC2 Pin assigned for connecting with an oscillator
• Pin no.16 OSC1 Pin assigned for connecting with an oscillator
• Pin no.17 RA2 Second pin on port A. No additional function
• Pin no.18 RA1 First pin on port A. No additional function.

8
[Type here ] [Type here ]

Procedure
Part 1
• Connect the circuit shown in the figure
• Write a C language program that send 0x8a to port B
• Load the program to the microcontroller

Part 2
• Connect the circuit shown in the figure
• Write a C program that inputs data from port A and sends it to port B
• Program a PIC 16F84A using the QL2006 programmer.
• Build the circuit using the programmed PIC 16F84A and then observe its
operation. Demonstrate the circuits operation to the instructor.

Part 3
• Present your results in a lab report including a copy of the source codes.

9
[Type here ] [Type here ]

Lab 3
Introduction to MikroC Language

Objectives
17. To know what is the MikroC Language.
18. To know how to write your first program in MikroC Language.
19. To know the advantages and disadvantages of this language over Assembly
Language.

Tools

PIC16F84A microcontroller, MikroC software, PROTEUS software, USB


Programmer.

Theory
MikroC is a powerful, feature rich development tool for PICmicros. It is designed
to provide the programmer with the easiest possible solution for developing
applications for embedded systems, without compromising performance or control.
PIC and C fit together well: PIC is the most popular 8-bit chip in the world, used
in a wide variety of applications, and C, prized for its efficiency, is the natural
choice for developing embedded systems. MikroC provides a successful match
featuring highly advanced IDE, ANSI compliant compiler, broad set of hardware
libraries, comprehensive documentation, and plenty of ready-to-run examples.

Features of MikroC

MikroC allows you to quickly develop and deploy complex applications:

• Write your C source code using the built-in Code Editor (Code and Parameter
Assistants, Syntax Highlighting, Auto Correct, Code Templates, and more…)
• Use the included MikroC libraries to dramatically speed up the development:
data acquisition, memory, displays, conversions, communications…
Practically all P12, P16, and P18 chips are supported.
• Monitor your program structure, variables, and functions in the Code
Explorer.
• Generate commented, human-readable assembly, and standard HEX
compatible with all programmers.
• Inspect program flow and debug executable logic with the integrated
Debugger.
• Get detailed reports and graphs: RAM and ROM map, code statistics,
assembly listing, calling tree, and more…
• There are plenty of examples for you to expand, develop, and use as building
bricks in your projects. Copy them entirely if you deem fit – that’s why we
included them with the compiler.

10
[Type here ] [Type here ]

Compilation and Assembling

As shown MikroC code needs two steps to be transformed to Machine code, the
first step is to transform the C code to Assembly code, which is called Compilation.
The second step is to transform the Assembly code to Machine Code, and this
process is called Assembling.
So, In spite of being easy to write your code in C Language, MikroC Language is
slower than the Assembly language because it needs two steps to be transformed to
machine language.

How to write Your Program in MikroC

a) In case of No Interrupt b) In case of Interrupt

Notes about Programming in MikroC Language

• In MikroC language you don't need to be in bank0, or in bank1, you can deal
directly with Special Function Registers (SFR).

11
[Type here ] [Type here ]

• To make an infinite loop, do as the following

Since this sentence is always true.


• To a delay you can use the following built in functions:
Delay_ms(const int) Î delay_ms(1000) Î 1 sec
Vdelay_ms(int) Î vdelay_ms(1000) Î 1 sec

• To make inverting use ~.


• To access an individual bit, use the following:

Or

Procedure
Part1:
• Write a C code program to make a counter count from (0 – 9).
Hint // Use for loop and delay function delay_ms.
• Simulate the program using the circuit shown in figure via Proteus software.
Verify it operates properly when simulated.
• Program a PIC 16F84A using the QL2006 programmer.
• Build the circuit using the programmed PIC 16F84A and then observe its
operation. Demonstrate the circuits operation to the instructor

12
[Type here ] [Type here ]

Part2:
• Write a C code program to make a flashing wave on PORT B,
and then control the direction, and the speed of the flashing wave,
through PORT A.
• Simulate the program using the circuit shown in figure via Proteus
software.
Verify it operates properly when simulated.
• Program a PIC 16F84A using the QL2006 programmer.
• Build the circuit using the programmed PIC 16F84A and then
observe its operation. Demonstrate the circuits operation to the
instructor

13
[Type here ] [Type here ]

Lab 4
Some Logic Functions Design

Objectives
1. To know how to design some logic functions like Addition, Subtraction, and
Multiplication using the microcontroller PIC16F84A.
2. To know how to simulate these functions using PROTEUS program.
3. To know how to program the microcontroller PIC16F84A and then simulate
these Logic Functions using hardware.

Tools

• PIC16F84A microcontroller.
• MIKROC software.
• PROTEUS software.
• QL2006 USB Programmer.

Theory
In this experiment we will implement the Addition and Subtraction Functions
Using PIC16F84A microcontroller.

• Addition and subtraction functions


The addition function is summarized as follow:

14
[Type here ] [Type here ]

1. After that we add the two numbers using the instruction + and then we display
the result on PORTA.

The subtraction function is the same as the addition function except you will
subtract the two numbers instead of adding them. To avoid negative, answer the
first number must be greater than the second.

Procedure

Part 1: Addition Function


• Write a C program to achieve the addition of two numbers entered to port B
and display the result on port A.
• Simulate the program using the circuit shown in figure via Proteus software.
Verify it operates properly when simulated.

• Program a PIC 16F84A using the QL2006 programmer.


• Build the circuit using the programmed PIC 16F84A and then observe its
operation. Demonstrate the circuits operation to the instructor.

15
[Type here ] [Type here ]

Part 2: Subtraction Function


• Write a C program to achieve the subtraction of two numbers entered to
port B and display the result on port A.
• Simulate the program using the circuit shown in figure via Proteus software.
Verify it operates properly when simulated.

• Program a PIC 16F84A using the QL2006 programmer.


• Build the circuit using the programmed PIC 16F84A and then observe its
operation. Demonstrate the circuits operation to the instructor.

Part 3
• Present your results in a lab report including a copy of the source codes.

16
[Type here ] [Type here ]

Lab 5
Delay Loops Applications
Flasher & Counter

Objectives
1. To know how to make a delay loop with a certain value.
2. To realize how PIC16F84A microcontroller deals with timing issues.
3. To get familiar with interfacing 7-Seg display to PIC16F84A and make a
counter.
4. To get familiar with interfacing LED display to PIC16F84A and make a
flasher.

Tools

PIC16F84A microcontroller, MIKROC software, PROTEUS software,


USB Programmer.

Theory
There are two methods to generate Delay IN PIC16F84A
Microcontroller:

• The first method is using TMR0, which is a built in timer in PIC16F84A


microcontroller.
• The second method is using Delay Loops Technique.

In this experiment we will know how to generate a Delay with a certain value using
the Delay Loops Technique; after that we will use this delay to make some
applications like Flasher and Counter.

The Ordinary Instructions need 1 cycle to be executed, but the cycles which cause
the program counter (PC) to be changed need 2 cycles.

Examples

Movlw .100 Î needs 1 cycle.


Movwf portb Î needs 1 cycle.
Call delay Î needs 2 cycles.
Goto loop Î needs 2 cycles. And so on.

17
Delay Subroutine

Consider the following delay subroutine:


- Delay_ms(100); This means 100 millisecond delay
Ms stands for Millisecond

- Delay_us(100); This means 100 Microsecond delay


Us stands for Microsecond

Procedure

Part 1: Flasher

• Write a C program to make a Flasher on RB0 (Hint: Use the Delay


Subroutine).
• Simulate the program using the circuit shown in figure via Proteus software.
Verify it operates properly when simulated
• Program a PIC 16F84A using the QL2006 programmer.
• Build the circuit using the programmed PIC 16F84A and then observe its
operation. Demonstrate the circuits operation to the instructor.

Part 2: Counter

• Write a C program to make a Counter (0 – 9) on Port A. RB0 (Hint: Use the Delay
Subroutine).
• Simulate the program using the circuit shown in figure via Proteus software.
Verify it operates properly when simulated
• Program a PIC 16F84A using the QL2006 programmer.
• Build the circuit using the programmed PIC 16F84A and then observe its
• operation. Demonstrate the circuits operation to the instructor.

Part 3: 8 Leds Flasher

• Write a C program to make a Led flasher on Portb. RB0 – RB7 (Hint: Use the
Delay Subroutine).
• Simulate the program using Proteus software.
Verify it operates properly when simulated
• Program a PIC 16F84A using the QL2006 programmer.
• Build the circuit using the programmed PIC 16F84A and then observe its operation.
• Demonstrate the circuits operation to the instructor.

Part 4: In and Out Flasher using Binary Numbering

• Write a C program to make a Led flasher on Portb. RB0 – RB7 in such a way that
the first led will turn on, then the second until the last Led then turn off the last led
then the one before it and so on.
(Hint: Use the Delay Subroutine).
• Simulate the program using Proteus software.
Verify it operates properly when simulated
• Program a PIC 16F84A using the QL2006 programmer.
• Build the circuit using the programmed PIC 16F84A and then observe its operation.
• Demonstrate the circuits operation to the instructor.

Part 5: In and Out Flasher using Shifting Instruction

• Write a C program to make a Led flasher on Portb. RB0 – RB7 in such a way that
the first led will turn on, then the second until the last Led then turn off the last led
then the one before it and so on.
(Hint: Use the Delay Subroutine).
• Simulate the program using Proteus software.
Verify it operates properly when simulated
• Program a PIC 16F84A using the QL2006 programmer.
• Build the circuit using the programmed PIC 16F84A and then observe its operation.
• Demonstrate the circuits operation to the instructor.

Part 6

• Present your results in a lab report including a copy of the source code
Lab 6
LCD Interface with PIC Microcontroller

Objectives
1. To know the internal structure of 7 Segment display.
2. To interface 7 Segment display with PIC16F84.
3. To apply different techniques and learn how to implement 7 Segment in different
applications

Tools

PIC16F877A microcontroller, 7 Segment Display, 74LS47 BCD Decoder,


MIKROC software, PROTEUS software, USB Programmer.

Theory

7 Segment Display

Seven segment display is regarded as the most basic


and simplest electronics display device. Simplest,
because its working is easy to understand and its
interface with the controller is quite straight-forward.
Seven segments, as the name suggests, consist of
seven LEDs organized in a specific pattern. Each LED
is known as a segment and it is assigned a name from
‘a’ to ‘g’. Another additional 8th LED named as ‘dp’
is also present sometimes in a 7-segment display which
is used to illuminate a dot or a decimal point.

A common pin is also associated with the 7-segment,


which is used to identify the type of 7-segment
display; whether it is common anode or common
cathode. In common anode display, the positive pins
of all the LEDs are tied together to form the common
pin which needs to be provided a ‘HIGH’ signal. In
common cathode display, all the cathode connections
of the LEDs are tied together which forms the
common pin that needs to be grounded.
Lab Work

Procedure

Part 1: From 0 to 9 Counter using Resistors

• Write a C program to display numbers from 0 – 9.


• Simulate the program using the circuit shown in figure via Proteus software.
Verify it operates properly when simulated
• Program a PIC 16F877A using the QL2006 programmer.
• Build the circuit using the programmed PIC 16F877A and then observe its
operation. Demonstrate the circuits operation to the instructor.
Part 2: From 0 to 9 Counter using BCD Counter

• Write a C program to display numbers from 0 – 9 using BCD Decoder.


• Simulate the program using the circuit shown in figure via Proteus software.
Verify it operates properly when simulated
• Program a PIC 16F877A using the QL2006 programmer.
• Build the circuit using the programmed PIC 16F877A and then observe its
• operation. Demonstrate the circuits operation to the instructor.

Part 3: Multiplexing a Number on two 7 Segments

• Write a C program to display the number 63 on two 7 Segment Display using


Multiplexing.
• Simulate the program using the circuit shown in figure via Proteus software.
Verify it operates properly when simulated
• Program a PIC 16F877A using the QL2006 programmer.
• Build the circuit using the programmed PIC 16F877A and then observe its
• operation. Demonstrate the circuits operation to the instructor.
Part 4: Multiplexing a 9999 counter on four 7 Segments

• Write a C program to make a Counter (0 – 9999) PortB and PortC


• Simulate the program using the circuit shown in figure via Proteus software.
Verify it operates properly when simulated
• Program a PIC 16F877A using the QL2006 programmer.
• Build the circuit using the programmed PIC 16F877A and then observe its
• operation. Demonstrate the circuits operation to the instructor.

Part 5

• Present your results in a lab report including a copy of the source codes.
Lab 7
LCD Interface with PIC Microcontroller

Objectives
1. To know how LCD Works.
2. To realize how PIC16F84A microcontroller deals with LCD.
3. To get familiar with interfacing LCD display to PIC16F84A and show words.

Tools

PIC16F84A microcontroller, LCD Display LM016L, MIKROC software,


PROTEUS software, USB Programmer.

Theory

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 has a simple interface as shown in
the figure.
D0-D7 is the data bus and is used to pass commands and characters to the
LCD. Data can be transferred to and from the display either as a single 8-bit
byte or two 4-bit nibbles. In the later case only the upper four data lines
(D4-D7) are used. This 4-bit mode is beneficial when using a microcontroller
with few input/output pins available.

VSS = Ground (0V)


VDD= VCC (4.5 V – 5V)
VEE= Used to alter the control contrast of the display. Ideally, it should be
connected to variable power supply.

RS (Register Select): when this line is low, data bytes transferred to the
display are treated as commands. By setting it to high data is treated as
characters.
E: Starts the transfer of data to or from the LCD on falling edge
R/W: This line is used to choose whether to write to or to read from the
LCD.
Since we will write to the LCD, and not read we will connect R/W
to the ground, and the above figure will be as shown

Lab Work

26
Hints about the program

1) To simplify the work, Use the PIC16F877A, because it has more I/O Bins.
2) To initialize the LCD use the function lcd_Init as follow

void Lcd_Init(unsigned short *port);


Example: if we write the following code:
Lcd_Init(); then
D7 → portb.7
D6 → portb.6
D5 → portb.5
D4 → portb.4
E → portb.3
RS → portb.2
RW → portb.0

3) To write a text use the function


void Lcd_Out_Cp(char *text);

Example: write the text Hello in the LCD


Lcd_Out_Cp("Hello");

7) To write in a specified location use the function


void Lcd_Out(unsigned short row, unsigned short col, char *text);
Example: write the text "Correct Password" in row 2 and column 1
Lcd_Out(2, 1, "Correct Password");

8) To print a character on the LCD use the function


void Lcd_Chr_Cp(char character);
So this function can be used to print a character on the LCD at current cursor
position. Both variables and literals can be passed as character.
Examples
To print the character 1 Î Lcd_Chr_Cp('1');
Also you can use the ASCII code for 1 Î Lcd_Chr_Cp(0X31);

9) To clear the LCD use the function


void Lcd_Cmd(unsigned short command);
This function Sends commands to LCD. You can pass one of the predefined
commands to the function.
Example: Lcd_Cmd(Lcd_Clear) Î clears the LCD.

10) To make a delay use the function


void Delay_ms(const time_in_ms);
Example: Delay_ms(1000); Î makes 1 sec delay.

11) To move text to the right use this function


Lcd_Cmd(_LCD_SHIFT_RIGHT);

12) To move text to the left use this function


Lcd_Cmd(_LCD_SHIFT_LEFT);

27
13) For more information about these functions, refer to the help of MikroC.

Procedure

Part 1: Write a sentence

• Write a C program to clear LCD and Turn off the Cursor then display “PIC
Microcontroller” for 5 seconds then clear LCD
• Simulate the program using the circuit shown in figure via Proteus software.
Verify it operates properly when simulated
• Program a PIC 16F84A using the QL2006 programmer.
• Build the circuit using the programmed PIC 16F84A and then observe its
operation. Demonstrate the circuits operation to the instructor.

Part 2: Write and Move Words on LCD

• Write a C program to clear LCD and Turn off the Cursor


• Display “Welcome to PIC Microcontroller” on LCD and move the words to the
right 16 times then back to the left 16 times.
• Simulate the program using the circuit shown in figure via Proteus software.
Verify it operates properly when simulated
• Program a PIC 16F84A using the QL2006 programmer.
• Build the circuit using the programmed PIC 16F84A and then observe its
operation. Demonstrate the circuits operation to the instructor.

Part 3

• Present your results in a lab report including a copy of the source code.

28
Lab 8
Keypad Interface with PIC Microcontroller

Objectives
1. To know what is a keypad and see its internal structure.
2. To realize how PIC16F877A microcontroller deals with keypad.
3. To get familiar with interfacing keypad to PIC16F877A and make a
counter.
4. To get familiar with coding keypad and control devices using it.

Tools

PIC16F877A microcontroller, keypad, LCD Display LM016L, MIKROC


software, PROTEUS software, USB Programmer.

Theory

Keypad
Matrix Keypad is a very useful and user-friendly when we want to design certain
applications like Calculator, Telephone etc. Matrix Keypad is made by arranging push
button switches in rows and columns. Just imagine, if you want to interface a 4*4 (16
keys) matrix keypad with a microcontroller. In the straight forward way, you will
need 16 pins of a microcontroller for that, but by using a simple technique we can
reduce it to 8 pins. In the matrix keypad switches are connected in a special manner a
shown in the figure below.

29
Pressed keys can be detected by Scanning. For the sake of explanation, let’s assume all
column connections (Col1 – Col4) are input pins and all row connections (Row1 –
Row4) are output pins. In the normal case (not scanning) all column inputs where in
LOW (GND) state. For scanning keypad,
1. A Logic HIGH signal is given to Col1 of column inputs.
2. Then each Row output (row1 – row4) is scanned one by one. If any of the key
belongs to first column is pressed, the Logic high signal from the Col1 will pass
to that row. Through we can detect the key.
3. This process is repeated for all columns if we want to detect multiple keys.
Matrix Keypad scanning is stopped as soon as any key press is detected and the
Scanning is restarted if we need more inputs.

Lab Work
In this lab we are going to connect Keypad and a 7 Segment display to show the key we
press on that display.

Matrix Keypad is connected to the PORTB of the PIC Microcontroller. Each column of

the Matrix Keypad is connected to RB0 – RB3 of the PIC Microcontroller, which are
configured as output pins. While each row of the Matrix Keypad is connected to RB4 –
RB7 of the PIC Microcontroller, which are configured as input pins.

Here 4*4 matrix keypad is being used, having characters 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, -,


C, U, E, F. ‘B’ is replaced by ‘-‘ and ‘D’ is replaced by ‘U’ because Seven Segment
Display is used for displaying characters. ‘B’ will be similar to ‘8’ and ‘D’ will be
similar to ‘0’ when displayed in Seven Segment Display. For reading data for the Matrix
Keypad, each column is made high and rows are scanned as we mentioned above.

30
Hints about the program

1) MikroC provides the following three functions to interface Matrix Keypad.

Keypad_Init
Keypad_Key_Press
Keypad_Key_Click

2) Keypad_Init

Prototype: void Keypad_Init(void);

It initializes a particular port for working with keypad. A global variable ‘keypadPort’
must be defined before using this function. Port need to be initialized before calling this
function.

3) Keypad_Key_Press

Prototype: char Keypad_Key_Press(void);

This function reads key when a key is pressed and it returns number corresponding (1 –
16) to the pressed key. If no key is pressed, it will return 0.

4) Keypad_Key_Click

Prototype: char Keypad_Key_Click(void);

When this function is called, it waits until some key is pressed and released. When
released it returns number corresponding (1 – 16) to the pressed key. If no key is pressed,
it will return 0. If more than one key is pressed, the function waits until all pressed keys
are released and returns number corresponds to first pressed key. Port need to be initialized
before calling this function.

31
Procedure

Part 1: 4*4 Keypad Matrix with 7 Segment

• Write a C program to read the key pressed on the matrix keypad and display the
value on 7 Segment Display.
• Simulate the program using the circuit shown in figure via Proteus software.
Verify it operates properly when simulated
• Program a PIC 16F877A using the QL2006 programmer.
• Build the circuit using the programmed PIC 16F877Aand then observe
its operation. Demonstrate the circuits operation to the instructor.

Part 2: 4*3 Keypad Matrix with LCD Display


For demonstration of the working, here we will use a 4*3 keypad. The pressed key and
number of times a particular key is pressed in displayed in LCD Display.

• Write a C Program to read the key pressed on the Matrix keypad and display
the result in this form “The Pressed Key is = ” + the Key
• Simulate the program using the circuit shown in figure via Proteus software.
Verify it operates properly when simulated
• Program a PIC 16F877Ausing the QL2006 programmer.
• Build the circuit using the programmed PIC 16F877Aand then observe its
operation
• Demonstrate the circuits operation to the instructor.

32
Part 3

• Present your results in a lab report including a copy of the source codes.

33
Lab 9
Analog Digital Conversion

Objectives
25. To know what do we mean by Analog Digital Conversion or simply ADC.
26. To know how to use the ADC module in microcontroller PIC16F877A.

Tools

PIC16F877A microcontroller, MikroC software, PROTEUS software, USB


Programmer.

Theory
In almost in all digital systems, there is a frequent need to convert analog
signals generated by peripheral devices such as microphones, analog cameras,
sensors, and etc. into digital values that can be stored and processed.
There are various types of analog to digital converters: high speed ones, precise
ones, and economical ones and so on. Most of them can be directly connected to
any processor as shown in the figure

From the Processor-ADC interface shown in the figure, 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.

34
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. In
consequence, the number of discrete values available, or "levels", is usually a
power of two. For example, an ADC with a resolution of 8 bits can encode an
analog input to one in 256 different levels, since 28 = 256. The values can represent
the ranges from 0 to 255 (i.e. unsigned integer) or from -128 to 127 (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:

Where:
Q : is resolution in volts per step (volts per output code),
EFSR : is the full scale voltage range = VRefHi − VRefLow,
M : is the ADC's resolution in bits.
N : is the number of intervals, given by the number of available
levels (output codes), which is: N = 2^M
Example
Full scale measurement range = 0 to 10 volts
ADC resolution is 12 bits: 2^12 = 4096 quantization levels (codes)
ADC voltage resolution is: (10V - 0V) / 4096 codes = 10V / 4096 codes
0.00244 volts/code 2.44 mV/code

ADC Module in Microcontroller PIC16F877A

The Microcontroller PIC16F877A has a built in ADC Module, and we can access this
module from ADCON1 Register, as follow

ADCON1 REGISTER

Bit 7 ADFM: A/D Result Format Select bit


1 = Right justified. Six (6) Most Significant bits of ADRESH are read as ‘0’.
0 = Left justified. Six (6) Least Significant bits of ADRESL are read as ‘0’.
Bit 6 ADCS2: A/D Conversion Clock Select bit (ADCON1 bits in shaded area and
in bold)

35
Bit 5-4 Unimplemented: Read as ‘0’
Bit 3-0 PCFG3:PCFG0: A/D Port Configuration Control bits

A = Analog input D = Digital I/O


C/R = # of analog input channels/# of A/D voltage references

Example
If we make ADCON1 = 0x80, then we have 8 analog channels, and Vref+ =
VDD, and Vref- = Vss.

36
The function Adc_Read( ) Î unsigned Adc_Read(unsigned short channel);
This function returns 10-bit unsigned value read from the specified channel, and
the Parameter channel represents the channel from which the analog value is to
be acquired.
Example
tmp = Adc_Read(1); This instruction reads the analog value from channel 1 ,
and returns the digital value result as 10 bits to tmp.
And the resolution will be (Vref+ - Vref-) / (2^10) = (5 – 0) / (1024) = 0.00488
volt / step.

The Digital Values corresponding to analog values will be as follow:

Analog value Digital Value


0V 0000000001 = 0x001

2.5V 0111111111 = 0x1FF

5V 1111111110 = 0x3FE

Digital Value = binary (Round [Analog Value / Resolution]).


In our case Resolution = 5/1024.
Also the results will start from 0 and end with 0x3FE, not with 0 and 0x3FF
as expected.

Procedure
• Write a C code program to take the analog value existed on channel 2, and
display the result on 3 seven segments.
Hint // Use the ADC built in module in Microcontroller PIC16F877A,
and
Also use DC voltmeter to see your analog value, before it is converted to
digital.
• Simulate the program using the circuit shown in figure via Proteus software.
Verify it operates properly when simulated.
• Program a PIC 16F84A using the QL2006 programmer.
• Build the circuit using the programmed PIC 16F877AA and then observe its
operation. Demonstrate the circuits operation to the instructor

37
38
Lab 10
Unipolar Stepper Motor Interface with PIC Microcontroller

Objectives
1. To see the internal structure of a unipolar stepper motor.
2. To get familiar with interfacing unipolar stepper motor display to PIC16F877A
and make control it.
7. To get familiar with controlling speed and direction of unipolar stepper
motor.

Tools

PIC16F877A microcontroller, Unipolar stepper Motor, ULN2003, H-Bridge,


MIKROC software, PROTEUS software, USB Programmer.

Theory
Unipolar Stepper Motor
A Stepper Motor is a brushless, synchronous DC electric motor, which divides the full
rotation into a number of equal steps. It finds great application in field of
microcontrollers such as robotics. Please refer the article Stepper Motor or Step Motor
for detailed information about working of stepper motor, types and modes of operation.
Unipolar Motor is the most popular stepper motor among electronics hobbyist because
of its ease of operation and availability. Here the working of Unipolar and Bipolar
Stepper Motor with PIC 16F877A Microcontroller is explained

39
Lab Work
Stepper Motor can be easily interfaced with PIC Microcontroller by using readymade ICs such as L293D
or ULN2003. Stepper Motor or Step Motor, we have three different types of stepping modes for unipolar
stepper motor.

Wave Drive
In this mode only one stator electromagnet is energized at a time. It has the same number
of steps as the full step drive but the torque is significantly less. It is rarely used. It can be
used where power consumption is more important than torque.

1. Full Drive
In this mode two stator electromagnets are energized at a time. It is the usual method used
for driving and the motor will run at its full torque in this mode of driving.

2. Half Drive
In this stepping mode, alternatively one and two phases are energized. This mode is
commonly used to increase the angular resolution of the motor but the torque is less
approximately 70% at its half step position (when only a single phase is on). We can see
that the angular resolution doubles in Half Drive Mode.

40
3. Driving Bipolar Motor
Bipolar motors are simpler in construction as it contains two coil and no center tap. Being
simple, driving is little complex compared to unipolar motors. To reverse the magnetic
polarity of stator windings, current through it must be reversed. For this we should use H-
Bridge. L293d is used here, H-Bridge Motor Driver for that. We can distinguish bipolar
motors from unipolar motors by measuring the coil resistance. In bipolar motors we can
find two wires with equal resistance.

41
Hints about the program

1) Interfacing Unipolar Stepper Motor with PIC Microcontroller To simplify the


work, Use the PIC16F877A, because it has more I/O Bins.

L293D and L293 are dual H-bridge motor drivers. The L293D can provide bidirectional
drive currents of up to 600-mA at voltages from 4.5 V to 36 V while L293 can provide up
to 1A at same voltages. Both ICs are designed to drive inductive loads such as dc motors,
bipolar stepping motors, relays and solenoids as well as other high-current or high-
voltage loads in positive-supply applications. All inputs of these ICs are TTL compatible
and output clamp diodes for inductive transient suppression are also provided internally.
These diodes protect our circuit from the Back EMF of DC Motor. In both ICs drivers are
enabled in pairs, with drivers 1 and 2 are enabled by a high input to 1,2EN and drivers 3
and 4 are enabled by a high input to 3,4EN. When drivers are enabled, their outputs will
be active and in phase with their inputs. When drivers are disabled, their outputs will be
off and will be in the high-impedance state.

ULN2003 is a monolithic high current and high voltage Darlington transistor


arrays. ULN2003 consists of seven NPN Darlington Transistor pairs that have high-
voltage outputs with common-cathode clamp diode for switching inductive loads. The
collector-current rating of a single Darlington pair can be up to 500mA. We can
connect Darlington Transistor pairs in parallel if higher current capability is needed.

42
Procedure

Part 1: Interfacing using L293

• Write a C program to make the motor rotate once in the left direction then in the
right direction
• Simulate the program using the circuit shown in figure via Proteus software.
Verify it operates properly when simulated
• Program a PIC 16F84A using the QL2006 programmer.
• Build the circuit using the programmed PIC 16F84A and then observe its
operation. Demonstrate the circuits operation to the instructor.

Part 2: Interfacing using ULN2003

• Write a C Program to control the Motor so that it will rotate 3 time in the left
direction then 4 times in the right direction then stop
• Simulate the program using the circuit shown in figure via Proteus software.
Verify it operates properly when simulated
• Program a PIC 16F84A using the QL2006 programmer.
• Build the circuit using the programmed PIC 16F84A and then observe its

• operation. Demonstrate the circuits operation to the instructor. 43


Part 3: Control Speed and Direction

• Write a C Program that has 4 switches two to make the motor rotate left and
right and two to make the motor rotate fast and slow
• Simulate the program using the circuit shown in figure via Proteus software.
Verify it operates properly when simulated
• Program a PIC 16F84A using the QL2006 programmer.
• Build the circuit using the programmed PIC 16F84A and then observe its
• operation. Demonstrate the circuits operation to the instructor.

Part 4

• Present your results in a lab report including a copy of the source codes.

44
Lab 11
Dot Matrix Display with PIC Microcontroller

Objectives
1. To know how Dot Matrix function and learn about it’s internal structure.
2. To get familiar with interfacing Dot Matrix display to PIC16F84A.
3. To know how to display numbers and letters.
4. To know how to move numbers, letters and words.

Tools

PIC16F877A microcontroller, DOT MATRIX Display, MIKROC software,


PROTEUS software, USB Programmer.

Theory

DOT MATRIX
LED dot matrices are very popular means of displaying information as it allows both static
and animated text and images. Perhaps, you have encountered them at gas stations
displaying the gas prices, or in the public places and alongside highways, displaying
advertisements on large dot matrix panels. In this experiment, we will discuss about the
basic structure of a monochrome (single color) LED dot matrix and its interface with a
microcontroller to display static characters and symbols.

45
In a dot matrix display, multiple LEDs are wired together in rows and columns. This is done
to minimize the number of pins required to drive them. For example, a 8×8 matrix of LEDs
(shown below) would need 64 I/O pins, one for each LED pixel. By wiring all the anodes
together in rows (R1 through R8), and cathodes in columns (C1 through C8), the required
number of I/O pins is reduced to 16. Each LED is addressed by its row and column number.
In the figure below, if R4 is pulled high and C3 is pulled low, the LED in fourth row and
third column will be turned on. Characters can be displayed by fast scanning of either rows
or columns.

Lab Work

The LED matrix used in this experiment is of size 5×7. We will learn how to display still
characters in a standard 5×7 pixel format. The figure below shows which LEDs are to be
turned on to display the English alphabet ‘A’. The 7 rows and 5 columns are controlled
through the microcontroller pins. Now, lets see in detail how it works.

Suppose, we want to display the alphabet A. We will first select the column C1 (which
means C1 is pulled low in this case), and deselect other columns by blocking their ground
paths (one way of doing that is by pulling C2 through C5 pins to logic high). Now, the first
column is active, and you need to turn on the LEDs in the rows R2 through R7 of this
column, which can be done by applying forward bias voltages to these rows. Next, select the
column C2 (and deselect all other columns), and apply forward bias to R1 and R5, and so
on. Therefore, by scanning across the column quickly (> 100 times per second), and turning
on the respective LEDs in each row of that column, the persistence of vision comes in to
play, and we perceive the display image as still.
46
Hints about the program
1) The table below gives the logic levels to be applied to R1 through R7 for each of the
columns in order to display the alphabet ‘A’.

2) You should have noted that across each row, one pin is sourcing the current for only
one LED at a time, but a column pin may have to sink the currents from more than
one LED. For example, the column C1 should be able to sink the currents from 6
LEDs while displaying the alphabet ‘A’. A microcontroller’s I/O pin cannot sink
this much of current, so external transistor arrays are required. I am using
ULN2003A IC which has seven built-in Darlington transistor arrays (see below). 47
The inputs of ULN2003A are active high. This means the input pins must be
supplied with logic high in order to bring the corresponding output pins to ground.
The schematic of the Darlington transistor array inside the ULN2003A chip is

shown below.

3) The switching between columns is fast enough to deceive the human eyes and a
steady character is displayed.

4) The wiring layout:

48
Procedure
Part 1: Display a Letter on 5*7 Matrix Display

• Write a C program to display the letter A on 5*7 Matrix Display


• Simulate the program using the circuit shown in figure via Proteus software.
Verify it operates properly when simulated
• Program a PIC 16F877A using the QL2006 programmer.
• Build the circuit using the programmed PIC 16F877A and then observe
its operation. Demonstrate the circuits operation to the instructor.

Part 2: Display Letters from A-Z on 5*7 Matrix Display

• Write a C program to display the letters from A-Z on 5*7 Matrix Display
• Simulate the program using the circuit shown in figure via Proteus software.
Verify it operates properly when simulated
• Program a PIC 16F877A using the QL2006 programmer.
• Build the circuit using the programmed PIC 16F877A and then observe its
• operation. Demonstrate the circuits operation to the instructor.

Part 3: Display a Moving Word on 5*7 Matrix Display

• Write a C program to display a Moving Word “Your Name” on 5*7 Matrix


Display
• Simulate the program using the circuit shown in figure via Proteus software.
Verify it operates properly when simulated
• Program a PIC 16F877A using the QL2006 programmer.
• Build the circuit using the programmed PIC 16F877A and then observe its
• operation. Demonstrate the circuits operation to the instructor.

Part 4

• Present your results in a lab report including a copy of the source codes.

49
Lab 12
Serial Interface with PIC Microcontroller
Objectives
1. To know what is Serial Communication.
5. To realize how 16F877A microcontroller deals with serial communication.
6. To get familiar with interfacing Computer COM Port for serial communication to
P I C 16F877A and send and receive data.
7. To get familiar with MAX232 IC and how to interface it with PIC
Microcontroller.

Tools

16F877A microcontroller, MAX232, Computer, MIKROC software, PROTEUS


software, USB Programmer.

Theory
Serial Communication
Unlike parallel communication, where several bits are send at one time, Serial
Communication is a process of transmitting data bit by bit. In this tutorial, you will learn how
to serially communicate a PC or any other device with a PIC microcontroller. You will also
study the use of a communication component – UART (Universal Asynchronous Receiver
Transmitter) present within the microcontroller.

Lab
Work

50
Serial Communication is the process of sending data one bit at a time. It is achieved by
using the UART feature within the pic microcontroller. UART (Universal Asynchronous
Receiver Transmitter) is a serial communication interface which is used for transmitting
and receiving data. The UART feature is first initialized and then it can be used for
transferring data. One of the serial communication architecture includes RS232 standard.
It is commonly used in computer serial ports. Using RS232 interface, the communication
between a microcontroller and a PC or two microcontrollers can be made possible.

Lab Work

In order to make the communication possible between PIC and a PC, a DB9 connector
(female) is used as shown in the schematic, whose male part is connected to the PC. The
voltage levels of RS232 protocol are different from that of UART. The voltage level
generally used in MCU is HIGH=5V and LOW=0V. Whereas the RS232 working
voltages are HIGH=+12V and LOW=-12V.

In order to use the RS232 protocol, we will need a level converter. A level converter will
convert the ±12V coming from PC into 5V which can be fed to the controller and vice
versa. The level converter used here is called ICMAX232. All the connections of IC with

the controller and also with the DB9 connector are shown in the circuit diagram above.
RC6/TX and RC7/RX pins of the microcontroller are connected to the T1IN and R1OUT
pins of the ICMAX232 respectively. Similarly, the T1OUT and R1IN pins of MAX232
are connected to the DB9 pins 2 (RX) and 3(TX) respectively. Pin 5 of the DB9 connector
is grounded. A virtual terminal is connected to the RX and TX pics of the microcontroller
to display the transmitting and receiving data.

Hints about the program

1) The idea of the program is to use the built in libraries to make serial
communication easier.
2) Initialize UART module at baud rate 19200 bps
51
UART1_Init(19200); //
3) You must add a delay to allow the UART Module to stabilize
Delay_ms(100);

4) Write data using this function


UART1_Write_Text(“Enter Data”);
5) To check if data is received or not
if (UART1_Data_Ready())
6) To read incoming data
UART1_Read(); // read the received data
11) For more information about these functions, refer to the help of MikroC.

Procedure

Part 1: Write and read data

• Write a C program to send data to a computer then receive data from it and
display it as it is on portb.
• Simulate the program using the circuit shown in figure via Proteus software.
Verify it operates properly when simulated
• Program a PIC 16F877A using the QL2006 programmer.
• Build the circuit using the programmed PIC 16F877A and then observe
its operation. Demonstrate the circuits operation to the instructor.

Part 2

• Present your results in a lab report including a copy of the source codes

52
Lab 13
Interrupt Application
Controlling flashing speed of a flasher

Objectives
8. To know what is the interrupt, and how many sources of interrupt does the
PIC16f84A microcontroller have.
9. To know how to make interrupt on PORTB through (RB4 – RB7).
10. To get familiar with interfacing LED display to PIC16F84A and make a
flasher.
11. To know how to change the flashing speed of this flasher using interrupts
method.

Tools

PIC16F84A microcontroller, MIKROC software, PROTEUS software, USB


Programmer.

Theory
Interrupts allow 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. The following
figure illustrates this

53
The PIC16F84A has 4 interrupt sources

1. Termination of writing data to EEPROM.


2. TMR0 interrupt caused by timer overflow.
3. Interrupt during alteration on RB4, RB5, RB6 and RB7 pins of port B.
4. External interrupt from RB0/INT pin of microcontroller.

In this experiment we will deal only with one of these sources, which is the interrupt
during alteration on (RB4 – Rb7).

Interrupt upon a change on pins 4, 5, 6 and 7 of port B


Change of input signal on PORTB <7:4> sets RBIF (INTCON<0>) bit. Four pins
RB7, RB6, RB5 and RB4 of port B, can trigger an interrupt which occurs when
status on them changes from logic one to logic zero, or vice versa. For pins to be
sensitive to this change, they must be defined as input. If any one of them is defined
as output, interrupt will not be generated at the change of status. If they are
defined as input, their current state is compared to the old value which was stored
at the last reading from port B.

Keeping the contents of important registers


Some registers which are already in use in the main program can also be in use in
interrupt routine. If they were not retained, main program would during a return
from an interrupt routine get completely different values in those registers, which
would cause an error in the program. Examples for such a case are the contents of
the work register W, and the status register. If we suppose that main program was
using work register W for some of its operations, and if it had stored in it some
value that's important for the following instruction, then an interrupt which
occurs before that instruction would change the value of work register W which
would directly be influenced the main program.

We use the instruction SWAPF F,d to save the contents of these registers
because it doesn't affect the Status Register.

1. How to save the contents

2. How to restore the contents

54
Procedure

• Write a C program to make a Flasher on RA0; then use the interrupt


method to control the flashing speed of this flasher.
Hint// Use the interrupt on change (RB4 – RB7)
• Simulate the program using the circuit shown in figure via Proteus software.
Verify it operates properly when simulated
• Program a PIC 16F84A using the QL2006 programmer.
• Build the circuit using the programmed PIC 16F84A and then
observe its operation. Demonstrate the circuits operation to the
instructor.

Part 2

• Present your results in a lab report including a copy of the source codes.
LAB 14
TMR0 Counter Application

Objectives
12. To know what is the free run timer TMR0; and the function of this timer.
13. To know how to make a counter using TMR0.

Tools

PIC16F84A m i c r o c o n t r o l l e r , M I K R O C s o f t w a r e , P R O T E U S
s o f t w a r e , U S B Programmer.

Theory
Timers are usually most complicated parts of a microcontroller, so it is
necessary to set aside more time for their explaining. With their application it is
possible to create relations between a real dimension such as "time" and a variable which
represents status of a timer within a microcontroller. Physically, timer is a register whose
value is continually increasing to 255, and then it starts all over again: 0, 1, 2, 3,
4...255....0, 1, 2, 3......etc. The following figure illustrates this.
More Information about TMR0
This incrementing is done in the background of everything a microcontroller does. It is
up to programmer to "think up a way" how he will take advantage of this characteristic for
his needs. One of the ways is increasing some variable on each timer overflow. If we know
how much time a timer needs to make one complete round, then multiplying the value of
a variable by that time will yield the total amount of elapsed time.
PIC16F84 has an 8-bit timer. Number of bits determines what value timer counts to before
starting to count from zero again. In the case of an 8-bit timer, that number is
256. A simplified scheme of relation between a timer and a prescaler is represented on the
previous diagram. Prescaler is a name for the part of a microcontroller which divides
oscillator clock before it will reach logic that increases timer status. Number which divides
a clock is defined through first three bits in OPTION register. The highest divisor is 256.
This actually means that only at every 256th clock, timer value would increase by one.
This provides us with the ability to measure longer timer periods.

TMR0 and Reset

After each count up to 255, timer resets its value to zero and starts with a new cycle of
counting to 255. During each transition from 255 to zero, T0IF bit in INTCOM
register is set. If interrupts are allowed to occur, this can be taken advantage of in
generating interrupts and in processing interrupt routine. It is up to programmer to
reset T0IF bit in interrupt routine, so that new interrupt or new overflow could be detected.
Beside the internal oscillator clock, timer status can also be increased by the external clock
on RA4/TOCKI pin. Choosing one of these two options is done in OPTION register
through T0CS bit. If this option of external clock was selected, it would be possible to
define the edge of a signal (rising or falling), on which timer would increase its value.

Option Control Register


Bit 0:2 PS0, PS1, PS2 (Prescaler Rate Select bit)
The subject of a prescaler, and how these bits affect the work of a microcontroller will be
covered in section on TMR0.

bit 3 PSA (Prescaler Assignment bit)


Bit which assigns prescaler between TMR0 and watchdog timer.
1=prescaler is assigned to watchdog timer.
0=prescaler is assigned to free timer TMR0

bit 4 T0SE (TMR0 Source Edge Select bit)


If trigger TMR0 was enabled with impulses from a RA4/T0CKI pin, this bit would
determine whether it would be on the rising or falling edge of a signal.
1=falling edge
0=rising edge

bit 5 T0CS (TMR0 Clock Source Select bit)


This pin enables a free-run timer to increment its value either from an internal
oscillator, i.e. every 1/4 of oscillator clock, or via external impulses on RA4/T0CKI
pin.
1=external impulses
0=1/4 internal clock

bit 6 INTEDG (Interrupt Edge Select bit)


If occurrence of interrupts was enabled, this bit would determine at what edge
interrupt on RB0/INT pin would occur.
1= rising edge
0= falling edge

bit 7 RBPU (PORTB Pull-up Enable bit)


This bit turns internal pull-up resistors on port B on or off.
1='pull-up' resistors turned on
0='pull-up' resistors turned off

Procedure
Part1: TMR0

• Write an C program to make a Counter using TMR0; the counter should


increment its value on every 2 pushbuttons on RA4.
• Simulate the program using the circuit shown in figure via Proteus software.
Verify it operates properly when simulated
• Program a PIC 16F84A using the QL2006 programmer.
• Build the circuit using the programmed PIC 16F84A and then observe its
operation. Demonstrate the circuits operation to the instructor.
Part2: Watchdog Timer (WDT)

• Write an C program to make a Counter using WDT; the counter should


increment its value on every one single pushbutton on RA4, and also counts
from 0 to 99.
• Simulate the program using the circuit shown in figure via Proteus software.
Verify it operates properly when simulated
• Program a PIC 16F84A using the QL2006 programmer.
Build the circuit using the programmed PIC 16F84A and then observe its
operation. Demonstrate the circuits operation to the instructor

Part 2

• Present your results in a lab report including a copy of the source codes.
Lab 15
Pulse-width modulation (PWM)

Objectives
27. To know what do we mean by Analog Digital Conversion or simply ADC.
28. To know how to use the ADC module in microcontroller PIC16F877A.

Tools

PIC16F877A microcontroller, MikroC software, PROTEUS software, USB


Programmer.

Theory
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.

Pulse-width modulation uses a rectangular pulse wave whose pulse width is


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

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

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

CAPTURE/COMPARE/PWM MODULES in Microcontroller


PIC16F877A

Each Capture/Compare/PWM (CCP) module contains a 16-bit register which can


operate as a:
• 16-bit Capture register
• 16-bit Compare register
• PWM Master/Slave Duty Cycle register

Both the CCP1 and CCP2 modules are identical in operation, with the exception being
the operation of the special event trigger. In
CCP1 Module:
Capture/Compare/PWM Register 1 (CCPR1) is comprised of two 8-bit registers:
CCPR1L (low byte) and CCPR1H (high byte). The CCP1CON register controls the
operation of CCP1. The special event trigger is generated by a compare match and
will reset Timer1.

CCP2 Module:
Capture/Compare/PWM Register 2 (CCPR2) is comprised of two 8-bit registers:
CCPR2L (low byte) and CCPR2H (high byte). The CCP2CON register controls the
operation of CCP2. The special event trigger is generated by a compare match and
will reset Timer1 .

CCP1CON/ CCP2CON REGISTERS

bit 7-6 Unimplemented: Read as ‘0’


bit 5-4 CCPxX:CCPxY: PWM Least Significant bits
Capture mode:
Unused.
Compare mode:
Unused.
PWM mode:
These bits are the two LSbs of the PWM duty cycle. The eight MSbs
are found in CCPRxL.
bit 3-0 CCPxM3:CCPxM0: CCPx Mode Select bits
0000 = Capture/Compare/PWM disabled (resets CCPx module)
0100 = Capture mode, every falling edge
0101 = Capture mode, every rising edge
0110 = Capture mode, every 4th rising edge
0111 = Capture mode, every 16th rising edge

61
1000 = Compare mode, set output on match (CCPxIF bit is set)
1001 = Compare mode, clear output on match (CCPxIF bit is set)
1010 = Compare mode, generate software interrupt on match (CCPxIF
bit is set, CCPx pin is unaffected)
1011 = Compare mode, trigger special event (CCPxIF bit is set, CCPx
pin is unaffected); CCP1 resets TMR1; CCP2 resets TMR1
and starts an A/D conversion (if A/D module is enabled)
11xx = PWM mode

PWM Mode (PWM)


In Pulse Width Modulation mode, the CCPx pin produces up to a 10-bit resolution PWM
output. Since the CCP1 pin is multiplexed with the PORTC data latch, the TRISC<2>
bit must be cleared to make the CCP1 pin an output. The following Figure shows a
simplified block diagram of the CCP module in PWM mode.

Pwm_Init function Î void Pwm_Init(unsigned long freq) :


Initializes the PWM module with duty ratio 0. Parameter freq is a desired PWM
frequency in Hz (refer to device data sheet for correct values in respect with Fosc).
This routine needs to be called before using other functions from PWM Library.

Example
Initialize PWM module at 5KHz:
Pwm_Init(5000);

62
Pwm_Change_Duty function Î void Pwm_Change_Duty(unsigned short
duty_ratio);

Changes PWM duty ratio. Parameter duty takes values from 0 to 255, where 0 is
0%, 127 is 50%, and 255 is 100% duty ratio. Other specific values for duty
ratio can be calculated as (Percent*255)/100.
Example
Set duty ratio to 75%:
Pwm_Change_Duty(192)
;

Pwm_Start function Î void

Pwm_Start(void); This function starts PWM.

Pwm_Stop function Î void

Pwm_Stop(void); This function stops PWM.

Procedue
• Write a C code program to changes PWM duty ratio on pin RC2 continually.
If LED is connected to RC2, you can observe the gradual change of
emitted light.
• Simulate the program using the circuit shown in figure via Proteus software.
Verify it operates properly when simulated.
• Program a PIC 16F84A using the QL2006 programmer.
• Build the circuit using the programmed PIC 16F877AA and then observe
its operation. Demonstrate the circuits operation to the instructor

63
Lab 16
EEPROM Memory Application

Objectives
14. To know what is the EEPROM Memory in Microcontroller PIC16F84A.
15. To know how to write to and how to read from this memory.
16. To know the advantages of this memory over other memories.

Tools

PIC16F84A microcontroller, MIKROC software, PROTEUS software, USB


Programmer.

Theory
PIC16F84 has 64 bytes of EEPROM memory locations on addresses from 00h to
63h those can be written to or read from. The most important characteristic of this
memory is that it does not lose its contents during power supply turned off. That
practically means that what was written to it will be remaining even if
microcontroller is turned off. Data can be retained in EEPROM without power
supply for up to 40 years (as manufacturer of PIC16F84 microcontroller states),
and up to 10000 cycles of writing can be executed.

In practice, EEPROM memory is used for storing important data or some process
parameters.
One such parameter is a given temperature, assigned when setting up a temperature
regulator to some process. If that data wasn't retained, it would be necessary to
adjust a given temperature after each loss of supply. Since this is very impractical
(and even dangerous), manufacturers of microcontrollers have began installing
one smaller type of EEPROM memory.

EEPROM memory is placed in a special memory space and can be accessed


through special registers. These registers are:

• EEDATA at address 08h, which holds read data or that to be written.


• EEADR at address 09h, which contains an address of EEPROM location
being accessed.
• EECON1 at address 88h, which contains control bits.
• EECON2 at address 89h. This register does not exist
physically and serves to protect EEPROM from accidental
writing.

EECON1 register at address 88h is a control register with five


implemented bits. Bits 5, 6 and 7 are not used, and by reading always
are zero. Interpretation of EECON1 register bits follows.

64
EECON1 Register

Bit 0 RD (Read Control bit)


Setting this bit initializes transfer of data from address defined in EEADR to EEDATA
register. Since time is not as essential in reading data as in writing, data from EEDATA
can already be used further in the next instruction.
1=initializes reading
0=does not initialize reading

Bit 1 WR (Write Control bit)


Setting of this bit initializes writing data from EEDATA register to the address
specified trough EEADR register.
1=initializes writing
0=does not initialize writing

Bit 2 WREN (EEPROM Write Enable bit) Enables writing to EEPROM


If this bit was not set, microcontroller would not allow writing to EEPROM.
1=writing allowed
0=writing disallowed

Bit 3 WRERR (Write EEPROM Error Flag ) Error during writing to EEPROM This bit
was set only in cases when writing to EEPROM had been interrupted by a reset signal
or by running out of time in watchdog timer (if it's activated).
1=error occured
0=error did not occur

Bit 4 EEIF (EEPROM Write Operation Interrupt Flag bit) Bit used to inform that writing
data to EEPROM has ended.
When writing has terminated, this bit would be set automatically. Programmer must
clear EEIF bit in his program in order to detect new termination of writing.
1=writing terminated
0=writing not terminated yet, or has not started

Procedure of Writing Operation


1. Put the address which you want to write to in EEADR.
2. Put the data which you want to write in EEDATA.
3. Disable all interrupts (GIE = 0).
4. Set the bin WREN in EECON1.
5. Put the Keys in EECON2 (first 0X55 then 0XAA).
6. Set the bin WR in EECON1.
7. Wait until Writing Operation is finished.

65
8. Enable all interrupts.

Procedure of Reading Operation


1. Put the address which you want to read from in EEADR.
2. Set the bin RD in EECON1.
3. Move the read data from EEDATA to the work register.

We follow these procedures in all times we want to write to or read from EEPROM
Memory, except that the address which we want to write to in writing operation /or read
from in reading operation; and the data which we want to write in writing operation/ or
read in reading operation differ each time.

Procedure
Part1:

• Write an C program to fill all the EEPROM Memory locations With


7.

Hint // Build an external Macro called EEPROM_Writing takes two parameters


the data and the address to achieve the writing operation; then call it in the
main program.
• Simulate your program using the software PIC Simulator IDE.

Part2:

• Write a C program to take the data existed on PORT A and display it on PORT
B; first, the data must be taken from PORT A and stored in the EEPROM
address location 0X10, and then be taken again from EEPROM and be
displayed on PORT B.

• You should use the EEPROM_Writing Macro from the previous part for
writing operation, and also build a nother macro EEPROM_Reading for reading
operation.
• Simulate your program using the software PIC Simulator IDE.
• Simulate the program using the circuit shown in figure via Proteus software.
Verify it operates properly when simulated
• Program a PIC 16F84A using the QL2006 programmer.
• Build the circuit using the programmed PIC 16F84A and then observe its
operation. Demonstrate the circuits operation to the instructor

66
Part 3

• Present your results in a lab report including a copy of the source codes.

67
Lab 17
Application for Interrupt using MikroC
Iqama System

Objectives
20. To know how to make interrupt using MikroC language.
21. To know how to use the method of interrupt in Iqama system.

Tools

PIC16F84A microcontroller, MikroC software, PROTEUS software, USB


Programmer.

Theory
Iqama system is a system which can be used to display the time remaining to the
Iqama after each Athan of the Muslim's five pray times.
We know that for each of the five prays there is a recognized (familiar) time
between the Athan and Iqama.

For the Fajr Î this time is 20 minutes


For the Zuhr and Assr Î 15 minutes.
For the Maghreb and Isha Î 10 minutes.

Note that these time periods (between Athan and Iqama) can differ in some
places, but these are the most familiar time periods.

Lab Work
In this lab we are going to build the Iqama system using MikroC language with
the method of interrupt. So that if the crier (Muezzen) after doing the Athan
pushes the button related to that Athan, two seven segments will decrease from
(20 or 15 or 10 minutes) according to the pray time, and when they reach zero
then the Iqama time comes. LED will flashing indicating that the crier (Muezzen)
must do the Iqama now. The buttons will be connected on bins (RB4, Rb5, and Rb6)
respectively, and will be accessed using interrupt method.

30

68
An illustration for this is shown in the following figure

Hints about the program


1) Use the method of interrupt on (RB4 – RB7) to make the Push Buttons (Fajr,
Zuhr & Assr, and Maghreb & Isha).
2) Within the Interrupt Service Subroutine (ISR), you should give some variable
a value (20 or 15 or 10) according to the pressed push button.
3) Then in the main program you should divide this number into 2 digits, and
then display each digit to a seven segment.
4) Decrement the original variable (variable from ISR) and then repeat step3.
Still decrement this variable until it reaches zero.
5) When it reaches zero, make a flasher on RA4 so that the crier (Muezzen)
notice that the Iqama time comes.
6) In order to fasten the simulation replace the minutes with seconds.

Tip about RA4 "RA4 as output"


Some PICs like PIC16F84A have RA4 with open drain output instead of CMOS
output !
RA4 is different; it is configured as an open drain MOSFET. When set to low,
it performs identically with the other pin architectures. However, when set to
high, there is no internal connection with VDD and hence it will not directly source
voltage. If it’s necessary to use RA4 as a sourcing output pin, you can add an
external “pull-up” resistor, typically in the range of 470 ohms–4.7K ohms. The
sourced current then comes from the pull-up resistor. Unlike all other pins that
cannot exceed VDD, RA4’s open drain is rated to 12 volts.
69
An illustration for this is shown in the following figure

This Tip is very important when it is necessary to use RA4 as output.


Procedure
• Write a C code program to make the Iqama system described in Lab Work
Part.
• Simulate the program using the circuit shown in figure via Proteus software.
Verify it operates properly when simulated.
• Program a PIC 16F84A using the QL2006 programmer.
• Build the circuit using the programmed PIC 16F84A and then observe its
operation. Demonstrate the circuits operation to the instructor

70
Lab 18
Application for Keypad and LCD
Security System

Objectives
22. To know what is the Keypad, and how to interface it to the Microcontroller.
23. To know what is the Liquid Crystal Display (LCD), and how to interface it to
the Microcontroller.
24. To know how to use Keypad and LCD to build a security system.

Tools

PIC16F84A microcontroller, MikroC software, PROTEUS software, USB


Programmer.

Theory

Keypad
Keypad is a commonly used input device when more than 8 keys
are necessary. It reduces the number of connections required by
arranging the keys in the form of a matrix which means that each
key could be referred to via its row and column indices.
Lets consider the case of a 12 keys matrix as the one shown
in the figure and we want to interface this keypad to PIC16F84A
microcontroller. In order to detect that one key is pressed we will
use the following strategy:

1. The 12 keys are arranged in 3 columns and 4 rows. Each


column and row is connected by a separated wire as shown in
the figure.

2. Pushing a key merely connects the corresponding row to the


corresponding column
3. We connect the columns to 3 output pin of the PIC and the rows to other 4
input pins.

71
4. For each of the columns we output logic '1' holding other columns to logic '0'
and scan the values of the rows, if one of the rows is logic '1', this means that
the key located at the intersection of the current column and the current row is
pressed. If no row is one, the logic '1' should be moved to the next column
and the rows then rescanned.
5. The PIC should keep repeating this process every time it's required to detect a
key press.

6. This method of keeping searching is called piling Method, also we may use
the interrupt method for key press detection.
7. There are many types of keypads like Phone Keypad (the shown above),
Calculator Keypad, and also keyboard is a form of keypad.
8. Almost all these keypads follow the same way in key press detection.
9. So, for interfacing any keypad to the microcontroller we need number of bins
equal to the number of rows and columns of that keypad.
10. As shown above the rows must be specified as inputs, and columns must be
specified as outputs.
LCD

72
Lab Work
In this lab we are going to make a security system using password. The LCD
indicates to the user that he must enter the password so that he can access the
system.
If the password is correct a LED will be ON. Showing that the password is correct,
we know that the LED merely represents an electrical signal and can be replaced
by a door or any other 220 VAC applications through a relay.

Hints about the program

1) The idea of the program is to store the original password in the EEPROM,
and then compare the password entered from the user with the original password
(Use the password 12345, so your password is 5 digits).

2) To simplify the work, Use the PIC16F877A, because it has more I/O Bins.
3) To initialize the LCD use the function lcd_Init as follow

void Lcd_Init(unsigned short *port);


Example: if we write the following code:
Lcd_Init(&PORTB); then
D7 → portb.7
D6 → portb.6
D5 → portb.5
D4 → portb.4
E → portb.3
RS → portb.2
RW → portb.0

4) To write and read from the EEPROM use the functions:

void Eeprom_Write(unsigned int address, unsigned short data);


unsigned short Eeprom_Read(unsigned int address);

Example (1): Write the Data 0XEE in the address 0X10


Eeprom_Write(0X10,0XEE)

Example (2): Read the data from the address 0X10


Eeprom_Read(0X10)
73
5) Make a function called Key_Read( ) to detect the number pressed on the
Keypad, use the method illustrated above.

6) For more information about these functions, refer to the help of MikroC.

Procedure
• Write a C code program to make the security system described in Lab
Work Part.
• The security system has the following features
a) The LCD asks the user to enter the password as shown.
b) If the password is correct, then the LCD writes "Correct Password" and
the LED will be on (connect the LCD on PORT D).
c) The user enters the password through a Keypad connected to PORT A.
Build a function called Key_Read( ) to detect the key press.
d) If the password is wrong then the LCD writes "Wrong Password, Try
again !", and the LED will be Off (connect the LED on PORT C).
e) The user can clear the LCD via the (#) button but the sentence "Enter
Password: " will be written again.
• Simulate the program using the circuit shown in figure via Proteus software.
Verify it operates properly when simulated.
• Program a PIC 16F84A using the QL2006 programmer.
• Build the circuit using the programmed PIC 16F877AA and then observe its
operation. Demonstrate the circuits operation to the instructor

74
75

You might also like