0% found this document useful (0 votes)
137 views

Microprocessor Systems Lab Manual 2023-1 PDF

This document outlines the labs for a Microprocessor Systems Lab course. It contains 8 labs that cover topics such as introduction to the PIC microcontroller architecture and MPLAB IDE, input/output port programming in assembly language, using timers and counters to generate waveforms, and pulse width modulation. The labs provide objectives, equipment needs, introductions to concepts, and exercises for students to complete to learn about programming PIC microcontrollers.

Uploaded by

Ajmal Yaqoob
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
137 views

Microprocessor Systems Lab Manual 2023-1 PDF

This document outlines the labs for a Microprocessor Systems Lab course. It contains 8 labs that cover topics such as introduction to the PIC microcontroller architecture and MPLAB IDE, input/output port programming in assembly language, using timers and counters to generate waveforms, and pulse width modulation. The labs provide objectives, equipment needs, introductions to concepts, and exercises for students to complete to learn about programming PIC microcontrollers.

Uploaded by

Ajmal Yaqoob
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 130

EE – 221L

Microprocessor Systems Lab

Faculty of Electrical Engineering


Ghulam Ishaq Khan Institute of Engineering Sciences & Technology

EE 222L – Microprocessor Systems Lab Page 1


Prepared By:

Engr. Hani Mazaheri & Dr. Memoon Sajid

EE 222L – Microprocessor Systems Lab Page 2


Table of Contents
LAB-1: INTRODUCTION TO PIC MICROCONTROLLER ARCHITECTURE AND MPLAB INTEGRATED DEVELOPMENT
ENVIRONMENT (IDE) ............................................................................................................................................... 10

1.1 OBJECTIVE................................................................................................................................................................. 10
1.2 PRE-LAB READING ...................................................................................................................................................... 10
1.3 EQUIPMENT/ SOFTWARE REQUIRED ............................................................................................................................... 10
1.4 INTRODUCTION .......................................................................................................................................................... 10
1.5 ACTIVITIES AND EXERCISES ........................................................................................................................................... 12
1.6 ASSESSMENT SHEET .................................................................................................................................................... 17

LAB-2: SIMULATION OF BASIC ASSEMBLY LANGUAGE PROGRAMS IN MPLAB IDE : READING REGISTER
STATUS/VALUES ...................................................................................................................................................... 18

2.1 OBJECTIVE................................................................................................................................................................. 18
2.2 PRE-LAB READING ...................................................................................................................................................... 18
2.3 EQUIPMENT/ SOFTWARE REQUIRED ............................................................................................................................... 18
2.4 INTRODUCTION .......................................................................................................................................................... 18
2.5 ACTIVITIES AND EXERCISES ........................................................................................................................................... 20
2.6 ASSESSMENT SHEET .................................................................................................................................................... 27

LAB-3: INPUT/OUTPUT PORT STRUCTURE OF PIC18 & I/O PORT PROGRAMMING USING ASSEMBLY LANGUAGE ... 28

3.1 OBJECTIVE................................................................................................................................................................. 28
3.2 PRE-LAB READING ...................................................................................................................................................... 28
3.3 EQUIPMENT/SOFTWARE REQUIRED ............................................................................................................................... 28
3.4 INTRODUCTION .......................................................................................................................................................... 28
3.5 ACTIVITIES AND EXERCISES ........................................................................................................................................... 31
3.6 ASSESSMENT SHEET .................................................................................................................................................... 31

LAB-4: LOOPS, DELAYS, AND SUBROUTINES: IMPLEMENTATION IN ASSEMBLY LANGUAGE .................................... 32

4.1 OBJECTIVE................................................................................................................................................................. 32
4.2 PRE-LAB READING ...................................................................................................................................................... 32
4.3 EQUIPMENT/SOFTWARE REQUIRED ............................................................................................................................... 32
4.4 INTRODUCTION .......................................................................................................................................................... 32
4.5 ACTIVITIES AND EXERCISES ........................................................................................................................................... 34
4.6 ASSESSMENT SHEET .................................................................................................................................................... 35

LAB-5: PIC PROGRAMMING USING EMBEDDED C & ASSEMBLY: PATTERNS, MASKING, AND MULTI STEPPER MOTORS
INTERFACING ........................................................................................................................................................... 36

5.1 OBJECTIVE................................................................................................................................................................. 36
5.2 PRE-LAB READING ...................................................................................................................................................... 36
5.3 EQUIPMENT/SOFTWARE REQUIRED ............................................................................................................................... 36
5.4 INTRODUCTION .......................................................................................................................................................... 36
5.5 ACTIVITIES AND EXERCISE ............................................................................................................................................. 38
5.6 ASSESSMENT SHEET .................................................................................................................................................... 40

LAB-6: INTERRUPTS PROGRAMMING IN PIC18 AND USE OF EXTERNAL INTERRUPTS AND IOC WITH IR SENSORS .... 41

6.1 OBJECTIVE................................................................................................................................................................. 41
6.2 PRE-LAB READING ...................................................................................................................................................... 41
6.3 EQUIPMENT/SOFTWARE REQUIRED ............................................................................................................................... 41
6.4 INTRODUCTION .......................................................................................................................................................... 41
6.5 ACTIVITIES AND EXERCISES ........................................................................................................................................... 45
6.6 ASSESSMENT SHEET .................................................................................................................................................... 46

EE 222L – Microprocessor Systems Lab Page 3


LAB-7: TIMERS/COUNTERS PROGRAMMING IN PIC18 FOR PRECISE DELAY & GENERATION OF MULTIPLE WAVEFORMS
................................................................................................................................................................................ 47

7.1 OBJECTIVE................................................................................................................................................................. 47
7.2 PRE-LAB READING ...................................................................................................................................................... 47
7.3 EQUIPMENT/SOFTWARE REQUIRED ............................................................................................................................... 47
7.4 INTRODUCTION .......................................................................................................................................................... 47
7.5 ACTIVITIES AND EXERCISES ........................................................................................................................................... 62
7.6 ASSESSMENT SHEET .................................................................................................................................................... 63

LAB-8: CCP AND PWM PROGRAMMING IN PIC18 FOR GENERATION OF PRECISE PWM WAVEFORMS ..................... 64

8.1 OBJECTIVE................................................................................................................................................................. 64
8.2 PRE-LAB READING ...................................................................................................................................................... 64
8.3 EQUIPMENT/SOFTWARE REQUIRED ............................................................................................................................... 64
8.4 INTRODUCTION .......................................................................................................................................................... 64
8.5 ACTIVITIES AND EXERCISES ........................................................................................................................................... 73
8.5 ASSESSMENT SHEET .................................................................................................................................................... 74

LAB-9: INTERNAL ADCC AND CWG FOR DC MOTOR SPEED, DIRECTION, AND POSITION CONTROL .......................... 75

9.1 OBJECTIVE................................................................................................................................................................. 75
9.2 PRE-LAB READING ...................................................................................................................................................... 75
9.3 EQUIPMENT/SOFTWARE REQUIRED ............................................................................................................................... 75
9.4 INTRODUCTION .......................................................................................................................................................... 75
9.5 ACTIVITIES AND EXERCISES ........................................................................................................................................... 92
9.6 ASSESSMENT SHEET .................................................................................................................................................... 93

LAB-10: ASYNCHRONOUS SERIAL COMMUNICATION WITH PIC18: UART MODULE WITH LCD INTERFACING ........... 94

10.1 OBJECTIVE............................................................................................................................................................... 94
10.2 PRE-LAB READING .................................................................................................................................................... 94
10.3 EQUIPMENT/SOFTWARE REQUIRED ............................................................................................................................. 94
10.4 INTRODUCTION ........................................................................................................................................................ 94
10.5 ACTIVITIES AND EXERCISES ....................................................................................................................................... 104
10.6 ASSESSMENT SHEET ................................................................................................................................................ 105

LAB-11: USING OTHER PERIPHERALS OF PIC18 INCLUDING DAC, COMPARATOR, ZCD, NCO, ETC. FOR VARIOUS
APPLICATIONS ....................................................................................................................................................... 106

11.1 OBJECTIVE............................................................................................................................................................. 106


11.2 PRE-LAB READING .................................................................................................................................................. 106
11.3 EQUIPMENT/SOFTWARE REQUIRED ........................................................................................................................... 106
11.4 INTRODUCTION ...................................................................................................................................................... 106
11.5 ACTIVITIES AND EXERCISE ......................................................................................................................................... 116
11.6 ASSESSMENT SHEET ................................................................................................................................................ 117

LAB-12: SYNCHRONOUS SERIAL COMMUNICATION (SPI/I2C) FOR EXTERNAL DEVICES INTERFACING WITH PIC18 . 118

12.1 OBJECTIVE............................................................................................................................................................. 118


12.2 PRE-LAB READING .................................................................................................................................................. 118
12.3 EQUIPMENT/SOFTWARE REQUIRED ........................................................................................................................... 118
12.4 INTRODUCTION ...................................................................................................................................................... 118
12.5 ACTIVITIES AND EXERCISE ......................................................................................................................................... 125
12.6 ASSESSMENT SHEET ................................................................................................................................................ 126

LAB-13: OPEN ENDED LAB ...................................................................................................................................... 127

13.1 OBJECTIVE............................................................................................................................................................. 127


13.2 PRE-LAB READING .................................................................................................................................................. 127

EE 222L – Microprocessor Systems Lab Page 4


13.3 EQUIPMENT/SOFTWARE REQUIRED ........................................................................................................................... 127
13.4 INTRODUCTION ...................................................................................................................................................... 127
13.5 ACTIVITIES AND EXERCISE ......................................................................................................................................... 129
13.6 ASSESSMENT SHEET ................................................................................................................................................ 130

EE 222L – Microprocessor Systems Lab Page 5


Instructions for Students
1. Attendance is mandatory for students in all the labs. If a student is absent from a lab due to any

reason, he/she will have to get written permission of the Dean to perform that lab. The Dean may

allow students to perform lab if he finds that the student has a genuine excuse.

2. Students should bring their textbooks to the lab, so that they can refer to theory, diagrams, and

instruction sets whenever required.

3. Labs will be graded in double entry fashion; one entry in the assessment sheet given at the end

of every lab and another entry in the instructor’s record. This system of keeping records will keep

students aware of their performance throughout the lab.

4. The assessment sheet at the end of every lab looks like the one presented at the following page.

EE 222L – Microprocessor Systems Lab Page 6


EE221L Microprocessor Systems Lab Evaluation Rubric

Student Name: ______________________ Reg. #: _________________

CLO & Excellent Good Satisfactory Poor Score


PLOs
Taxonomy 3.0—2.0 2.0—1.0 1.0--0 0
CLO-1
Can setup and Can setup and
P-3 Can independently Cannot setup or
handle the handle the
(Guided PLO-5 setup, operate and handle the
apparatus with apparatus with
Response) handle the apparatus apparatus
minimal help some help.
Apparatus Usage
Data recorded and Data recorded and
CLO-2
All required data is presented is presented is Data recorded
P-4
recorded and complete, but partially only with
(Mechanism)
PLO-5 presented accurately accuracy is not as complete. The considerable
Data Acquisition
and completely in per requirement. required format is assistance from
& Efficiency in
the required format The required followed but with instructor
System Usage
format is followed. few deficiencies.
Specifications, Specifications, Some
No specifications,
CLO-3 parameters, and parameters, and specifications,
parameters and
C-5 PLO-3 constraints of design constraints of parameters and
constraints of
(Evaluation) are completely design are partially constraints of
design are present
Design present present design are present
Analyzes data
CLO-4 Analyzes and Analyzes and
correctly however Unable to analyze
C-4 interprets data interprets data
unable to interpret and interpret data
(Analysis) PLO-4 correctly for all correctly for few
it for tasks/ for any tasks/
Data tasks/ experiments tasks/
experiments in experiments in lab
Interpretation in the lab experiments in lab
lab.
CLO-5
Student arrives
A3 Student arrives on
PLO-8 NA NA after 5 minutes of
(Valuing) time
lab timing
Punctuality
Total Score in Lab /

Instructor Signature: _________________

Date: _________________

EE 222L – Microprocessor Systems Lab Page 7


5. The tentative marks distribution for final grade is as follows:

• Lab Performance – 30%


• Mid Exam – 20%
• Project – 30%
• Open-Ended Lab/Final – 20%

CLO Course Learning Outcomes PLOs Blooms Taxonomy


To be able to use MPLAB IDE and PIC development
CLO-1 PLO-5 P.3 (Guided Response)
boards in an experiment.
To display expertise in using the system/setup and be
CLO-2 able to compare the actual output of PIC trainer boards PLO-5 P.4 (Mechanism)
with the expected results and Simulations
To design systems for real-world applications using
CLO-3 PLO-3 C.5 (Evaluation)
MPLAB IDE, PIC trainer board, and Interfacing Circuits
To analyze the output and results from physical
CLO-4 input/output of controllers on PIC trainer boards and PLO-4 C.4 (Analysis)
Simulations
CLO-5 To follow lab timings as per instructions PLO-8 A.3 (Valuing)
To use technical writing skills and prepare project reports
CLO-6 PLO-10 C.3 (Application)
in IEEE format.
To justify time and resource allocation to complete the
CLO-7 PLO-11 A.3 (Valuing)
assigned task

EE 222L – Microprocessor Systems Lab Page 8


PIC18 Enhanced Family Architecture

EE 222L – Microprocessor Systems Lab Page 9


Lab-1: Introduction to PIC Microcontroller Architecture and
MPLAB Integrated Development Environment (IDE)

1.1 Objective
• An introduction to MPLAB Integrated Development Environment (IDE).
• Brief overview of PIC18 Family RISC Architecture

1.2 Pre-Lab Reading


• Lab Manual
• PIC18F47K42 Instruction set from its datasheet.

1.3 Equipment/ Software Required


• MPLABX IDE

1.4 Introduction
The PIC18(L)F26/27/45/46/47/55/56/57K42 microcontrollers are available in 28/40/44/48-pin
devices. These devices feature a 12-bit ADC with Computation (ADC2) automating Capacitive
Voltage Divider (CVD) techniques for advanced touch sensing, averaging, filtering, oversampling
and threshold comparison, Temperature Sensor, Vectored Interrupt Controller with fixed latency for
handling interrupts, System Bus Arbiter, Direct Memory Access capabilities, UART with support
for Asynchronous, DMX, DALI and LIN transmissions, SPI, I2C, memory features like Memory
Access Partition (MAP) to support customers in data protection and bootloader applications, and
Device Information Area (DIA) which stores factory calibration values to help improve temperature
sensor accuracy.

EE 222L – Microprocessor Systems Lab Page 10


Core Features of PIC18F47K42:

• C Compiler Optimized RISC Architecture


• Operating Speed:
- Up to 64 MHz clock input
- 62.5 ns minimum instruction cycle
• Two Direct Memory Access (DMA) Controllers
- Data transfers to SFR/GPR spaces from either Program Flash Memory, Data
EEPROM or SFR/GPR spaces
- User-programmable source and destination sizes
- Hardware and software-triggered data transfers
• System Bus Arbiter with User-Configurable
Priorities for Scanner and DMA1/DMA2 with respect to the main line and interrupt
execution
• Vectored Interrupt Capability
- Selectable high/low priority
- Fixed interrupt latency
- Programmable vector table base address
• 31-Level Deep Hardware Stack
• Low-Current Power-on Reset (POR)
• Configurable Power-up Timer (PWRT)
• Brown-Out Reset (BOR)
• Low-Power BOR (LPBOR) Option
• Windowed Watchdog Timer (WWDT)
- Variable prescaler selection
- Variable window size selection
- Configurable in hardware or software

The standard PIC18 instruction set adds many enhancements to the previous PIC microcontroller
instruction sets, while maintaining an easy migration from these PIC microcontroller instruction sets.
Most instructions are a single program memory word (16 bits), but there are four instructions that
require two-program memory locations and two that require three-program memory locations.

Each single-word instruction is a 16-bit word divided into an opcode, which specifies the instruction
type and one or more operands, which further specify the operation of the instruction. The instruction
set is highly orthogonal and is grouped into four basic categories:

• Byte-oriented operations
• Bit-oriented operations
• Literal operations
• Control operations

For the instruction sets, please refer to the Datasheet of PIC 18F47K42.

EE 222L – Microprocessor Systems Lab Page 11


1.5 Activities and Exercises

The manual shows the steps for setting up a project in MPLAB IDE and writing a source code in
assembly language.

Steps
1- Open the MPLAB X IDE

2- Go to file in the menu bar and select New Project.

EE 222L – Microprocessor Systems Lab Page 12


MPLAB allows to use existing project files and libraries. To write a code from scratch, select
standalone project. Standalone Project creates a new standalone application project. It uses an
IDE-generated makefile to build your project.

3- After creating the standalone project, select the device you are using. In this lab we will be
using PIC18F47K42 which belongs to the advanced 8-bit PIC microprocessor family.

4- In the tool options, select simulator.

5- After selecting the tool, select the compiler you will be using. For assembly language, use the
mpasm compiler and for C language, use the XC8 compiler.

EE 222L – Microprocessor Systems Lab Page 13


We will be using the mpasm compiler for now.

6- Now just give the project a name and finish, we are good to go to write our first source code
on MPLAB.

7- After the project has been created, right click on the source files and select new file from the
menu and select other by expanding the project you have created. You can view your project
file in the project window tab which is on the left side by default.

EE 222L – Microprocessor Systems Lab Page 14


8- Now select assembler from the categories option and select the .asm file from the file types.

9- Give the file a name and finish to create the source file for this project.

10- Before writing the source code, we need to set the configuration bits for the microcontroller
which we are using. Configuration Bits are a collection of binary data located in the Flash
program memory of a PIC microcontroller. Configuration bits are programmed into the PIC
microcontroller with the application code. These bits are not executable code as their
addresses are not accessible by the program counter.

EE 222L – Microprocessor Systems Lab Page 15


The configuration bits needed to be set depend on the application of the program therefore
there is no absolute setting of these bits and they depend on the application. The lab instructor
will guide how to set these bits.

11- After setting the configuration bits, press the generate source code output button. This will
generate a source code for the configuration bits. Copy this code and paste it into source code
file.
12- Now all that’s left is to write the source code for the desired application and then compile it.
After the source code is compiled successfully, we can create its hex file. A hex file is a
hexadecimal source file typically used by programmable logic devices, such as
microcontrollers.
13- The procedure for creating the hex file will be conveyed by the lab instructor.
.

EE 222L – Microprocessor Systems Lab Page 16


1.6 Assessment Sheet
EE221L Microprocessor Systems Lab Evaluation Rubric
Student Name: ______________________ Reg. #: _________________

CLO & Excellent Good Satisfactory Poor Score


PLOs
Taxonomy 3.0—2.0 2.0—1.0 1.0--0 0
CLO-1
Can setup and Can setup and
P-3 Can independently Cannot setup or
handle the handle the
(Guided PLO-5 setup, operate and handle the
apparatus with apparatus with
Response) handle the apparatus apparatus
minimal help some help.
Apparatus Usage
CLO-5
Student arrives
A3 Student arrives on
PLO-8 NA NA after 5 minutes of
(Valuing) time
lab timing
Punctuality
Total Score in Lab /

Instructor Signature: _________________

Date: _________________

EE 222L – Microprocessor Systems Lab Page 17


Lab-2: Simulation of Basic Assembly Language Programs in
MPLAB IDE : Reading Register Status/Values

2.1 Objective
• Simulation of Assembly language code in MPLAB IDE and it’s deployment on PIC18

2.2 Pre-Lab Reading


PIC18 Basic Assembly language Instructions and it’s architecture.

2.3 Equipment/ Software Required


• MPLABX IDE

2.4 Introduction
The PIC microcontroller has many special function and general purpose registers in addition to the
WREG. They are either physically implemented or are mapped in the data memory space. The data
memory of PIC18 is read/write memory and is also referred to as file register in the PIC nomenclature
as only one register from data memory can be addressed at an instance.

Data memory in PIC18F26/27/45/46/47/55/56/57K42 devices is implemented as static RAM. Each


register in the data memory has a 14-bit address, allowing up to 16384 bytes of data memory. The
memory space is divided into 64 banks that contain 256 bytes each. Figure 4-3 shows the data
memory organization for the PIC18F26/27/45/46/47/55/56/57K42 devices in this data sheet.

The data memory contains Special Function Registers (SFRs) and General Purpose Registers
(GPRs). The SFRs are used for control and status of the controller and peripheral functions, while
GPRs are used for data storage and scratchpad operations in the user’s application. Any read of an
unimplemented location will read as ‘0’s. The instruction set and architecture allow operations across
all banks. The entire data memory may be accessed by Direct, Indirect or Indexed Addressing modes.
Addressing modes are discussed later in this subsection.

To ensure that commonly used registers (select SFRs and GPRs) can be accessed in a single cycle,
PIC18 devices implement an Access Bank. This is a 256-byte memory space that provides fast access
to some SFRs and the lower portion of GPR Bank 0 without using the Bank Select Register (BSR).
Section 4.5.4 “Access Bank” provides a detailed description of the Access RAM.

EE 222L – Microprocessor Systems Lab Page 18


GENERAL PURPOSE REGISTER FILE

General Purpose RAM is available starting Bank 0 of data memory. GPRs are not initialized by a
Power-on Reset and are unchanged on all other Resets.

SPECIAL FUNCTION REGISTERS

The Special Function Registers (SFRs) are registers used by the CPU and peripheral modules for
controlling the desired operation of the device. These registers are implemented as static RAM. SFRs
start at the top of data memory (3FFFh) and extend downward to occupy Bank 56 through 63 (3800h
to 3FFFh). A list of these registers is given in Table 4-3 to Table 4-11. A bitwise summary of these
registers can be found in Section 42.0 “Register Summary”.

EE 222L – Microprocessor Systems Lab Page 19


2.5 Activities and Exercises

The following show the steps to simulate the code in MPLAB IDE.

1. After creating a new project, set the configuration bits for pic18f47k42 and generate the
source code.

2. Copy the generated source code to the main program as header. This configures our PIC
microcontroller.

3. After you have written your code, debug the main project following the below steps. Create
a break point by at any valid instruction in your code line for the step wise debugging. The
keyboard shortcut key F8 is used for this purpose.

EE 222L – Microprocessor Systems Lab Page 20


4. Follow the below steps to locate the file registers and SFRs and check their respective values.

UPLOADING THE CODE TO THE BOARD (EASYPIC V8)


The tool that will be used to burn the code is CODEGRIP Suite.

STEPS:

EE 222L – Microprocessor Systems Lab Page 21


1. Open the CODEGRIP Suite.

2. Connect the board to your PC and press the power button. To successfully scan and detect the
board you will first need to update the firmware.

3. To update the firmware follow the following path, HELP>>>Updates>>>CODEGRIP.

You will be asked to power the board in the “boot loading mode”.

To enable the boot loader mode, turn off the board by pressing the power button, click on SCAN
DEVICES and power on the board again.

EE 222L – Microprocessor Systems Lab Page 22


Click on update firmware and then on START BOOTLOADING.

4. Now go to CODEGRIP>>> Scanning>>>SCAN DEVICES and press the port icon.

EE 222L – Microprocessor Systems Lab Page 23


5. Go to PIC18F47K42>>>Options >>>Select PIC18F47K42 in MCUS>>>Detect

6. Go to programming and upload the hex file of your project.

7. Finally click on WRITE to upload the code to the board.

EE 222L – Microprocessor Systems Lab Page 24


EE 222L – Microprocessor Systems Lab Page 25
LAB TASKS

1. Simulate the following code in MPLab IDE. Note down the values of the following registers in
the table given below:
ORG 00H

CLRF TRISA
CLRF TRISB

CLRF PORTA
CLRF PORTB

MOVLW 50H
MOVWF 00H
MOVLW 10H
MOVWF 01H
MOVLW 20H
ADDWF 0,0,0
MOVWF PORTA
ADDWF 1,0,0
MOVWF PORTB

END

Timing Cycle Mem 0x00 Mem 0x01 WREG PORTA PORTB

2. Copy the path of the hex file generated and import it in Code Grip Studio. Follow the instructions
to burn the code on EasyPIC V8 board. Comment on your output.

EE 222L – Microprocessor Systems Lab Page 26


2.6 Assessment Sheet
EE221L Microprocessor Systems Lab Evaluation Rubric

Student Name: ______________________ Reg. #: _________________

CLO & Excellent Good Satisfactory Poor Score


PLOs
Taxonomy 3.0—2.0 2.0—1.0 1.0--0 0
CLO-1
Can setup and Can setup and
P-3 Can independently Cannot setup or
handle the handle the
(Guided PLO-5 setup, operate and handle the
apparatus with apparatus with
Response) handle the apparatus apparatus
minimal help some help.
Apparatus Usage
Data recorded and Data recorded and
CLO-2
All required data is presented is presented is Data recorded
P-4
recorded and complete, but partially only with
(Mechanism)
PLO-5 presented accurately accuracy is not as complete. The considerable
Data Acquisition
and completely in per requirement. required format is assistance from
& Efficiency in
the required format The required followed but with instructor
System Usage
format is followed. few deficiencies.
CLO-5
Student arrives
A3 Student arrives on
PLO-8 NA NA after 5 minutes of
(Valuing) time
lab timing
Punctuality
Total Score in Lab /

Instructor Signature: _________________

Date: _________________

EE 222L – Microprocessor Systems Lab Page 27


Lab-3: Input/Output PORT Structure of PIC18 & I/O PORT
Programming using Assembly Language

3.1 Objective
• To familiarize the students with PORT structure of PIC18F47K42.
• Programming of the I/O ports of PIC18F47K42 using assembly language.
• Binary coded decimal number and Decimal Adjust command in PIC18
3.2 Pre-lab Reading
• Lab manual for Lab-3
• Chapter 16 of PIC18F47K42 Datasheet
• Chapter 41 of PIC18F47K42 Datasheet
• M. Ali Mazidi Textbook Chapter 4

3.3 Equipment/Software Required


• MPLABX IDE
• EASYPICv8 development board

3.4 Introduction
Binary Coded Decimal BCD Data Format:

Binary Coded Decimal, or BCD, is another process for converting decimal numbers into their
binary equivalents.

• It is a form of binary encoding where each digit in a decimal number is represented in


the form of bits.
• This encoding can be done in either 4-bit or 8-bit.

The BCD equivalent of a decimal number is written by replacing each decimal digit in the
integer and fractional parts with its four-bit binary equivalent. The BCD code is more precisely
known as 8421 BCD code, with 8,4,2 and 1 representing the weights of different bits in the four-
bit groups, Starting from MSB and proceeding towards LSB. This feature makes it a weighted
code, which means that each bit in the four-bit group representing a given decimal digit has an
assigned weight.

In the BCD numbering system, the given decimal number is segregated into chunks of four
bits for each decimal digit within the number. Each decimal digit is converted into its direct
binary form (usually represented in 4-bits).

For example:

D’123’ in BCD is 0001 0010 0011

EE 222L – Microprocessor Systems Lab Page 28


The number have to be adjusted and converted to a BCD number after any operation on the data
before displaying it on the PORT.

PIC18 has a built-in DAW (Decimal Adjust Working Register) command that works on the
result stored in the WREG after the command of “Addition” has been executed. Details of the
DAW command are presented below:

I/O PORTS:
PIC18F47K42 has five I/O ports that can be configured as Input or Output manually.
These ports are named PORT A, B, C, D and E.
Each port operation is controlled by using specific Special Function Registers (SFRs).

SFRs:
Special Function Registers are dedicated to specific functions such as ALU status, timers, serial
communication, I/O ports, ADC, and so on. The PIC18F47K42 SFRs are 8-bit registers and some of
the commonly used SFRs are explained below.

• PORTx Registers (Data Register):


Reading the PORTx register reads the status of the pins, whereas writing to it will write
to the corresponding PORT latch.
• TRISx Register (Data Direction):
Every PORTx register has a directional register TRISx associated with it. TRISx defines
the direction of the port (whether the PORT is an output port or input port). Setting TRISx
register will make PORTx an input port and clearing TRISx register will make PORTx
an output port.
For example,
CLRF TRISA makes PORTA an output port.
EE 222L – Microprocessor Systems Lab Page 29
• LATx Register (output latch):
LATx are the port latch registers. A write to the LAT register is the same as sending data
to the port. The contents of the port are contained inside the LAT register.
• ANSELx registers (analog select):
The ANSELx register is used to configure the Input mode of an I/O pin to analog. Setting
the appropriate ANSELx bit high will cause all digital reads on the pin to be read as ‘0’
and allow analog functions on the pin to operate correctly.
• SLRCONx Register (slew rate control):
The SLRCONx register controls the slew rate option for each port pin. Slew rate for each
port pin can be controlled independently. When an SLRCONx bit is set, the corresponding
port pin drive is slew rate limited. When an SLRCONx bit is cleared, the corresponding
port pin drive slews at the maximum rate possible.
• ODCONx register (open-drain control):
The ODCONx register controls the open-drain feature of the port. Open-drain operation
is independently selected for each pin. When an ODCONx bit is set, the corresponding
port output becomes an open-drain driver capable of sinking current only.
The address of these SFRs can be viewed from the datasheet. The memory banks allocated for SFRs
in PIC18F47K42 are from bank 52 to 63.

I/O PORT OPERATION:

The above figure explains how the data is being read from the port and vice versa. There is a data
register where the contents of the PORT are stored. There is a tristate buffer TRISx which controls
the direction of the port. The multiplexer allows the data to switch between analog and digital. The
data is stored in the Data Register on the rising or falling edge of the clock.

EE 222L – Microprocessor Systems Lab Page 30


3.5 Activities and Exercises

1. Write an assembly language code and test it on hardware to display the last two digits of your
registration number as BCD value on PORTD. The number should increment every time a push
button connected to RB0 is pressed. You have to decimal adjust the incremented number before
updating it to be displayed on the PORT.

3.6 Assessment Sheet

EE221L Microprocessor Systems Lab Evaluation Rubric

Student Name: ______________________ Reg. #: _________________

CLO & Excellent Good Satisfactory Poor Score


PLOs
Taxonomy 3.0—2.0 2.0—1.0 1.0--0 0
CLO-1
Can setup and Can setup and
P-3 Can independently Cannot setup or
handle the handle the
(Guided PLO-5 setup, operate and handle the
apparatus with apparatus with
Response) handle the apparatus apparatus
minimal help some help.
Apparatus Usage
Data recorded and Data recorded and
CLO-2
All required data is presented is presented is Data recorded
P-4
recorded and complete, but partially only with
(Mechanism)
PLO-5 presented accurately accuracy is not as complete. The considerable
Data Acquisition
and completely in per requirement. required format is assistance from
& Efficiency in
the required format The required followed but with instructor
System Usage
format is followed. few deficiencies.
CLO-5
Student arrives
A3 Student arrives on
PLO-8 NA NA after 5 minutes of
(Valuing) time
lab timing
Punctuality
Total Score in Lab /

Instructor Signature: _________________

Date: _________________

EE 222L – Microprocessor Systems Lab Page 31


Lab-4: Loops, Delays, and Subroutines: Implementation in
Assembly Language

4.1 Objective
• To familiarize the students with the concept of Loops, Delays and Subroutine in
PIC18F47K42.
• To write codes in assembly language to implement loops, subroutines, and delays in
Assembly Language

4.2 Pre-lab Reading


• Lab manual for Lab-4
• Chapter 41 of PIC18F47K42 Datasheet

4.3 Equipment/Software Required


• MPLAB X IDE
• EASYPICv8 development board

4.4 Introduction

A subroutine is a section of code, or program, then can be called as and when you need it. Subroutines
are used if you are performing the same function more than once, for example creating a delay. The
advantages of using a subroutine are that it will be easier to alter the value once inside a subroutine
rather than, say, ten times throughout your program, and it helps to reduce the amount of memory
your program occupies inside the PIC.

Let us look at a subroutine:

ROUTINE: MOVLW 255


MOVWF COUNT1
LABEL: DECFSZ COUNT1,1
GOTO LABEL
RETURN

First, we must give our subroutine a name, and in this case, we have chosen ROUTINE. We then
type the code that we want to perform as normal. Finally, we end the subroutine by typing the
RETURN instruction.

To start the subroutine from anywhere in our program, we simply type the instruction CALL followed
by the subroutine name.

EE 222L – Microprocessor Systems Lab Page 32


Let us look at this in slightly more detail. When we reach the part of our program that says CALL
xxx, where xxx is the name of our subroutine, the program jumps to wherever the subroutine xxx
resides. The instructions inside the subroutine are carried out. When the instruction RETURN is
reached, the program jumps back to our main program to the instruction immediately following our
CALL xxx instruction.

You can call the same subroutine as many times as you want, which is why using subroutines reduces
the overall length of our program. However, there are two things one must be aware of.

First, as in our main program, any constants must be declared before they are used. These can be
either declared within the subroutine itself, or right at the start of the main program. It is
recommended that one declares everything at the start of the main program. This reduces confusion
where constant declaration has been done.

Second, one must ensure that the main program skips over the subroutine. What is meant by this is
if the subroutine is placed right at the end of the main program, unless a ‘GOTO’ statement is used
to jump away from where the subroutine is, the program will carry on and execute the subroutine
whether it is desired to call it or not. The PIC does not differentiate between a subroutine and the
main program.

There are two methods to generate Delay in PIC Microcontroller:

• The first method is using built in timers in PIC 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.

Example:

MOVLW 100 ;needs 1 cycle.


MOVWF PORTB ;needs 1 cycle.
CALL DELAY ;needs 2 cycles.
GOTO LOOP ;needs 2 cycles.

EE 222L – Microprocessor Systems Lab Page 33


4.5 Activities and Exercises

1. Create a 1 second delay using assembly language nested loops.


2. Now, make a 24 Hour BCD 7-Segment Display based clock. First test your system using a 1
second delay for an actual clock and then reduce the delay to 0.01 seconds to test the complete
running of the 24 hour clock. Also comment how much time it will take to run through the full
24 hour cycle?

Perform your calculations for the analysis part of all above questions in the space given below:

EE 222L – Microprocessor Systems Lab Page 34


4.6 Assessment Sheet

EE221L Microprocessor Systems Lab Evaluation Rubric

Student Name: ______________________ Reg. #: _________________

CLO & Excellent Good Satisfactory Poor Score


PLOs
Taxonomy 3.0—2.0 2.0—1.0 1.0--0 0
CLO-1
Can setup and Can setup and
P-3 Can independently Cannot setup or
handle the handle the
(Guided PLO-5 setup, operate and handle the
apparatus with apparatus with
Response) handle the apparatus apparatus
minimal help some help.
Apparatus Usage
Data recorded and Data recorded and
CLO-2
All required data is presented is presented is Data recorded
P-4
recorded and complete, but partially only with
(Mechanism)
PLO-5 presented accurately accuracy is not as complete. The considerable
Data Acquisition
and completely in per requirement. required format is assistance from
& Efficiency in
the required format The required followed but with instructor
System Usage
format is followed. few deficiencies.
Analyzes data
CLO-4 Analyzes and Analyzes and
correctly however Unable to analyze
C-4 interprets data interprets data
unable to interpret and interpret data
(Analysis) PLO-4 correctly for all correctly for few
it for tasks/ for any tasks/
Data tasks/ experiments tasks/
experiments in experiments in lab
Interpretation in the lab experiments in lab
lab.
CLO-5
Student arrives
A3 Student arrives on
PLO-8 NA NA after 5 minutes of
(Valuing) time
lab timing
Punctuality
Total Score in Lab /

Instructor Signature: _________________

Date: _________________

EE 222L – Microprocessor Systems Lab Page 35


Lab-5: PIC Programming using Embedded C & Assembly:
Patterns, Masking, and Multi Stepper Motors Interfacing

5.1 Objective
• Develop understanding of PIC programming in embedded C
• To write codes in mixed embedded C and Assembly language to generate patterns and
masking of data.
• Use of data manipulation techniques in multiple stepper motor interfacing and control

5.2 Pre-lab Reading


• Lab manual for Lab-5
• Chapter 41 of PIC18F47K42 Datasheet
• Section 17.2 from PIC Microcontroller and Embedded Systems using Assembly and C
for PIC18 by M.A. Mazidi

5.3 Equipment/Software Required


• MPLAB X IDE
• EASYPICv8 development board
• Stepper Motors with Driver (Microcontroller Interfacing Board)

5.4 Introduction

Low-level language, Assembly, is fine for relatively simple programs but becomes time consuming
for more complex programs. In addition, assembly language is specific to a particular type of
processor and, therefore, not “portable. ” Another level of abstraction is needed, requiring a high-
level language.

C is becoming the language of choice for embedded systems, as memory capacity increases in
microcontrollers. Microchip supplies the 18 and 24 series chips specifically designed for C
programming. However, C can be used in the less complex 16 series PIC, as long as the applications
are relatively simple and therefore do not exceed the more limited memory capacity.

Multiplexing is technique used in PIC programming using a single port to drive multiple outputs
of such as multiple seven segments with a single port. The technique is based on the principle of
persistence of vision of human eyes. If the frame changes at rate greater than 25 fps, the human
eye can’t detect that visual change. Multiple seven segments can be turned on above 25 fps and
the human eye will think that display turned on for the whole time.

EE 222L – Microprocessor Systems Lab Page 36


The Stepper motor is a brushless DC motor that divides the full rotation angle of 360° into the
number of equal steps.

• The motor is rotated by applying a certain sequence of control signals. The speed of rotation
can be changed by changing the rate at which the control signals are applied.
• Various stepper motors with different step angles and torque ratings are available in the
market.
• A microcontroller can be used to apply different control signals to the motor to make it rotate
according to the need of an application.
STEPPER MOTORS AND INTERFACING IT USING PIC:
A stepper motor is a widely used device that translates electrical pulses into mechanical
movement. In applications such as disk drives, dot matrix printers, robotics etc. the stepper motor
is used for position control. Stepper motors commonly have a permanent magnet rotor
surrounded by a stator. There are also stepper motors called variable reluctance stepper motors
that do not have a permanent magnet rotor. The most common stepper motors have four stator
windings that are paired with a center-tapped common.

Figure 1: Stator Winding Configuration


This type of stepper motor is referred to as a unipolar stepper motor. The center tap allows a
change of current direction in each of the two coils when a winding is grounded, thereby resulting
in a polarity change of the stator. Unlike a conventional motor, the stepper motor shaft moves in
a fixed repeatable increment which allows one to move it to a precise position. This repeatable
fixed movement is possible as a result of basic magnetic theory where poles of the same polarity
repel and opposite poles attract. The direction of the rotation is dictated by the stator poles. The
stator poles are determined by the current sent through the wire coils. As the direction of the
current is changed, the polarity is also changed causing the reverse motion of the rotor. As a
sequence of power is applied through PIC microcontroller to each stator winding, the rotor will

EE 222L – Microprocessor Systems Lab Page 37


rotate. There are several widely used sequences each one having a different degree of precision.
The below table shows a two phase, four step winding sequence.

Clockwise Step # A B C D Counter-


clockwise
1 1 0 0 1

2 1 1 0 0

3 0 1 1 0

4 0 0 1 1

The microcontroller interfacing trainer board has a pre-built motor driver installed inside it. Only
the sequence is needed to be applied to rotate the motor. The sequence can be changed through
hard coding or the instruction “RRNCF” and “RLNCF”.

Below is sample code for generating a step pattern for a stepper motor through hard coding.

void main(void)
{
TRISD=0x00;
while(1
{
LATD = 0b00001100;
delay_ms(100);
LATD = 0b00000110;
delay_ms(100);
LATD = 0b00000011;
delay_ms(100);
LATD = 0b00001001;
delay_ms(100);
}
}

5.5 Activities and Exercise

1. Write a C language code with embedded assembly language rotate instructions and test it on
hardware to drive a stepper motor connected to PORTB of the microcontroller. First, rotate it
clockwise for a full 360-degree rotation that should take 10 seconds to complete. Then rotate it
in counterclockwise direction for 180 degrees (half cycle) that should take 3 seconds to complete.

EE 222L – Microprocessor Systems Lab Page 38


2. Develop a C language code with embedded assembly language rotate instructions and test it on
hardware to drive two stepper motors connected to the PORTD of the microcontroller. The aim
is to design a system such that the motors should rotate synchronously to draw a triangle as per
specifications given in the figure below if connected to a 2D CNC stage. Assume that each step
of the motor is translated into 0.1 mm in linear motion of the stage.

Perform your calculations for the analysis part of all above questions in the space given below:

EE 222L – Microprocessor Systems Lab Page 39


5.6 Assessment Sheet

EE221L Microprocessor Systems Lab Evaluation Rubric

Student Name: ______________________ Reg. #: _________________

CLO & Excellent Good Satisfactory Poor Score


PLOs
Taxonomy 3.0—2.0 2.0—1.0 1.0--0 0
CLO-1
Can setup and Can setup and
P-3 Can independently Cannot setup or
handle the handle the
(Guided PLO-5 setup, operate and handle the
apparatus with apparatus with
Response) handle the apparatus apparatus
minimal help some help.
Apparatus Usage
Data recorded and Data recorded and
CLO-2
All required data is presented is presented is Data recorded
P-4
recorded and complete, but partially only with
(Mechanism)
PLO-5 presented accurately accuracy is not as complete. The considerable
Data Acquisition
and completely in per requirement. required format is assistance from
& Efficiency in
the required format The required followed but with instructor
System Usage
format is followed. few deficiencies.
Specifications, Specifications, Some
No specifications,
CLO-3 parameters, and parameters, and specifications,
parameters and
C-5 PLO-3 constraints of design constraints of parameters and
constraints of
(Evaluation) are completely design are partially constraints of
design are present
Design present present design are present
Analyzes data
CLO-4 Analyzes and Analyzes and
correctly however Unable to analyze
C-4 interprets data interprets data
unable to interpret and interpret data
(Analysis) PLO-4 correctly for all correctly for few
it for tasks/ for any tasks/
Data tasks/ experiments tasks/
experiments in experiments in lab
Interpretation in the lab experiments in lab
lab.
CLO-5
Student arrives
A3 Student arrives on
PLO-8 NA NA after 5 minutes of
(Valuing) time
lab timing
Punctuality
Total Score in Lab /

Instructor Signature: _________________

Date: _________________

EE 222L – Microprocessor Systems Lab Page 40


Lab-6: Interrupts Programming in PIC18 and Use of External
Interrupts and IOC with IR Sensors

6.1 Objective
• Understanding of Interrupts and Interrupt Sources in PIC18
• Understanding of External Interrupts and Interrupt-on-Change Features
• Use of External and IOC with sensor interfacing for various applications

6.2 Pre-lab Reading


• Lab manual for Lab-6
• Chapter 41 of PIC18F47K42 Datasheet
• Chapter 9 of PIC18F47K42 Datasheet
• Chapter 17 of PIC18F47K42 Datasheet
• M. Ali Mazidi Textbook Chapter 11

6.3 Equipment/Software Required


• MPLAB X IDE
• EASYPICv8 development board
• IR Sensors and Push Buttons

6.4 Introduction

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

There are two Interrupt Service Routines (ISR) for the interrupts in PIC. One is low_ISR (vector
address 0x018) for low priority interrupts and the other one is high_ISR (vector address 0x008) for
high priority interrupts. If no priority is set for any interrupt or just one interrupt is being used, we
can use the general ISR without mentioning high or low. User has to check manually using the
Interrupt Indicating Flags within the ISR that which interrupt has caused the program to jump to ISR.

The format for writing the ISR is shown below in the sample code.

void __interrupt () ISR(void)


{
if(INT0IF == 1)
PORTD = 0xFF;
INT0IF = 0;
}
void main(void)

EE 222L – Microprocessor Systems Lab Page 41


{
TRISD = 0;
TRISB0 = 1;
ANSELB0 = 0;
INT0PPS = 0B00001000;
GIE = 1;
INT0IE = 1;
while(1);
}

In the above code, whenever an interrupt is made on external peripheral pin, the flag will be raised
and the program will jump to ISR. The bits, INT0IE must be set first to enable the interrupt flags.
The bit GIE is the global interrupt enable bit which unmasks all interrupts. The register INT0PPS
selects the bit RB0 for INT0.

INTERRUPT ENABLES AND INTERRUPT FLAGS:


The interrupts by default are set off. The enable bit of the corresponding interrupt is needed to be set
to check for that interrupt. For example, the enable bit INT0IE when set to high will enable the
interrupt INT0. When any interrupt occurs, the flag corresponding to that interrupt if it has been
enabled will be set to 1, for example if an interrupt because of INT0, the flag INT0IF will be set
high. While there isn’t an interrupt, the flag is set to 0. When an interrupt flag is raised, the interrupt
will go to the ISR and execute it, while the flag wasn’t raised, the pic was allowed to keep responding
to the interrupts. As soon as the flag was set high, it will respond to that interrupt and then go back
to the main program. One important point to note is that the after the ISR is executed, the PIC will
not set the flag low automatically. To use that interrupt again, the user must manually set the flag
low through software.

PERIPHERAL PIN SELECT (PPS):


The Peripheral Pin Select (PPS) module connects peripheral inputs and outputs to the device I/O
pins. Only digital signals are included in the selections. All analog inputs and output remain fixed to
their assigned pins. Input and output selections are independent.

PPS INPUT:
Each peripheral has a PPS register with which the inputs to the peripheral are selected. Inputs include
the device pins. Multiple peripherals can operate from the same source simultaneously. Port reads
always return the pin level regardless of peripheral PPS selection. If a pin also has analog functions
associated, the ANSEL bit for that pin must be cleared to enable the digital input buffer. Although
every peripheral has its own PPS input selection register, the selections are identical for every
peripheral.

EE 222L – Microprocessor Systems Lab Page 42


bit 7-6 Unimplemented: Read as ‘0’
bit 5-3 xxxPPS<5:3>: Peripheral xxx Input PORTx Pin Selection bits
101 = PORTF(2)
100 = PORTE(3)
011 = PORTD(3)
010 = PORTC
001 = PORTB
000 = PORTA
bit 2-0 xxxPPS<2:0>: Peripheral xxx Input PORTx Pin Selection bits
111 = Peripheral input is from PORTx Pin 7 (Rx7)
110 = Peripheral input is from PORTx Pin 6 (Rx6)
101 = Peripheral input is from PORTx Pin 5 (Rx5)
100 = P eripheral input is from PORTx Pin 4 (Rx4)
011 = Peripheral input is from PORTx Pin 3 (Rx3)
010 = Peripheral input is from PORTx Pin 2 (Rx2)
001 = Peripheral input is from PORTx Pin 1 (Rx1)
000 = Peripheral input is from PORTx Pin 0 (Rx0)

The notation “xxx” in the register name is a place holder for the peripheral identifier. For example,
setting INT0PPS = 00001101 selects bit R5 of PORTB for INT0. For the list of available ports and
default pin locations, refer table 17-1 of the datasheet.

PPS OUTPUT:
Each I/O pin has a PPS register with which the pin output source is selected. With few exceptions,
the port TRIS control associated with that pin retains control over the pin output driver. Peripherals
that control the pin output driver as part of the peripheral operation will

override the TRIS control as needed.

bit 7-6 Unimplemented: Read as ‘0’

EE 222L – Microprocessor Systems Lab Page 43


bit 5-0 RxyPPS<5:0>: Pin Rxy Output Source Selection bits

For the list of available ports, refer to table 17-2 of the datasheet.

SOURCES OF INTERRUPTS:
There are many sources of interrupts in the PIC 18, depending which peripheral is incorporated into
the chip. The following are some of the most widely used sources of interrupts in the PIC18 family:

1- Timer Interrupts.
2- Interrupt on change at Ports.
3- ADC interrupt.
4- CCP interrupt.
5- External Hardware interrupts.
6- Serial communication interrupts

REGISTERS ASSOCIATED WITH INTERRUPT CONTROLLER:


The devices in this family implement the following registers for the interrupt controller:
• INTCON0, INTCON1 Control Registers
• PIRx – Peripheral Interrupt Status Registers
• PIEx – Peripheral Interrupt Enable Registers
• IPRx – Peripheral Interrupt Priority Registers
• IVTBASE<20:0> Address Registers
• IVTLOCK Register
Global interrupt control functions and external interrupts are controlled from the INTCON0
register. The INTCON1 register contains the status flags for the Interrupt controller.
The PIRx registers contain all of the interrupt request flags. Each source of interrupt has a status
bit, which is set by the respective peripherals or an external signal and is cleared via software.
The PIEx registers contain all of the interrupt enable bits. These control bits are used to
individually enable interrupts from the peripherals or external signals.
The IPRx registers are used to set the Interrupt Priority Level for each source of interrupt. Each
user interrupt source can be assigned to either a high or low priority.
The IVTBASE register is user programmable and is used to determine the start address of the
Interrupt Vector Table and the IVTLOCK register is used to prevent any unintended writes to the
IVTBASE register.
There are two other configuration bits that control the way the interrupt controller can be
configured.

• CONFIG2L<3>, MVECEN bit


• CONFIG2L<4>, IVT1WAY bit

The MVECEN bit in CONFIG2L determines whether the Vector table is used to determine the
interrupt priorities.

EE 222L – Microprocessor Systems Lab Page 44


IR Sensors:
An infrared (IR) sensor is an electronic device that measures and detects infrared radiation in its
surrounding environment. There are two types of infrared sensors: active and passive. Active
infrared sensors both emit and detect infrared radiation. Active IR sensors have two parts: a light
emitting diode (LED) and a receiver. When an object comes close to the sensor, the infrared light
from the LED reflects off of the object and is detected by the receiver. Active IR sensors act
as proximity sensors, and they are commonly used in obstacle detection systems (such as in robots).

6.5 Activities and Exercises

1. Design a system to count the number of people entering and leaving a room using two IR sensors
at the gate. Use this data to turn the lights ON if anyone is inside the room and turn them OFF
when the room is empty. Also, light and LED indicating that the room is full when 20 people are
inside. Use both the sensors connected to the two external interrupts to perform the task.

2. Design a fan speed control system that uses one push button to control the speed of fan. When
the button is pressed once, the fab turns on with 30% speed. When pressed again (2nd time), the
fan runs at 60%, for the third press, the speed is 100%, and for the 4th press, the fan is turned off.
The cycle repeats indefinitely. Implement the system both with and without using external
interrupt to take button input.

Perform your calculations for the analysis part of all above questions in the space given below:

EE 222L – Microprocessor Systems Lab Page 45


6.6 Assessment Sheet

EE221L Microprocessor Systems Lab Evaluation Rubric

Student Name: ______________________ Reg. #: _________________

CLO & Excellent Good Satisfactory Poor Score


PLOs
Taxonomy 3.0—2.0 2.0—1.0 1.0--0 0
CLO-1
Can setup and Can setup and
P-3 Can independently Cannot setup or
handle the handle the
(Guided PLO-5 setup, operate and handle the
apparatus with apparatus with
Response) handle the apparatus apparatus
minimal help some help.
Apparatus Usage
Data recorded and Data recorded and
CLO-2
All required data is presented is presented is Data recorded
P-4
recorded and complete, but partially only with
(Mechanism)
PLO-5 presented accurately accuracy is not as complete. The considerable
Data Acquisition
and completely in per requirement. required format is assistance from
& Efficiency in
the required format The required followed but with instructor
System Usage
format is followed. few deficiencies.
Specifications, Specifications, Some
No specifications,
CLO-3 parameters, and parameters, and specifications,
parameters and
C-5 PLO-3 constraints of design constraints of parameters and
constraints of
(Evaluation) are completely design are partially constraints of
design are present
Design present present design are present
Analyzes data
CLO-4 Analyzes and Analyzes and
correctly however Unable to analyze
C-4 interprets data interprets data
unable to interpret and interpret data
(Analysis) PLO-4 correctly for all correctly for few
it for tasks/ for any tasks/
Data tasks/ experiments tasks/
experiments in experiments in lab
Interpretation in the lab experiments in lab
lab.
CLO-5
Student arrives
A3 Student arrives on
PLO-8 NA NA after 5 minutes of
(Valuing) time
lab timing
Punctuality
Total Score in Lab /

Instructor Signature: _________________

Date: _________________

EE 222L – Microprocessor Systems Lab Page 46


Lab-7: Timers/Counters Programming in PIC18 for Precise
Delay & Generation of Multiple Waveforms

7.1 Objective
• To explain Timers and Counters to the students
• Understanding the features and settings of different types of Timer peripherals available in PIC18
• Use of Timers/Counters in creating delay and Counting Events

7.2 Pre-Lab Reading


• Lab manual for Lab-7
• PIC18F47K42 Datasheet Chapter 20, 21, 22
• M. Ali Mazidi Textbook Chapter 9

7.3 Equipment/Software Required


• MPLAB X IDE
• EASYPICv8 development board
• Oscilloscope

7.4 Introduction

PIC18F47K42 has 7 independent timer modules. They are further divided into three types with
Timer 0 in type-1, Timers 1/3/5 in type-2, and Timers 2/4/6 in type-3.

TIMER0 MODULE:

Timer0 module is an 8/16-bit timer/counter with the


following features:
• 16-bit timer/counter
• 8-bit timer/counter with programmable period
• Synchronous or asynchronous operation
• Selectable clock sources
• Programmable prescaler
• Programmable postscaler
• Operation during Sleep mode
• Interrupt on match or overflow
• Output on I/O pin (via PPS) or to other peripherals

EE 222L – Microprocessor Systems Lab Page 47


Timer0 can operate as either an 8-bit timer/counter or a 16-bit timer/counter. The mode is selected
with the MD16 bit of the T0CON register.
16-BIT MODE
The register pair TMR0H:TMR0L increments on the rising edge of the clock source. A 15-bit
prescaler on the clock input gives several prescale options (see prescaler control bits, CKPS[3:0] in
the T0CON1 register)
Timer0 Reads and Writes in 16-Bit Mode
In 16-bit mode, in order to avoid rollover between reading high and low registers, the TMR0H
register is a buffered copy of the actual high byte of Timer0, which is neither directly readable, nor
writable (see Figure 20- 1). TMR0H is updated with the contents of the high byte of Timer0 during
a read of TMR0L. This provides the ability to read all 16 bits of Timer0 without having to verify that
the read of the high and low byte was valid, due to a rollover between successive reads of the high
and low byte.
Similarly, a write to the high byte of Timer0 must also take place through the TMR0H Buffer register.
The high byte is updated with the contents of TMR0H when a write occurs to TMR0L. This allows
all 16 bits of Timer0 to be updated at once.
8-BIT MODE
In 8-bit mode, the value of TMR0L is compared to that of the Period buffer, a copy of TMR0H, on
each clock cycle. When the two values match, the following events happen:
• TMR0_out goes high for one prescaled clock period
• TMR0L is reset
• The contents of TMR0H are copied to the period buffer
In 8-bit mode, the TMR0L and TMR0H registers are both directly readable and writable. The
TMR0L register is cleared on any device Reset, while the TMR0H register initializes at FFh.
COUNTER MODE
In Counter mode, the prescaler is normally disabled by setting the CKPS bits of the T0CON1 register
to ‘0000’. Each rising edge of the clock input (or the output of the prescaler if the prescaler is used)
increments the counter by ‘1’.
TIMER MODE
In Timer mode, the Timer0 module will increment every instruction cycle as long as there is a valid
clock signal and the CKPS bits of the T0CON1 register (Register 20-2) are set to ‘0000’. When a
prescaler is added, the timer will increment at the rate based on the prescaler value.

EE 222L – Microprocessor Systems Lab Page 48


ASYNCHRONOUS MODE
When the ASYNC bit of the T0CON1 register is set (ASYNC = ‘1’), the counter increments with
each rising edge of the input source (or output of the prescaler, if used). Asynchronous mode allows
the counter to continue operation during Sleep mode provided that the clock also continues to operate
during Sleep.
SYNCHRONOUS MODE
When the ASYNC bit of the T0CON1 register is clear (ASYNC = ‘0’), the counter clock is
synchronized to the system clock (FOSC/4). When operating in Synchronous mode, the counter clock
frequency cannot exceed FOSC/4.
Clock Source Selection
The CS[2:0] bits of the T0CON1 register are used to select the clock source for Timer0. Register 20-
2 displays the clock source selections.
INTERNAL CLOCK SOURCE
When the internal clock source is selected, Timer0 operates as a timer and will increment on
multiples of the clock source, as determined by the Timer0 prescaler.
EXTERNAL CLOCK SOURCE
When an external clock source is selected, Timer0 can operate as either a timer or a counter. Timer0
will increment on multiples of the rising edge of the external clock source, as determined by the
Timer0 prescaler.

EE 222L – Microprocessor Systems Lab Page 49


EE 222L – Microprocessor Systems Lab Page 50
TIMER1/3/5 MODULE WITH GATE CONTROL:

Timer1/3/5 module is a 16-bit timer/counter with the following features:


• 16-bit timer/counter register pair (TMRxH:TMRxL)
• Programmable internal or external clock source
• 2-bit prescaler
• Dedicated Secondary 32 kHz oscillator circuit
• Optionally synchronized comparator out
• Multiple Timer1/3/5 gate (count enable) sources
• Interrupt on overflow
• Wake-up on overflow (external clock, Asynchronous mode only)
• 16-Bit Read/Write Operation
• Time base for the Capture/Compare function with the CCP modules
• Special Event Trigger (with CCP)
• Selectable Gate Source Polarity
• Gate Toggle mode

EE 222L – Microprocessor Systems Lab Page 51


• Gate Single-pulse mode
• Gate Value Status
• Gate Event Interrupt

Timer1/3/5 Operation
The Timer1/3/5 module is a 16-bit incrementing counter which is accessed through the
TMRxH:TMRxL register pair. Writes to TMRxH or TMRxL directly update the counter.
When used with an internal clock source, the module is a timer and increments on every instruction
cycle. When used with an external clock source, the module can be used as either a timer or counter
and increments on every selected edge of the external source.
Timer1/3/5 is enabled by configuring the ON and GE bits in the TxCON and TxGCON registers,
respectively.

EE 222L – Microprocessor Systems Lab Page 52


EE 222L – Microprocessor Systems Lab Page 53
EE 222L – Microprocessor Systems Lab Page 54
EE 222L – Microprocessor Systems Lab Page 55
TIMER2/4/6 MODULE
The Timer2/4/6 modules are 8-bit timers that can operate as free-running period counters or in
conjunction with external signals that control start, run, freeze, and reset operation in One-Shot and
Monostable modes of operation. Sophisticated waveform control such as pulse density modulation
are possible by combining the operation of these timers with other internal peripherals such as the
comparators and CCP modules. Features of the timer include:
• 8-bit timer register
• 8-bit period register
• Selectable external hardware timer resets
• Programmable prescaler (1:1 to 1:128)
• Programmable postscaler (1:1 to 1:16)
• Selectable synchronous/asynchronous operation
• Alternate clock sources
• Interrupt on period
EE 222L – Microprocessor Systems Lab Page 56
EE 222L – Microprocessor Systems Lab Page 57
EE 222L – Microprocessor Systems Lab Page 58
EE 222L – Microprocessor Systems Lab Page 59
EE 222L – Microprocessor Systems Lab Page 60
EE 222L – Microprocessor Systems Lab Page 61
7.5 Activities and Exercises

1. Write a program to create delay of 1 sec using Timer 1 interrupt and blink all LEDs of PORTD.
2. Write a program to use Timer 0 in 8-bit period mode and generate a waveform of 1 kHz frequency
at RD0. Use timer interrupt to generate the waveform when the match occurs.
3. Write a program to generate the following waveforms simultaneously using timers and interrupts:
RD0: Frequency 100 Hz, Duty cycle 30%
RD1: Frequency 1 kHz, Duty cycle 45%
RD2: Frequency 10 kHz, Duty cycle 60%
RD3: Frequency 100 kHz, Duty cycle 75%
Perform your calculations for the analysis part of all above questions in the space given below:

EE 222L – Microprocessor Systems Lab Page 62


7.6 Assessment Sheet

EE221L Microprocessor Systems Lab Evaluation Rubric

Student Name: ______________________ Reg. #: _________________

CLO & Excellent Good Satisfactory Poor Score


PLOs
Taxonomy 3.0—2.0 2.0—1.0 1.0--0 0
CLO-1
Can setup and Can setup and
P-3 Can independently Cannot setup or
handle the handle the
(Guided PLO-5 setup, operate and handle the
apparatus with apparatus with
Response) handle the apparatus apparatus
minimal help some help.
Apparatus Usage
Data recorded and Data recorded and
CLO-2
All required data is presented is presented is Data recorded
P-4
recorded and complete, but partially only with
(Mechanism)
PLO-5 presented accurately accuracy is not as complete. The considerable
Data Acquisition
and completely in per requirement. required format is assistance from
& Efficiency in
the required format The required followed but with instructor
System Usage
format is followed. few deficiencies.
Analyzes data
CLO-4 Analyzes and Analyzes and
correctly however Unable to analyze
C-4 interprets data interprets data
unable to interpret and interpret data
(Analysis) PLO-4 correctly for all correctly for few
it for tasks/ for any tasks/
Data tasks/ experiments tasks/
experiments in experiments in lab
Interpretation in the lab experiments in lab
lab.
CLO-5
Student arrives
A3 Student arrives on
PLO-8 NA NA after 5 minutes of
(Valuing) time
lab timing
Punctuality
Total Score in Lab /

Instructor Signature: _________________

Date: _________________

EE 222L – Microprocessor Systems Lab Page 63


Lab-8: CCP and PWM Programming in PIC18 for Generation
of Precise PWM waveforms

8.1 Objective
• To develop understanding of Capture Compare PWM (CCP) Modules
• To develop understanding of dedicated PWM Peripherals
• Understanding the features and settings of CCP and PWM Modules
• Use of CCP and PWM Peripherals in applications requiring multiple simultaneous waveforms

8.2 Pre-Lab Reading


• Lab manual for Lab-8
• PIC18F47K42 Datasheet Chapter 23, 24
• M. Ali Mazidi Textbook Chapter 15

8.3 Equipment/Software Required


• MPLAB X IDE
• EASYPICv8 development board
• Oscilloscope

8.4 Introduction

The Capture/Compare/PWM module is a peripheral that allows the user to time and control different
events, and to generate Pulse-Width Modulation (PWM) signals. In Capture mode, the peripheral
allows the timing of the duration of an event. The Compare mode allows the user to trigger an external
event when a predetermined amount of time has expired. The PWM mode can generate pulse-width
modulated signals of varying frequency and duty cycle.
This family of devices contains four standard Capture/ Compare/PWM modules (CCP1, CCP2,
CCP3 and CCP4). Each individual CCP module can select the timer source that controls the module.
Each module has an independent timer selection which can be accessed using the CxTSEL bits in
the CCPTMRS register (Register 23-2). The default timer selection is TMR1 when using
Capture/Compare mode and TMR2 when using PWM mode in the CCPx module.
Please note that the Capture/Compare mode operation is described with respect to TMR1 and the
PWM mode operation is described with respect to TMR2 in the following sections.
The Capture and Compare functions are identical for all CCP modules.

CCP Module Configuration


Each Capture/Compare/PWM module is associated with a control register (CCPxCON), a capture
input selection register (CCPxCAP) and a data register (CCPRx). The data register, in turn, is
comprised of two 8-bit registers: CCPRxL (low byte) and CCPRxH (high byte).
CCP MODULES AND TIMER RESOURCES
The CCP modules utilize Timers 1 through 6 that vary with the selected mode. Various timers are
available to the CCP modules in Capture, Compare or PWM modes, as shown in Table below.

EE 222L – Microprocessor Systems Lab Page 64


The assignment of a particular timer to a module is determined by the timer to CCP enable bits in
the CCPTMRS register. All of the modules may be active at once and may share the same timer
resource if they are configured to operate in the same mode (Capture/Compare or PWM) at the same
time.

Capture Mode
Capture mode makes use of the 16-bit Timer1 resource. When an event occurs on the capture source,
the 16-bit CCPRxH:CCPRxL register pair captures and stores the 16-bit value of the
TMRxH:TMRxL register pair, respectively. An event is defined as one of the following and is
configured by the MODE[3:0] bits of the CCPxCON register:

• Every falling edge of CCPx input


• Every rising edge of CCPx input
• Every 4th rising edge of CCPx input
• Every 16th rising edge of CCPx input
• Every edge of CCPx input (rising or falling)

When a capture is made, the Interrupt Request Flag bit CCPxIF of the respective PIR register is set.
The interrupt flag must be cleared in software. If another capture occurs before the value in the
CCPRxH:CCPRxL register pair is read, the old captured value is overwritten by the new captured
value.

Compare Mode
Compare mode makes use of the 16-bit Timer1 resource. The 16-bit value of the CCPRxH:CCPRxL
register pair is constantly compared against the 16-bit value of the TMRxH:TMRxL register pair.
When a match occurs, one of the following events can occur:

EE 222L – Microprocessor Systems Lab Page 65


• Toggle the CCPx output, clear TMRx
• Toggle the CCPx output
• Set the CCPx output
• Clear the CCPx output
• Pulse output
• Pulse output, clear TMRx

The action on the pin is based on the value of the MODE[3:0] control bits of the CCPxCON register.
At the same time, the interrupt flag CCPxIF bit is set, and an ADC conversion can be triggered, if
selected. All Compare modes can generate an interrupt and trigger an ADC conversion. When MODE
= 0b0001 or 0b1011, the CCP resets the TMR register pair.

PWM Overview
Pulse-Width Modulation (PWM) is a scheme that provides power to a load by switching quickly
between fully ON and fully OFF states. The PWM signal resembles a square wave where the high
portion of the signal is considered the ON state and the low portion of the signal is considered the
OFF state. The high portion, also known as the pulse width, can vary in time and is defined in steps.
A larger number of steps applied, which lengthens the pulse width, also supplies more power to the
load. Lowering the number of steps applied, which shortens the pulse width, supplies less power.
The PWM period is defined as the duration of one complete cycle or the total amount of on and off
time combined.
PWM resolution defines the maximum number of steps that can be present in a single PWM period.
A higher resolution allows for more precise control of the pulsewidth time and in turn the power that
is applied to the load.
The term duty cycle describes the proportion of the on time to the off time and is expressed in
percentages, where 0% is fully off and 100% is fully on. A lower duty cycle corresponds to less
power applied and a higher duty cycle corresponds to more power applied.

EE 222L – Microprocessor Systems Lab Page 66


STANDARD PWM OPERATION
The standard PWM mode generates a Pulse-Width Modulation (PWM) signal on the CCPx pin with
up to ten bits of resolution. The period, duty cycle, and resolution are controlled by the following
registers:
• T2PR registers
• T2CON registers
• CCPRxL and CCPRxH registers
• CCPxCON registers
It is required to have FOSC/4 as the clock input to TMR2/4/6 for correct PWM operation.

SETUP FOR PWM OPERATION


The following steps should be taken when configuring the CCP module for standard PWM operation:
1. Use the desired output pin RxyPPS control to select CCPx as the source and disable the CCPx pin
output driver by setting the associated TRIS bit.
2. Load the T2PR register with the PWM period value.
3. Configure the CCP module for the PWM mode by loading the CCPxCON register with the
appropriate values.
4. Load the CCPRxL register, and the CCPRxH register with the PWM duty cycle value and
configure the FMT bit of the CCPxCON register to set the proper register alignment.
5. Configure and start Timer2:
• Clear the TMR2IF interrupt flag bit of the respective PIR register.
• Select the timer clock source to be as FOSC/4 using the T2CLK register. This is required
for correct operation of the PWM module.
• Configure the CKPS bits of the T2CON register with the Timer prescale value.
• Enable the Timer by setting the ON bit of the T2CON register.
6. Enable PWM output pin:
• Wait until the Timer overflows and the TMR2IF bit of the PIR4 register is set.

EE 222L – Microprocessor Systems Lab Page 67


• Enable the CCPx pin output driver by clearing the associated TRIS bit.

EE 222L – Microprocessor Systems Lab Page 68


EE 222L – Microprocessor Systems Lab Page 69
PULSE-WIDTH MODULATION (PWM)
The PWM module generates a pulse-width modulated signal determined by the duty cycle, period,
and resolution that are configured by the following registers:
• TxPR
• TxCON
• PWMxDCH
• PWMxDCL
• PWMxCON
Each PWM module can select the timer source that controls the module. Each module has an
independent timer selection which can be accessed using the CCPTMRS1 register (Register 23-2).
Please note that the PWM mode operation is described with respect to T2TMR in the following
sections.
PWMx Pin Configuration
All PWM outputs are multiplexed with the PORT data latch. The user must configure the pins as
outputs by clearing the associated TRIS bits.
FUNDAMENTAL OPERATION
The PWM module produces a 10-bit resolution output. The PWM timer can be selected using the
PxTSEL bits in the CCPTMRS1 register. The default selection for PWMx is T2TMR. Please note
that the PWM module operation in the following sections is described with respect to T2TMR.
Timer2 and T2PR set the period of the PWM. The PWMxDCL and PWMxDCH registers configure
the duty cycle. The period is common to all PWM modules, whereas the duty cycle is independently
controlled.
All PWM outputs associated with Timer2 are set when T2TMR is cleared. Each PWMx is cleared
when T2TMR is equal to the value specified in the corresponding PWMxDCH (8 MSb) and
PWMxDCL[7:6] (2 LSb) registers. When the value is greater than or equal to T2PR, the PWM output
is never cleared (100% duty cycle).

SETUP FOR PWM OPERATION USING PWMx PINS


The following steps should be taken when configuring the module for PWM operation using the
PWMx pins:
1. Disable the PWMx pin output driver(s) by setting the associated TRIS bit(s).
2. Clear the PWMxCON register.
3. Load the T2PR register with the PWM period value.
4. Load the PWMxDCH register and bits [7:6] of the PWMxDCL register with the PWM duty cycle
value.
EE 222L – Microprocessor Systems Lab Page 70
5. Configure and start Timer2:
• Clear the TMR2IF interrupt flag bit of the respective PIR register. See Note 1 below.
• Select the timer clock source to be as FOSC/4 using the TxCLK register. This is required for correct
operation of the PWM module.
• Configure the CKPS bits of the T2CON register with the Timer2 prescale value.
• Enable Timer2 by setting the ON bit of the T2CON register.
6. Enable PWM output pin and wait until Timer2 overflows, TMR2IF bit of the respective PIR
register is set.
7. Enable the PWMx pin output driver(s) by clearing the associated TRIS bit(s) and setting the
desired pin PPS control bits.
8. Configure the PWM module by loading the PWMxCON register with the appropriate values.

EE 222L – Microprocessor Systems Lab Page 71


EE 222L – Microprocessor Systems Lab Page 72
8.5 Activities and Exercises

1. Use the CCP1 module in Capture mode to measure the frequency of an input waveform and
display the count in multiples of 2 µs on PORTD (lower byte) and PORTC (upper byte).

2. Use all 4 CCP modules in PWM mode and all 4 PWM modules to generate 8 PWM outputs
simultaneously at RB0, RB1, RB2, RB3, RA0, RA1, RA2, and RA3.
Use Timer 2 as time base for all CCP modules and use Timer 4 for all PWM modules.
All CCP module PWM outputs should have a base frequency of 65 kHz while all PWM module
outputs should have a base frequency of 100 kHz.
The duty-cycles of CCP module PWM outputs should be 30%, 45%, 60%, and 75%.
The duty-cycles of PWM module PWM outputs should be 20%, 40%, 60%, and 80%.

Perform your calculations for the analysis part of all above questions in the space given below:

EE 222L – Microprocessor Systems Lab Page 73


8.5 Assessment Sheet

EE221L Microprocessor Systems Lab Evaluation Rubric

Student Name: ______________________ Reg. #: _________________

CLO & Excellent Good Satisfactory Poor Score


PLOs
Taxonomy 3.0—2.0 2.0—1.0 1.0--0 0
CLO-1
Can setup and Can setup and
P-3 Can independently Cannot setup or
handle the handle the
(Guided PLO-5 setup, operate and handle the
apparatus with apparatus with
Response) handle the apparatus apparatus
minimal help some help.
Apparatus Usage
Data recorded and Data recorded and
CLO-2
All required data is presented is presented is Data recorded
P-4
recorded and complete, but partially only with
(Mechanism)
PLO-5 presented accurately accuracy is not as complete. The considerable
Data Acquisition
and completely in per requirement. required format is assistance from
& Efficiency in
the required format The required followed but with instructor
System Usage
format is followed. few deficiencies.
Analyzes data
CLO-4 Analyzes and Analyzes and
correctly however Unable to analyze
C-4 interprets data interprets data
unable to interpret and interpret data
(Analysis) PLO-4 correctly for all correctly for few
it for tasks/ for any tasks/
Data tasks/ experiments tasks/
experiments in experiments in lab
Interpretation in the lab experiments in lab
lab.
CLO-5
Student arrives
A3 Student arrives on
PLO-8 NA NA after 5 minutes of
(Valuing) time
lab timing
Punctuality
Total Score in Lab /

Instructor Signature: _________________

Date: _________________

EE 222L – Microprocessor Systems Lab Page 74


Lab-9: Internal ADCC and CWG for DC motor speed,
direction, and position control

9.1 Objective
• To develop understanding of Analog to Digital Converter with Computation (ADCC) module
• To develop understanding of Complementary Waveform Generator (CWG) Module
• Understanding the features and settings of ADCC and CWG
• Use of ADCC and CWG in DC motor speed, direction, and position control applications

9.2 Pre-Lab Reading


• Lab manual for Lab-9
• PIC18F47K42 Datasheet Chapter 26 and 36
• M. Ali Mazidi Textbook Chapter 13, 15, and 17

9.3 Equipment/Software Required


• MPLAB X IDE
• EASYPICv8 development board
• Oscilloscope
• Potentiometer
• Power supply
• Full Bridge DC Motor Driver IC Modules (L293)
• DC Mabuchi Motor

9.4 Introduction

The Analog-to-Digital Converter with Computation (ADCC) allows conversion of an analog input
signal to a 12-bit binary representation of that signal. This device uses analog inputs, which are
multiplexed into a single sample and hold circuit. The output of the sample and hold is connected to
the input of the converter. The converter generates a 12-bit binary result via successive
approximation and stores the conversion result into the ADC result registers (ADRESH:ADRESL
register pair).

Additionally, the following features are provided within the ADC module:
• 13-bit Acquisition Timer
• Hardware Capacitive Voltage Divider (CVD) support:
- 13-bit Precharge Timer
- Adjustable sample and hold capacitor array
- Guard ring digital output drive
• Automatic repeat and sequencing:
- Automated double sample conversion for CVD
- Two sets of result registers (Result and Previous result)
- Auto-conversion trigger
- Internal retrigger
• Computation features:
- Averaging and Low-Pass Filter functions

EE 222L – Microprocessor Systems Lab Page 75


- Reference Comparison
- 2-level Threshold Comparison
- Selectable Interrupts

The ADC voltage reference is software selectable to be either internally generated or externally
supplied. The ADC can generate an interrupt upon completion of a conversion and upon threshold
comparison. These interrupts can be used to wake up the device from Sleep.

ADC Configuration

When configuring and using the ADC the following functions must be considered:

• Port configuration
• Channel selection
• ADC voltage reference selection
• ADC conversion clock source
• Interrupt control
• Result formatting
• Conversion Trigger Selection
• ADC Acquisition Time
• ADC Precharge Time
• Additional Sample and Hold Capacitor
• Single/Double Sample Conversion
• Guard Ring Outputs

The ADC will convert the voltage level on a pin whether or not the ANSEL bit is set. When
converting analog signals, the I/O pin should be configured for analog by setting the associated TRIS
and ANSEL bits.

There are several channel selections available. The ADPCH register determines which channel is
connected to the sample and hold circuit. When changing channels, a delay is required before starting
the next conversion.

CONVERSION CLOCK

The conversion clock source is selected with the CS bit in the ADCON0 register. When CS = 1 the
ADC clock source is an internal fixed-frequency clock referred to as ADCRC. When CS = 0 the
ADC clock source is derived from FOSC.

EE 222L – Microprocessor Systems Lab Page 76


RESULT FORMATTING

The 12-bit ADC conversion result can be supplied in two formats, left justified or right justified. The
FM bits of the ADCON0 register controls the output format. Figure below shows the two output
formats. Writes to the ADRES register pair are always right justified regardless of the selected format
mode. Therefore, data read after writing to ADRES when FM = 0 will be shifted left four places.

AUTO-CONVERSION TRIGGER

The auto-conversion trigger allows periodic ADC measurements without software intervention.
When a rising edge of the selected source occurs, the GO bit is set by hardware. The auto-conversion
trigger source is selected by the ADACT register. Using the auto-conversion trigger does not assure
proper ADC timing. It is the user’s responsibility to ensure that the ADC timing requirements are
met.

ADC CONVERSION PROCEDURE (BASIC MODE)

This is an example procedure for using the ADC to perform an analog-to-digital conversion:

1. Configure Port:
• Disable pin output driver (Refer to the TRISx register)
• Configure pin as analog (Refer to the ANSELx register)
2. Configure the ADC module:
• Select ADC conversion clock
• Select voltage reference
• Select ADC input channel
• Precharge and acquisition
• Turn on ADC module
3. Configure ADC interrupt (optional):
• Clear ADC interrupt flag
• Enable ADC interrupt
• Enable global interrupt
4. If ADACQ = 0, software must wait the required acquisition time.
5. Start conversion by setting the GO bit.
6. Wait for ADC conversion to complete by one of the following:
• Polling the GO bit
• Polling the ADIF bit
• Waiting for the ADC interrupt (interrupts enabled)
7. Read ADC Result.
8. Clear the ADC interrupt flag (required if interrupt is enabled).

EE 222L – Microprocessor Systems Lab Page 77


/*This code block configures the ADC
for polling, VDD and VSS references, ADCRC
oscillator and AN0 input.
Conversion start & polling for completion
are included.
*/
void main() {
//System Initialize
initializeSystem();

//Setup ADC
ADCON0bits.FM = 1; //right justify
ADCON0bits.CS = 1; //ADCRC Clock
ADPCH = 0x00; //RA0 is Analog channel
TRISAbits.TRISA0 = 1; //Set RA0 to input
ANSELAbits.ANSELA0 = 1; //Set RA0 to analog
ADCON0bits.ON = 1; //Turn ADC On

while (1) {
ADCON0bits.GO = 1; //Start conversion
while (ADCON0bits.GO); //Wait for conversion done
resultHigh = ADRESH; //Read result
resultLow = ADRESL; //Read result
}
}

EE 222L – Microprocessor Systems Lab Page 78


EE 222L – Microprocessor Systems Lab Page 79
EE 222L – Microprocessor Systems Lab Page 80
EE 222L – Microprocessor Systems Lab Page 81
EE 222L – Microprocessor Systems Lab Page 82
EE 222L – Microprocessor Systems Lab Page 83
EE 222L – Microprocessor Systems Lab Page 84
EE 222L – Microprocessor Systems Lab Page 85
COMPLEMENTARY WAVEFORM GENERATOR (CWG) MODULE

The Complementary Waveform Generator (CWG) produces half-bridge, full-bridge, and steering of
PWM waveforms. It is backwards compatible with previous CCP functions. There are three instances
of the CWG module present on the device. Each of the CWG modules has the following features:

• Six operating modes:


- Synchronous Steering mode
- Asynchronous Steering mode
- Full-Bridge mode, Forward
- Full-Bridge mode, Reverse
- Half-Bridge mode
- Push-Pull mode
• Output polarity control
• Output steering
• Independent 6-bit rising and falling event dead-band timers
- Clocked dead band
- Independent rising and falling dead-band enables
• Auto-shutdown control with:
- Selectable shutdown sources
- Auto-restart option
- Auto-shutdown pin override control

Fundamental Operation

The CWG generates two output waveforms from the selected input source. The off-to-on transition
of each output can be delayed from the on-to-off transition of the other output, thereby creating a
time delay immediately where neither output is driven. This is referred to as dead time.

EE 222L – Microprocessor Systems Lab Page 86


EE 222L – Microprocessor Systems Lab Page 87
Direction Change in Full-Bridge Mode

In Full-Bridge mode, changing MODE[2:0] controls the forward/reverse direction. Changes to


MODE[2:0] change to the new direction on the next rising edge of the modulated input. A direction
change is initiated in software by changing the MODE[2:0] bits of the CWGxCON0 register.

Configuring the CWG

1. Ensure that the TRIS control bits corresponding to CWG outputs are set so that all are
configured as inputs, ensuring that the outputs are inactive during setup. External hardware should
ensure that pin levels are held to safe levels.
2. Clear the EN bit, if not already cleared.
3. Configure the MODE[2:0] bits of the CWGxCON0 register to set the output operating mode.
4. Configure the POLy bits of the CWGxCON1 register to set the output polarities.
5. Configure the ISM[4:0] bits of the CWGxISM register to select the data input source.
6. If a steering mode is selected, configure the STRx bits to select the desired output on the CWG
outputs.
7. Configure the LSBD[1:0] and LSAC[1:0] bits of the CWGxASD0 register to select the
autoshutdown output override states (this is necessary even if not using auto-shutdown because
start-up will be from a shutdown state).
8. If auto-restart is desired, set the REN bit of CWGxAS0.
9. If auto-shutdown is desired, configure the ASxE bits of the CWGxAS1 register to select the
shutdown source.
10. Set the desired rising and falling dead-band times with the CWGxDBR and CWGxDBF
registers.
11. Select the clock source in the CWGxCLKCON register.
EE 222L – Microprocessor Systems Lab Page 88
12. Set the EN bit to enable the module.
13. Clear the TRIS bits that correspond to the CWG outputs to set them as outputs.

EE 222L – Microprocessor Systems Lab Page 89


EE 222L – Microprocessor Systems Lab Page 90
EE 222L – Microprocessor Systems Lab Page 91
9.5 Activities and Exercises

1. Use three ADC channels to get analog data from three different sources and display them in real-
time on three different 8-bit PORTs. Use ADC interrupt to display & switch between channels.
2. Use the CWG and ADCC modules of the microcontroller to design and implement a system for
DC motor speed and position control. A potentiometer will be used as a continuous analog
feedback sensor. The output voltage of the potentiometer will be the input of the ADC. The DC
motor to be controlled is connected to a full bridge controlled by the CWG module. Assume that
the shaft of the motor is connected to the shaft of the potentiometer. When the motor is at the
desired position, the variable resistor is at its exact center and the motor will remain stopped. Our
aim is to bring the motor back to the central point whenever there is an external disturbance in
the motor position (potentiometer). The motor should return quickly, with higher speed, in case
of a large disturbance and slowly in case of a small disturbance.

Perform your calculations for the analysis part of all above questions in the space given below:

EE 222L – Microprocessor Systems Lab Page 92


9.6 Assessment Sheet

EE221L Microprocessor Systems Lab Evaluation Rubric

Student Name: ______________________ Reg. #: _________________

CLO & Excellent Good Satisfactory Poor Score


PLOs
Taxonomy 3.0—2.0 2.0—1.0 1.0--0 0
CLO-1
Can setup and Can setup and
P-3 Can independently Cannot setup or
handle the handle the
(Guided PLO-5 setup, operate and handle the
apparatus with apparatus with
Response) handle the apparatus apparatus
minimal help some help.
Apparatus Usage
Data recorded and Data recorded and
CLO-2
All required data is presented is presented is Data recorded
P-4
recorded and complete, but partially only with
(Mechanism)
PLO-5 presented accurately accuracy is not as complete. The considerable
Data Acquisition
and completely in per requirement. required format is assistance from
& Efficiency in
the required format The required followed but with instructor
System Usage
format is followed. few deficiencies.
Specifications, Specifications, Some
No specifications,
CLO-3 parameters, and parameters, and specifications,
parameters and
C-5 PLO-3 constraints of design constraints of parameters and
constraints of
(Evaluation) are completely design are partially constraints of
design are present
Design present present design are present
Analyzes data
CLO-4 Analyzes and Analyzes and
correctly however Unable to analyze
C-4 interprets data interprets data
unable to interpret and interpret data
(Analysis) PLO-4 correctly for all correctly for few
it for tasks/ for any tasks/
Data tasks/ experiments tasks/
experiments in experiments in lab
Interpretation in the lab experiments in lab
lab.
CLO-5
Student arrives
A3 Student arrives on
PLO-8 NA NA after 5 minutes of
(Valuing) time
lab timing
Punctuality
Total Score in Lab /

Instructor Signature: _________________

Date: _________________

EE 222L – Microprocessor Systems Lab Page 93


Lab-10: Asynchronous Serial Communication with PIC18:
UART module with LCD Interfacing

10.1 Objective
• To develop understanding of Serial Communication and UART Module of PIC18
• To develop understanding of LCD Displays
• Understanding the features and settings UART and LCD
• Use of UART and LCD in data transfer, logging, plotting, and display applications

10.2 Pre-Lab Reading


• Lab manual for Lab-10
• PIC18F47K42 Datasheet Chapter 31
• M. Ali Mazidi Textbook Chapter 10 and 12

10.3 Equipment/Software Required


• MPLAB X IDE
• EASYPICv8 development board
• Oscilloscope
• Potentiometer
• LCD Display
• Serial Terminal Software

10.4 Introduction

UNIVERSAL ASYNCHRONOUS RECEIVER TRANSMITTER (UART)

The Universal Asynchronous Receiver Transmitter (UART) module is a serial I/O communications
peripheral. It contains all the clock generators, shift registers and data buffers necessary to perform
an input or output serial data transfer, independent of device program execution. The UART, also
known as a Serial Communications Interface (SCI), can be configured as a full-duplex asynchronous
system or one of several automated protocols. Full-Duplex mode is useful for communications with
peripheral systems, such as CRT terminals and personal computers.

The UART module includes the following capabilities:

• Full-duplex asynchronous transmit and receive


• Two-character input buffer
• One-character output buffer
• Programmable 7-bit or 8-bit character length
• Input buffer overrun error detection
• Received character framing error detection
• Hardware and software flow control
• Automatic checksums
• Programmable 1, 1.5, and 2 Stop bits
• Programmable data polarity
• Operation in Sleep
EE 222L – Microprocessor Systems Lab Page 94
• Automatic detection and calibration of the baud rate
• Wake-up on Break reception
• Automatic and user timed Break period generation
• RX and TX inactivity timeouts (with Timer2)

The operation of the UART module is controlled through nineteen registers:


• Three control registers (UxCON0-UxCON2)
• Error enable and status (UxERRIE, UxERRIR, UxUIR)
• UART buffer status and control (UxFIFO)
• Three 9-bit protocol parameters (UxP1-UxP3)
• 16-bit baud rate generator (UxBRGH:L)
• Transmit buffer write (UxTXB)
• Receive buffer read (UxRXB)
• Receive checksum (UxRXCHK)
• Transmit checksum (UxTXCHK)

UART I/O Pin Configuration

The RX input pin is selected with the UxRPPS register. The TX output pin is selected with each pin’s
RxyPPS register. When the TRIS control for the pin corresponding to the TX output is cleared, then
the UART will maintain control and the logic level on the TX pin. Changing the TXPOL bit in
UxCON2 will immediately change the TX pin logic level regardless of the value of EN or TXEN.

Enabling the Transmitter

The UART transmitter is enabled for asynchronous operations by configuring the following control
bits:

• TXEN = 1
• MODE[3:0] = 0h through 3h
• UxBRGH:L = desired baud rate
• UxBRGS = desired baud rate multiplier
• RxyPPS = code for desired output pin
• ON = 1
All other UART control bits are assumed to be in their default state. Setting the TXEN bit in the
UxCON0 register enables the transmitter circuitry of the UART. The MODE[3:0] bits in the
UxCON0 register select the desired mode. Setting the ON bit in the UxCON1 register enables the
UART. When TXEN is set and the transmitter is not idle, the TX pin is automatically configured as
an output. When the transmitter is idle, the TX pin drive is relinquished to the port TRIS control. If
the TX pin is shared with an analog peripheral, the analog I/O function should be disabled by clearing
the corresponding ANSEL bit.

Transmitting Data

A transmission is initiated by writing a character to the UxTXB register. If this is the first character,
or the previous character has been completely transmitted from the TSR, the data in the UxTXB is
immediately transferred to the TSR register. If the TSR still contains all or part of a previous
character, the new character data is held in the UxTXB until the previous character transmission is
complete. The pending character in the UxTXB is then transferred to the TSR at the beginning of the
previous character Stop bit transmission. The transmission of the Start bit, data bits and Stop bit
EE 222L – Microprocessor Systems Lab Page 95
sequence commences immediately following the completion of all of the previous character’s Stop
bits.

Enabling the Receiver

The UART receiver is enabled for asynchronous operation by configuring the following control bits:

• RXEN = 1
• MODE[3:0] = 0h through 3h
• UxBRGH:L = desired baud rate
• RXPPS = code for desired input pin
• Input pin ANSEL bit = 0
• ON = 1
All other UART control bits are assumed to be in their default state. Setting the RXEN bit in the
UxCON0 register enables the receiver circuitry of the UART. Setting the MODE[3:0] bits in the
UxCON0 register configures the UART for the desired asynchronous mode. Setting the ON bit in
the UxCON1 register enables the UART. The TRIS bit corresponding to the selected RX I/O pin
must be set to configure the pin as an input.

Receiving Data

Data is recovered from the bit stream by timing to the center of the bits and sampling the input level.
In HighSpeed mode, there are four BRG clocks per bit and only one sample is taken per bit. In
Normal-Speed mode, there are 16 BRG clocks per bit and three samples are taken per bit. The
receiver data recovery circuit initiates character reception on the falling edge of the Start bit. The
Start bit, is always a ‘0’. The Start bit is qualified in the middle of the bit. In Normal-Speed mode
only, the Start bit is also qualified at the leading edge of the bit. The following paragraphs describe
the majority detect sampling of Normal-Speed mode. The falling edge starts the baud rate generator
(BRG) clock. The input is sampled at the first and second BRG clocks.

EE 222L – Microprocessor Systems Lab Page 96


EE 222L – Microprocessor Systems Lab Page 97
EE 222L – Microprocessor Systems Lab Page 98
EE 222L – Microprocessor Systems Lab Page 99
EE 222L – Microprocessor Systems Lab Page 100
Liquid Crystal Displays (LCD)

LCDs are a popular display option to diplay graphics and alphanumeric characters. The most
common type of LCDs include dot matrix based cells and each cell can display one character. Mostly
LCDs accept input in the form of ASCII codes for the characters to be displayed. To write a command
ot the LCD like setting the position of cursor, increment, decrement, clear diplay, move to next line,
etc., command register is selected through Regisrer Selec (RS) pin and the command is written
through the data lines. To send the data to be displayed, data resgiter is selected.

EE 222L – Microprocessor Systems Lab Page 101


EE 222L – Microprocessor Systems Lab Page 102
Following egenric program is used to send a command or data to the LCD:

PORT = data /*Send data to PORT*/


RS = 1; /*Data Register is selected*/
EN = 1; /*High-to-low pulse on Enable pin to latch data*/
MSdelay(5); /*Give appropriate delay for the pulse*/
EN = 0;

EE 222L – Microprocessor Systems Lab Page 103


Further details can be studies from the sections mentioned in the prelab reading.

10.5 Activities and Exercises

1. Write a code to Echo the Serially received data back to the terminal.
2. Design a system that can receive data serially through UART from the computer terminal and
display it in run time on an LCD interfaced with the PIC18 microcontroller. The program should
have the capacity for backspace, enter to second line, and clear the whole display to start from
the first line again.
3. Design a system that can send the ADC input at channel 0 serially to the computer via UART to
USB in real time. Make sure to convert the ADC data into characters before sending serially. Use
the following waveforms as inputs one by one:
i. 50 Hz Sine ii. 100 Hz Sine iii. 1000 Hz Sine
iv. 1000 Hz Tri v. 5000 Hz Tri vi. 10,000 Hz Tri

Send 100 samples to the serial terminal for each waveform, copy the data received, and plot it in
excel. Analyze and comment on all your plots of received data as compared to the respective
input signals.

Perform your calculations for the analysis part of all above questions in the space given below:

EE 222L – Microprocessor Systems Lab Page 104


10.6 Assessment Sheet

EE221L Microprocessor Systems Lab Evaluation Rubric

Student Name: ______________________ Reg. #: _________________

CLO & Excellent Good Satisfactory Poor Score


PLOs
Taxonomy 3.0—2.0 2.0—1.0 1.0--0 0
CLO-1
Can setup and Can setup and
P-3 Can independently Cannot setup or
handle the handle the
(Guided PLO-5 setup, operate and handle the
apparatus with apparatus with
Response) handle the apparatus apparatus
minimal help some help.
Apparatus Usage
Data recorded and Data recorded and
CLO-2
All required data is presented is presented is Data recorded
P-4
recorded and complete, but partially only with
(Mechanism)
PLO-5 presented accurately accuracy is not as complete. The considerable
Data Acquisition
and completely in per requirement. required format is assistance from
& Efficiency in
the required format The required followed but with instructor
System Usage
format is followed. few deficiencies.
Specifications, Specifications, Some
No specifications,
CLO-3 parameters, and parameters, and specifications,
parameters and
C-5 PLO-3 constraints of design constraints of parameters and
constraints of
(Evaluation) are completely design are partially constraints of
design are present
Design present present design are present
Analyzes data
CLO-4 Analyzes and Analyzes and
correctly however Unable to analyze
C-4 interprets data interprets data
unable to interpret and interpret data
(Analysis) PLO-4 correctly for all correctly for few
it for tasks/ for any tasks/
Data tasks/ experiments tasks/
experiments in experiments in lab
Interpretation in the lab experiments in lab
lab.
CLO-5
Student arrives
A3 Student arrives on
PLO-8 NA NA after 5 minutes of
(Valuing) time
lab timing
Punctuality
Total Score in Lab /

Instructor Signature: _________________

Date: _________________

EE 222L – Microprocessor Systems Lab Page 105


Lab-11: Using Other Peripherals of PIC18 including DAC,
Comparator, ZCD, NCO, etc. for Various Applications

11.1 Objective
• To develop understanding of Peripherals including DAC, Comparator, NCO, and ZCD
• Understanding the features and settings of the said peripherals in PIC18.
• Use of DAC, Comparators, ZCD, ADC, and NCO in Analog front end applications

11.2 Pre-Lab Reading


• Lab manual for Lab-11
• PIC18F47K42 Datasheet Chapter 28, 29, 37, and 38
• M. Ali Mazidi Textbook Chapter 13

11.3 Equipment/Software Required


• MPLAB X IDE
• EASYPICv8 development board
• Oscilloscope
• Function Generator
• LCD Display
• Serial Terminal and Plotting Software

11.4 Introduction

DIGITAL TO ANALOG CONVERTER (DAC):

The 5-bit Digital-to-Analog Converter supplies a variable voltage reference, ratio metric with the
input source, with 32 selectable output levels.
The positive input source (VSOURCE+) of the DAC can be connected to:
• FVR Buffer
• External VREF+ pin
• VDD supply voltage
The negative input source (VSOURCE-) of the DAC can be connected to:
• External VREF- pin
• Vss
The output of the DAC (DAC1_output) can be selected as a reference voltage to the following:
• Comparator positive input
• ADC input channel
• DAC1OUT1 pin
• DAC1OUT2 pin
The Digital-to-Analog Converter (DAC) can be enabled by setting the EN bit of the DAC1CON0
register.

EE 222L – Microprocessor Systems Lab Page 106


EE 222L – Microprocessor Systems Lab Page 107
COMPARATOR MODULE:

Comparators are used to interface analog circuits to a digital circuit by comparing two analog
voltages and providing a digital indication of their relative magnitudes. Comparators are very useful

EE 222L – Microprocessor Systems Lab Page 108


mixed signal building blocks because they provide analog functionality independent of program
execution.
The analog comparator module includes the following features:
• Programmable input selection
• Programmable output polarity
• Rising/falling output edge interrupts
A single comparator is shown in Figure below along with the relationship between the analog input
levels and the digital output. When the analog voltage at VIN+ is less than the analog voltage at VIN-
, the output of the comparator is a digital low level. When the analog voltage at VIN+ is greater than
the analog voltage at VIN-, the output of the comparator is a digital high level.

EE 222L – Microprocessor Systems Lab Page 109


Each comparator has two control registers: CMxCON0 and CMxCON1. The CMxCON0 register
(see Register 38-1) contains Control and Status bits for the following:
• Enable
• Output
• Output polarity
• Hysteresis enable
• Timer1 output synchronization
The CMxCON1 register (see Register 38-2) contains Control bits for the following:
• Interrupt on positive/negative edge enables
The CMxPCH and CMxNCH registers are used to select the positive and negative input channels,
respectively.
CWG1 Auto-Shutdown Source
The output of the comparator module can be used as an auto-shutdown source for the CWG1 module.
When the output of the comparator is active and the corresponding WGASxE is enabled, the CWG
operation will be suspended immediately (see Section 26.10.1.2 “External Input Source”).
ADC Auto-Trigger Source
The output of the comparator module can be used to trigger an ADC conversion. When the ADACT
register is set to trigger on a comparator output, an ADC conversion will trigger when the Comparator
output goes high.
TMR2/4/6 Reset
The output of the comparator module can be used to reset Timer2. When the TxRST register is
appropriately set, the timer will reset when the Comparator output goes high.

EE 222L – Microprocessor Systems Lab Page 110


EE 222L – Microprocessor Systems Lab Page 111
EE 222L – Microprocessor Systems Lab Page 112
ZERO-CROSS DETECTION (ZCD) MODULE:

The ZCD module detects when an A/C signal crosses through the ground potential. The actual zero-
crossing threshold is the zero-crossing reference voltage, VCPINV, which is typically 0.75V above
ground. The connection to the signal to be detected is through a series current-limiting resistor. The
module applies a current source or sink to the ZCD pin to maintain a constant voltage on the pin,
thereby preventing the pin voltage from forward biasing the ESD protection diodes. When the applied
voltage is greater than the reference voltage, the module sinks current. When the applied voltage is
less than the reference voltage, the module sources current. The current source and sink action keeps
the pin voltage constant over the full range of the applied voltage.

EE 222L – Microprocessor Systems Lab Page 113


The ZCD module is useful when monitoring an A/C waveform for, but not limited to, the following
purposes:
• A/C period measurement
• Accurate long term time measurement
• Dimmer phase delayed drive
• Low EMI cycle switching

The ZCD module includes a Status bit, which can be read to determine whether the current source or
sink is active. The OUT bit of the ZCDCON register is set when the current sink is active, and cleared
when the current source is active. The OUT bit is affected by the polarity bit, even if the module is
disabled. The OUT signal can also be used as input to other modules. This is controlled by the
registers of the corresponding module.

EE 222L – Microprocessor Systems Lab Page 114


OUT can be used as follows:
• Gate source for TMR1/3/5
• Clock source for TMR2/4/6
• Reset source for TMR2/4/6

EE 222L – Microprocessor Systems Lab Page 115


11.5 Activities and Exercise

1. Design a system that can continuously take analog input from the built-in ADC of PIC18 and
send the output in runtime to the built-in DAC of the microcontroller. Analyze the input and
output waveforms together on two oscilloscope channels and comment on the results.
2. Use a ZCD to detect the polarity switching instance of a 50 Hz sine wave. Use this information
to generate a sine wave at the output of your DAC (using pre-calculated look-up table) that is in
synchronization with the input wave. Use the maximum resolution of the DAC to generate the
output waveform.

Perform your calculations for the analysis part of all above questions in the space given below:

EE 222L – Microprocessor Systems Lab Page 116


11.6 Assessment Sheet

EE221L Microprocessor Systems Lab Evaluation Rubric

Student Name: ______________________ Reg. #: _________________

CLO & Excellent Good Satisfactory Poor Score


PLOs
Taxonomy 3.0—2.0 2.0—1.0 1.0--0 0
CLO-1
Can setup and Can setup and
P-3 Can independently Cannot setup or
handle the handle the
(Guided PLO-5 setup, operate and handle the
apparatus with apparatus with
Response) handle the apparatus apparatus
minimal help some help.
Apparatus Usage
Data recorded and Data recorded and
CLO-2
All required data is presented is presented is Data recorded
P-4
recorded and complete, but partially only with
(Mechanism)
PLO-5 presented accurately accuracy is not as complete. The considerable
Data Acquisition
and completely in per requirement. required format is assistance from
& Efficiency in
the required format The required followed but with instructor
System Usage
format is followed. few deficiencies.
Specifications, Specifications, Some
No specifications,
CLO-3 parameters, and parameters, and specifications,
parameters and
C-5 PLO-3 constraints of design constraints of parameters and
constraints of
(Evaluation) are completely design are partially constraints of
design are present
Design present present design are present
Analyzes data
CLO-4 Analyzes and Analyzes and
correctly however Unable to analyze
C-4 interprets data interprets data
unable to interpret and interpret data
(Analysis) PLO-4 correctly for all correctly for few
it for tasks/ for any tasks/
Data tasks/ experiments tasks/
experiments in experiments in lab
Interpretation in the lab experiments in lab
lab.
CLO-5
Student arrives
A3 Student arrives on
PLO-8 NA NA after 5 minutes of
(Valuing) time
lab timing
Punctuality
Total Score in Lab /

Instructor Signature: _________________

Date: _________________

EE 222L – Microprocessor Systems Lab Page 117


Lab-12: Synchronous Serial Communication (SPI/I2C) for
External Devices Interfacing with PIC18

12.1 Objective
• To develop understanding of working principle and interfacing requirements of various devices
• To use various peripherals of PIC18 for interfacing and data acquisition of different devices
• To display/plot and log the device data in real-time.

12.2 Pre-Lab Reading


• Lab manual for Lab-12
• PIC18F47K42 Datasheet Chapter 31, 32, 33, and 36
• M. Ali Mazidi Textbook Chapter 13 and 16
• MCP482X DAC Datasheet
• HTU-21D Sensor Datasheet
• HC-SR04 Ultrasonic Sensor Datasheet

12.3 Equipment/Software Required


• MPLAB X IDE
• EASYPICv8 development board
• Oscilloscope
• HTU-21D Humidity and Temperature Sensor
• HC-SR04 Ultrasonic Distance Sensor
• MCP482X External DAC IC
• LCD Display
• Serial Terminal Software

12.4 Introduction

HTU-21D HUMIDITY & TEMPERATURE SENSOR:

The HTU21D is a new digital humidity sensor with temperature output by MEAS. This sensor
provides calibrated, linearized signals in digital, I²C format. HTU21D digital humidity sensors are
dedicated humidity and temperature plug and play transducers for OEM applications where reliable
and accurate measurements are needed. Direct interface with a micro-controller is made possible
with the module for humidity and temperature digital outputs. These low power sensors are designed
for high volume and cost sensitive applications with tight space constraints. Every sensor is
individually calibrated and tested. Lot identification is printed on the sensor and an electronic
identification code is stored on the chip – which can be read out by command. Low battery can be
detected and a checksum improves communication reliability. The resolution of these digital
humidity sensors can be changed by command (8/12bit up to 12/14bit for RH/T).

EE 222L – Microprocessor Systems Lab Page 118


Wiring Considerations and Signal Integrity

Carrying the SCK and DATA signal parallel and in close proximity (e.g. in wires) for more than 10
cm may result in cross talk and loss of communication. This may be resolved by routing VDD and/or
GND between the two data signals and/or using shielded cables. Furthermore, slowing down SCK
frequency will possibly improve signal integrity. Power supply pins (VDD, GND) must be bypassed
with a 100nF capacitor if wires are used. Capacitor should be placed as close as possible to the sensor.

Serial data (DATA)

The DATA pin is used to transfer data in and out of the device. For sending a command to the
HTU21D(F) sensor, DATA is valid on the rising edge of SCK and must remain stable while SCK is
high. After the falling edge of SCK, the DATA value may be changed. For safe communication
DATA shall be valid tSU and tHD before the rising and after the falling edge of SCK, respectively.
For reading data from the HTU21D(F) sensor, DATA is valid tVD after SCK has gone low and
remains valid until the next falling edge of SCK. An external pull-up resistor (e.g. 10kΩ) on SCK is
required to pull the signal high only for open collector or open drain technology microcontrollers. In
most of the cases, pull-up resistors are internally included in I/O circuits of microcontrollers.

Serial clock input (SCK)

SCK is used to synchronize the communication between microcontroller and HTU21D(F) sensor.
Since the interface consists of fully static logic there is no minimum SCK frequency.

EE 222L – Microprocessor Systems Lab Page 119


COMMUNICATION WITH SENSOR

Startup Sensor

The HTU21D(F) sensor requires a voltage supply between 1.5V and 3.6V. After power up, the device
needs at most 15ms while SCK is high for reaching idle state (sleep mode), i.e to be ready accepting
commands from the MCU. No command should be sent before that time. Soft reset is recommended
at start, refer p.11.

Start Sequence

To initiate transmission, a start bit has to be issued. It consists of a lowering of the DATA line while
SCK is high followed by lowering SCK.

Stop Sequence

To stop transmission, a stop bit has to be issued. It consists of a heightening of the DATA line while
SCK is high preceded by a heightening of the SCK.

Sending a Command

After sending the start condition, the subsequent I²C header consist of a 7-bit I²C device address 0x40
and a DATA direction bit (‘0’ for Write access : 0x80). The HTU21D(F) sensor indicates the proper
reception of a byte by pulling the DATA pin low (ACK bit) after the falling edge of the 8th SCK
clock. After the issue of a measurement command (0xE3 for temperature, 0xE5 for relative
humidity), the MCU must wait for the measurement to complete.

EE 222L – Microprocessor Systems Lab Page 120


Measurement of RH and T

Conversion of Signal Outputs

Default resolution is set to 12-bit relative humidity and 14-bit temperature readings. Measured data
are transferred in two byte packages, i.e. in frames of 8-bit length where the most significant bit
(MSB) is transferred first (left aligned). Each byte is followed by an acknowledge bit. The two status
bits, the last bits of LSB, must be set to ‘0’ before calculating physical values.

HC-SR04 ULTRASONIC DISTANCE SENSOR:

HC-SR04 ultrasonic distance sensor is an economical sensor which provides 2 cm to 400 cm of non-
contact measurement functionality with a ranging accuracy that can reach up to 3mm. Each HC-
SR04 module includes an ultrasonic transmitter, a receiver and a control circuit.

There are only four pins that you need to worry about on the HC-SR04: VCC (Power), Trig (Trigger),
Echo (Receive), and GND (Ground). This sensor has additional control circuitry that can prevent
inconsistent "bouncy" data depending on the application.

EE 222L – Microprocessor Systems Lab Page 121


Timing diagram

The Timing diagram is shown below. You only need to supply a short 10uS pulse to the trigger input
to start the ranging, and then the module will send out an 8 cycle burst of ultrasound at 40 kHz and
raise its echo. The Echo is a distance object that is pulse width and the range in proportion .You can
calculate the range through the time interval between sending trigger signal and receiving echo
signal. Formula: uS / 58 = centimeters or uS / 148 =inch; or: the range = high level time * velocity
(340M/S) / 2; we suggest to use over 60ms measurement cycle, in order to prevent trigger signal to
the echo signal.

MCP482X 12-bit DAC with SPI Interface :

The MCP4801/4811/4821 devices are single channel 8-bit, 10-bit and 12-bit buffered voltage output
Digital-to-Analog Converters (DACs), respectively. The devices operate from a single 2.7V to 5.5V
supply with an SPI compatible Serial Peripheral Interface.

EE 222L – Microprocessor Systems Lab Page 122


EE 222L – Microprocessor Systems Lab Page 123
EE 222L – Microprocessor Systems Lab Page 124
12.5 Activities and Exercise

1. Interface the HTU-21D humidity and temperature sensor with the microcontroller and display
the humidity and temperature data in real time on UART Serial Port or LCD.
2. Interface the provided Ultrasonic distance sensor with the microcontroller and display the
distance measurement data in centimeters in real time on either an LCD or a UART Serial Port
Terminal of a Computer.
3. Interface the provided MCP482X external DAC with the microcontroller. Generate a triangular
wave at the output and check it on an Oscilloscope.

Perform your calculations for the analysis part of all above questions in the space given below:

EE 222L – Microprocessor Systems Lab Page 125


12.6 Assessment Sheet

EE221L Microprocessor Systems Lab Evaluation Rubric

Student Name: ______________________ Reg. #: _________________

CLO & Excellent Good Satisfactory Poor Score


PLOs
Taxonomy 3.0—2.0 2.0—1.0 1.0--0 0
CLO-1
Can setup and Can setup and
P-3 Can independently Cannot setup or
handle the handle the
(Guided PLO-5 setup, operate and handle the
apparatus with apparatus with
Response) handle the apparatus apparatus
minimal help some help.
Apparatus Usage
Data recorded and Data recorded and
CLO-2
All required data is presented is presented is Data recorded
P-4
recorded and complete, but partially only with
(Mechanism)
PLO-5 presented accurately accuracy is not as complete. The considerable
Data Acquisition
and completely in per requirement. required format is assistance from
& Efficiency in
the required format The required followed but with instructor
System Usage
format is followed. few deficiencies.
Specifications, Specifications, Some
No specifications,
CLO-3 parameters, and parameters, and specifications,
parameters and
C-5 PLO-3 constraints of design constraints of parameters and
constraints of
(Evaluation) are completely design are partially constraints of
design are present
Design present present design are present
Analyzes data
CLO-4 Analyzes and Analyzes and
correctly however Unable to analyze
C-4 interprets data interprets data
unable to interpret and interpret data
(Analysis) PLO-4 correctly for all correctly for few
it for tasks/ for any tasks/
Data tasks/ experiments tasks/
experiments in experiments in lab
Interpretation in the lab experiments in lab
lab.
CLO-5
Student arrives
A3 Student arrives on
PLO-8 NA NA after 5 minutes of
(Valuing) time
lab timing
Punctuality
Total Score in Lab /

Instructor Signature: _________________

Date: _________________

EE 222L – Microprocessor Systems Lab Page 126


Lab-13: Open Ended Lab

13.1 Objective
• To use the knowledge acquired in previous labs to solve real-life complex engineering problems
involving system design and interfacing.

13.2 Pre-Lab Reading


• Lab manual for Labs 1-13
• PIC18F47K42 Datasheet
• M. Ali Mazidi Textbook

13.3 Equipment/Software Required


• MPLAB X IDE
• EASYPICv8 development board
• Oscilloscope
• Potentiometer
• Function Generator
• HC-05 Bluetooth Transceiver
• Serial Terminal Software
• Transistors (MOSFETs/BJTs)
• Center-tapped transformers
• Capacitors

13.4 Introduction

HC-05 is a Bluetooth based wireless serial transceiver. It works at RS232 TTL protocol at 9600 bps.
Following image shows the pin diagram of the module.

EE 222L – Microprocessor Systems Lab Page 127


Understand the working principle and the interfacing requirements of the given module.

CWG PUSH-PULL MODE

In Push-Pull mode, two output signals are generated, alternating copies of the input as illustrated in
Figure 26-4. This alternation creates the push-pull effect required for driving some transformer-based
power supply designs. Steering modes are not used in Push-Pull mode. The push-pull sequencer is
reset whenever EN = 0 or if an auto-shutdown event occurs. The sequencer is clocked by the first
input pulse, and the first output appears on CWGxA. The unused outputs CWGxC and CWGxD drive
copies of CWGxA and CWGxB, respectively, but with polarity controlled by the POLC and POLD
bits of the CWGxCON1 register, respectively.

Now study the Push-Pull converters and their working principle and solve the problem given below
by utilizing the available modules, tools, and features of the available microcontroller.

EE 222L – Microprocessor Systems Lab Page 128


13.5 Activities and Exercise

1. Use the internal CWG module of PIC18 in appropriate mode to design a Sine Pulse Width
Modulation (SPWM) based Push-Pull converter with a 60 Hz reference Sine wave applied
through a function generator. Check the output of the converter before and after filtering on an
oscilloscope. Also plot the real-time voltage output of the converter in real-time wirelessly on a
computer by interfacing one HC-05 Bluetooth module with the controller and one module with
the computer (create a wireless computer based oscilloscope). Use Arduino IDE serial plotter.

Perform your calculations for the analysis part of all above questions in the space given below:

EE 222L – Microprocessor Systems Lab Page 129


13.6 Assessment Sheet

EE221L Microprocessor Systems Lab Evaluation Rubric

Student Name: ______________________ Reg. #: _________________

CLO & Excellent Good Satisfactory Poor Score


PLOs
Taxonomy 3.0—2.0 2.0—1.0 1.0--0 0
CLO-1
Can setup and Can setup and
P-3 Can independently Cannot setup or
handle the handle the
(Guided PLO-5 setup, operate and handle the
apparatus with apparatus with
Response) handle the apparatus apparatus
minimal help some help.
Apparatus Usage
Data recorded and Data recorded and
CLO-2
All required data is presented is presented is Data recorded
P-4
recorded and complete, but partially only with
(Mechanism)
PLO-5 presented accurately accuracy is not as complete. The considerable
Data Acquisition
and completely in per requirement. required format is assistance from
& Efficiency in
the required format The required followed but with instructor
System Usage
format is followed. few deficiencies.
Specifications, Specifications, Some
No specifications,
CLO-3 parameters, and parameters, and specifications,
parameters and
C-5 PLO-3 constraints of design constraints of parameters and
constraints of
(Evaluation) are completely design are partially constraints of
design are present
Design present present design are present
Analyzes data
CLO-4 Analyzes and Analyzes and
correctly however Unable to analyze
C-4 interprets data interprets data
unable to interpret and interpret data
(Analysis) PLO-4 correctly for all correctly for few
it for tasks/ for any tasks/
Data tasks/ experiments tasks/
experiments in experiments in lab
Interpretation in the lab experiments in lab
lab.
CLO-5
Student arrives
A3 Student arrives on
PLO-8 NA NA after 5 minutes of
(Valuing) time
lab timing
Punctuality
Total Score in Lab /

Instructor Signature: _________________

Date: _________________

EE 222L – Microprocessor Systems Lab Page 130

You might also like