Nothing Special   »   [go: up one dir, main page]

Microprocessor Lab Manual Solution

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

Experiment 01: Introduction to PIC 18 Microcontrollers and their

Architecture

Objective:

• Introduction to PIC 18 series Microcontrollers and their Architecture


• To get familiar with Program memory, Data memory, GPR and SFR (Registers)
• Introduction to PIC 18 IDE Simulator and its working
• How to write assembly code in PIC 18 IDE Simulator assembler

Instruments Required:

• Computer/PC/Laptop
• PIC 18 IDE Simulator

Theoretical Background: Microchip Inc. has developed the PIC18 series of microcontrollers
for use in high-pin count, high density, and complex applications. The PIC18F
microcontrollers offer cost-efficient solutions for general-purpose applications written in C
that use a real-time operating system (RTOS) and require a complex communication
protocol stack such as TCP/IP, CAN, USB, or ZigBee. PIC18F devices provide flash program
memory in sizes from 8 to 128Kbytes and data memory from 256 to 4Kbytes, operating at a
range of 2.0 to 5.0 volts, at speeds from DC to 40MHz.

The basic features of PIC18F-series microcontrollers include:

• 77 instructions
• PIC16 source code compatible
• Program memory addressing up to 2Mbytes
• Data memory addressing up to 4Kbytes
• 8-bit CPU
• 2 MB program memory space
• 256 bytes to 1KB of data EEPROM
• Up to 3968 bytes of on-chip SRAM
• 4 KB to 128KB flash program memory
• Sophisticated timer functions
• Serial communication interfaces: SCI, SPI, I2C, and CAN
• Background debug mode (BDM)
• 10-bit A/D converter
• Memory protection capability
• Operates at up to 40 MHz crystal oscillator
Overview of the PIC18 MCU: Microchip has introduced six different lines of 8-bit MCUs over
the years, each with slightly different instruction formats and designs in their peripheral
functions. The PIC18 MCU family shares the same instruction set and peripheral function
design, providing from eight to more than 80 signal pins. The PIC18 MCU aims to eliminate
design flaws of earlier MCU families and provide a better upgrade path to other MCU
families. In terms of cost, the PIC18 MCUs are not more expensive than those in other
families with similar capability.

The PIC18 MCUs provide various peripheral functions, including parallel I/O ports, timer
functions, pulse width modulation (PWM), serial communication interfaces, A/D converter,
memory options, and more.

PIC18FXX2 Architecture: The PIC18FXX2 series consists of four devices. PIC18F2X2


microcontrollers are 28-pin devices, while PIC18F4X2 microcontrollers are 40-pin devices.
The architectures of the two groups are almost identical except for the number of I/O ports
and A/D converter channels.

Memory Organization: Memory consists of a sequence of directly addressable locations,


each having an address and contents. Memory is divided into program memory and data
memory, each accessible through separate buses.

Registers: Registers in PIC18 MCUs include Special Function Registers (SFR) and General
Purpose Registers (GPR). SFRs control operations such as peripheral devices,
timers/counters, interrupts, and more. GPRs are used for various computational and
storage purposes.

Assembly Language: Assembly language is a mnemonic representation of machine


instructions used to program microcontrollers. It simplifies the programming process by
providing human-readable instructions that can be translated into machine language.

PIC Simulator IDE: PIC Simulator IDE is a powerful application that provides a user-friendly
graphical development environment for Windows. It includes an integrated simulator, pic
basic compiler, assembler, disassembler, and debugger, supporting various
microcontrollers from the Microchip 8-bit PIC Mid-Range architecture product line.

Familiarization with PIC Simulator IDE:

• Opening PIC 18 Simulator IDE


• Viewing Special Function Registers (SFR), General Purpose Registers (GPR),
Program Counter (PC), and working register (WREG) in the IDE environment
• Using the assembler editor to write and compile assembly code
• Loading the assembled HEX file in the simulator
• Running and simulating the assembly code step by step

Basic Programming Model:

• Examples demonstrating assembly instructions for loading values into WREG,


performing arithmetic operations, and copying values to registers

Lab Tasks:

• Assemble and run specific instructions on PIC 18 simulator IDE.


• Comment on each program after running.
• Paste the screenshots of the results.

Conclusion:

In this experiment, we explored the architecture and features of PIC18 microcontrollers.


We gained familiarity with PIC Simulator IDE and learned how to write, assemble, and
simulate assembly code for PIC18 microcontrollers. The fundamental instructions and
programming model were demonstrated through examples, enhancing our understanding
of PIC assembly language programming.
Experiment 02: Data Transfer and LED Interfacing in
PIC18 Microcontroller
Objective:
• To understand the different Addressing Modes in PIC18 Microcontroller.
• To blink an LED by connecting to PORT B of PIC18 Microcontroller using Assembly
code in PIC18 IDE Simulator.
• To light up alternate LEDs on different PORTS of PIC18 Microcontroller.

Tools Required:
• Computer/PC/Laptop
• PIC18 IDE Simulator

Addressing Modes:
Microcontrollers use addressing modes to specify the operand to be operated on. The
PIC18 MCU provides several addressing modes for specifying instruction operands. These
include Register Direct, Immediate, Inherent, Indirect, and Bit-Direct Addressing Modes.

Register Direct:

• The PIC18 device uses an 8-bit value to specify a data register as an operand.
• The register may be in the access bank or other banks.
• Examples:
• MOVWF 0x1A, BANKED: Copies the contents of the WREG register to the memory
location 0x1A in the specified bank.
• MOVWF 0x45, A: Copies the contents of the WREG register to the memory location
0x45 in the access bank.
• MOVFF reg1, reg2: Copies the contents of register reg1 to register reg2.
Immediate Mode:
• The actual operand is provided in the instruction.
• No need to access any memory location.
• Examples:
• ADDLW 0x20: Adds the hex value 20 to the WREG register.
• MOVLW 0x15: Loads the hex value 15 into the WREG register.
• MOVLB 3: Places the decimal value 3 in the lower four bits of the BSR register.

Inherent Mode:

• The operand is implied in the opcode field.


• No address information for the operand is supplied.
• Examples:
• MOVLW 0X20: Places the hex value 20 in the WREG register.
• ANDLW 0X13: Performs an AND operation on the corresponding bits of the hex number
13 and the WREG register.
Indirect Mode:
• Uses a special function register as a pointer to the data memory location.
• Examples:
• MOVWF INDF0: Copies the contents of the WREG register to the data memory location
specified by the FSR0 register.
• MOVWF POSTDEC0: Copies the contents of the WREG register to the data memory
location specified by the FSR0 register and decrements FSR0.

Bit-Direct Addressing Mode:

• Deals with an individual bit.


• Uses specific instructions to manipulate individual bits.
• Examples:
• BCF PORTB,3,A: Clears bit 3 of the data register PORTB.
• BSF PORTA,4,A: Sets bit 4 of the data register PORTA.

LED Interfacing:
In this experiment, we demonstrate interfacing LEDs using Assembly code on a PIC18
microcontroller. The goal is to blink an LED connected to PORT B and light up alternate
LEDs on different ports.
Example 01: Blinking LED at PORTB
Program (To light up the LED at bit 2 of PORTB):

ORG 0 ; Starting from 0 address

MOVWF TRISB, 0 ; Move 0 value from WORKING REG to TRIS REG of PORT B, for TRISB=0
PORT B will become output port

MOVLW B'00000010' ; Move literal value in bit form 00000010 in working register value
00000010 is ‘2’ bit no 2 is 1 or ON

MOVWF PORTB ; Move value of WREG in PORTB which is enabled as output PORT

end ; program ends here

Example 02: Lighting up Alternate LEDs at PORTC


Program:

MOVLW 0x7F

MOVWF ADCON1 ; Select all digital pins for ports

MOVLW 00 ; Load W register with 0

MOVWF TRISC, 0 ; Set up PORTC as output

MOVLW 0x55 ; Byte 55H to turn on LEDs

MOVWF PORTC,0 ; Turn on LEDs

SLEEP ; Power down

Lab Tasks:
Task 1: Blinking LED on PORTB

• Write a program in assembly language to light up the LED at bit 2 of PORTB.


• Assemble the code and load the HEX file into the PIC18 IDE simulator.
• Simulate the project to light up the specified LED on PORTB.
Task 2: Lighting up Alternate LEDs on PORTC

• Write a program in assembly language to light up alternate LEDs at PORTC.


• Assemble the code and load the HEX file into the PIC18 IDE simulator.
• Simulate the project to light up the alternate LEDs on PORTC.

Task 3: Program Execution and Analysis

• Run the programs using the Program Memory Editor in the PIC18 Simulator IDE.
• Analyze the values of registers (PC, WREG, PORTC, TRISC, etc.) after program
execution.

Conclusion:
This experiment provided valuable insights into the addressing modes used in PIC18
microcontrollers and demonstrated LED interfacing by manipulating various ports.
Understanding and implementing different addressing modes are crucial for effective
programming of microcontrollers. The practical demonstration of LED interfacing
enhances the understanding of how these modes can be used to control hardware
components.

Review Questions:
Q1. Differentiate between direct and immediate addressing mode.

• Direct addressing mode involves specifying a memory location directly.


• Immediate addressing mode involves providing the actual operand value within the
instruction.

Q2. What is the difference between MOVWF and MOVF command?

• MOVWF is used to move the contents of the WREG register to a specified memory
location.
• MOVF is used to move the contents of a memory location to the WREG register.

Q3. If you want to light up the LED at bit 3 of PORTA in Example 01, what change
would you make in the code?

• Change the bit value in the MOVLW instruction to correspond to LED bit 3.

Q4. If you want to light up all LEDs in Example 02, what change would you make in
the code?
• Set the MOVLW instruction to a value that turns on all the desired LEDs.

Task 3: Program Execution and Analysis


Part I - Task 1 Execution
Register Value after Execution
PC 00000A

WREG 0x30

PORTC 00110000

TRISC 0

LATC 00110000

Part II - Task 2 Execution

Register Value after Execution


PC 00000C

WREG 0xF0

PORTB 11110000

TRISB 0

LATB 11110000
Experiment 03: Introduction to MPLABX IDE, XC8 Compiler, and Proteus

Objective:
• Downloading and installing MPLABX IDE and MPLAB XC8 compilers
• Getting familiar with MPLABX IDE Software and creating a new project
• Setting configuration bits and generating source code to output
• Introduction to Proteus
• Interfacing Proteus with MPLABX software

Tools Required:

• Computer/PC/Laptop
• MPLABX IDE
• MPLAB XC8 Compiler
• Proteus software

Theory:

MPLAB® X IDE (Integrated Development Environment) is a robust and versatile software


program used for the development of applications targeting Microchip microcontrollers
and digital signal controllers. An IDE, such as MPLAB X, integrates various essential tools
and functionalities into one platform, streamlining the process of creating, editing,
debugging, compiling, assembling, and downloading microcontroller programs. It's a
comprehensive toolset that provides a unified environment for programmers to work on
embedded microcontroller projects across different operating systems, including Windows,
Mac OS, and Linux.

MPLAB XC8 C compiler is a crucial tool in the development process, specifically for the
Microchip PIC microcontrollers. It stands as a standalone, optimizing ISO C90 compiler that
supports the full range of 8-bit PIC microcontrollers, including PIC10, PIC12, PIC16, PIC18
series devices, and the PIC 14000 device. The compiler operates in three modes: Free,
Standard, and PRO. The modes differ in optimization levels but share the same basic
compiler operations, supported devices, and memory usage. The XC8 compiler is vital for
translating high-level C code into machine-readable instructions for the PIC
microcontroller.

Proteus is a highly useful simulation software that offers a complete solution for the
development, testing, and virtual prototyping of embedded system designs, particularly
those based on Microchip Technologies TM series of microcontrollers. It facilitates
schematic capture and simulation of circuits, allowing engineers to work on both hardware
and firmware concurrently. The simulation in Proteus is highly accurate and enables real-
time testing of the design before the actual hardware is built. This ensures better design
quality and significantly reduces development time.
Procedure:

Downloading and Installing MPLABX IDE and MPLAB XC8 Compiler:

• Visit the provided links for MPLABX IDE and MPLAB XC8 Compiler download.
• Download the setup files for MPLABX IDE and XC8 compiler compatible with your
operating system (Windows, Linux, Mac OS).
• Run the downloaded setup files and follow the installation instructions to complete
the installation process.

Creating a New Project in MPLABX IDE:

• Launch MPLAB X IDE.


• Click on "File" in the menu and select "New Project".
• Choose "Microchip Embedded" and "Standalone Project" and click "Next".
• Select the appropriate PIC Family (e.g., PIC18) and the specific PIC model (e.g.,
PIC18F2220).
• Click "Next" and proceed to select the tools like PICkit3 for programming and the
XC8 Compiler for compilation.
• Enter the project name, choose the location to save the project, and click "Finish".

Setting Configuration Bits:

• In MPLAB X IDE, click on the "Window" menu and select "PIC Memory Views" and
then "Configuration Bits".
• Configure the necessary settings such as oscillator, low voltage, reset, and other
features as per the project requirements.
• Ensure to select the appropriate clock sources and disable unnecessary features.
• After configuring, click on "Generate Source Code to Output".

Creating Main C File:

• Right-click on "Source Files" in the project window, then select "New" and choose "C
Main File".
• Provide a suitable name for the C file (e.g., main.c) and click "Finish".
• Write the main program for LED blinking or any desired functionality and include
necessary header files.

Simulating the Circuit using Proteus:

• Launch Proteus software.


• Create a new design by selecting "New Design" from the "File" menu and choose
"Default".
• Click on the "P" button or select "Pick Device/Symbol" to add components to the
schematic.
• Search and add components such as PIC18F2220, LEDs, resistors, and other
necessary components to the schematic.
• Connect the components to design the desired circuit.
• Attach the generated HEX file from the MPLABX project to the PIC microcontroller
in the Proteus schematic.
• Run the simulation to observe the behavior of the circuit.

Lab Task
Task 01
Design a circuit for controlling 4 to 5 LEDs/light chaser circuit and run this simulation.
Paste its screen shot.
Task 02
Write the code for in C for task 01.

Conclusion: This experiment provided hands-on experience in downloading, installing,


and using MPLABX IDE, XC8 Compiler, and Proteus simulation software. Understanding
how to configure configuration bits and simulate the design before physical
implementation is crucial for successful embedded system development.

Review Questions:

• What is MPLABX IDE, and how does it differ from MPLAB XC8 compiler?

MPLABX IDE is an integrated development environment for microcontroller applications,


providing a comprehensive platform for development. MPLAB XC8, on the other hand, is a
C compiler specific to PIC microcontrollers.

• How are configuration bits configured?

Configuration bits are set through the MPLABX IDE by specifying various options related to
oscillator, reset, and other features.

• Why is configuration bits configuration necessary?

Configuration bits configuration is essential to ensure the microcontroller operates


correctly and in the desired manner by configuring key settings like clock source and low
voltage programming.

• How is a Hex file loaded into a PIC microcontroller using Proteus?


In Proteus, right-click on the PIC microcontroller, go to Properties, and specify the path to
the Hex file in the Program File field.
Experiment 04: LED Blinking using PIC Microcontroller
in MPLABX
Objective:
• Familiarize with PIC 18F series microcontroller.
• Flash a single LED and control multiple LEDs' blinking pattern using PIC
microcontroller.
• Learn how to blink an LED using MPLAB XC8.

Tools Required:
• Computer/PC/Laptop
• MPLabx IDE
• MPLab XC8 Compiler
• Proteus software

Theory:
PIC 18 Microcontrollers:
The PIC18F series of microcontrollers offer a balance of high computational performance
and cost-effectiveness, making them suitable for a wide range of applications. They are
equipped with high endurance Enhanced Flash program memory and introduce design
enhancements that make them a logical choice for high-performance, power-sensitive
applications.

LEDs:
A Light Emitting Diode (LED) is a semiconductor device that emits light when forward
biased. LEDs have become ubiquitous in electronics and are used to indicate the status of
electronic circuits, display information, and in various lighting applications. LEDs offer
advantages such as low voltage of operation, minimal energy consumption, compact size,
long lifetime, and availability in various colors.

XC8 Code for LED Blinking:


The code for LED blinking is written in C using the MPLAB XC8 compiler. The code
configures the PIC microcontroller's I/O pins to control LEDs.

#include <xc.h>

void main(void) {
TRISBbits.RB0 = 0; // Configure RB0 as output

OSCCON = 0x76; // Configure oscillator settings

while (1) {

LATBbits.LATB0 = ~LATBbits.LATB0; // Toggle the LED state

for (int countDelay = 0; countDelay < 20; countDelay++)

__delay_ms(50); // Delay to control LED blinking speed

return;

In this code:

• TRISBbits.RB0 = 0; configures pin RB0 as an output for controlling the LED.


• OSCCON = 0x76; sets the oscillator settings for the microcontroller.
• LATBbits.LATB0 = ~LATBbits.LATB0; toggles the LED state (on/off).
• __delay_ms(50); introduces a delay of 50 milliseconds to control the LED blinking
speed.

Procedure:

Downloading and Installing MPLABX IDE and MPLAB XC8 Compiler:

• Visit the provided links for MPLABX IDE and MPLAB XC8 Compiler download.
• Download the setup files for MPLABX IDE and XC8 compiler compatible with your
operating system (Windows, Linux, Mac OS).
• Run the downloaded setup files and follow the installation instructions to complete
the installation process.

Creating a New Project in MPLABX IDE:

• Launch MPLAB X IDE.


• Click on "File" in the menu and select "New Project".
• Choose "Microchip Embedded" and "Standalone Project" and click "Next".
• Select the appropriate PIC Family (e.g., PIC18) and the specific PIC model (e.g.,
PIC18F2220).
• Click "Next" and proceed to select the tools like PICkit3 for programming and the
XC8 Compiler for compilation.
• Enter the project name, choose the location to save the project, and click "Finish".

Setting Configuration Bits:

• In MPLAB X IDE, click on the "Window" menu and select "PIC Memory Views" and
then "Configuration Bits".
• Configure the necessary settings such as oscillator, low voltage, reset, and other
features as per the project requirements.
• Ensure to select the appropriate clock sources and disable unnecessary features.
• After configuring, click on "Generate Source Code to Output".

Creating Main C File:

• Right-click on "Source Files" in the project window, then select "New" and choose "C
Main File".
• Provide a suitable name for the C file (e.g., main.c) and click "Finish".
• Write the main program for LED blinking or any desired functionality and include
necessary header files.

Simulating the Circuit using Proteus:

• Launch Proteus software.


• Create a new design by selecting "New Design" from the "File" menu and choose
"Default".
• Click on the "P" button or select "Pick Device/Symbol" to add components to the
schematic.
• Search and add components such as PIC18F2220, LEDs, resistors, and other
necessary components to the schematic.
• Connect the components to design the desired circuit.
• Attach the generated HEX file from the MPLABX project to the PIC microcontroller
in the Proteus schematic.
• Run the simulation to observe the behavior of the circuit.
Lab Tasks:
Task 01: Designing a Light Chaser Circuit with LEDs
Design a circuit to control a light chaser circuit with 4 to 5 LEDs, creating a chasing effect.
Simulate this circuit in Proteus.

Task 02: Writing C Code for the Light Chaser Circuit


Write the C code to control the light chaser circuit, causing the LEDs to create a chasing
effect.

Review Questions:
Q1. What is the function of the LAT register?

• The LAT (Latch) register is used to write data to the output pins of a port, providing
a way to control the output state of the pins.

Q2. What is the function of the TRIS register?

• The TRIS (Tri-State) register is used to set the direction (input or output) of a port
pin, allowing control over whether the pin is used for input or output.

Q3. Why is the OSCCON register used?

• The OSCCON (Oscillator Control) register is used to configure and control the
microcontroller's oscillator settings, which are crucial for proper operation and
timing.

Q4. If you use LATB = 0; in the code, what does it mean?

• Setting LATB = 0; means turning off all the output pins of port B, effectively turning
off any LEDs or devices connected to those pins.

Conclusion:
In this experiment, we gained practical experience in controlling LEDs using a PIC
microcontroller. We learned to configure I/O pins, utilize the LAT and TRIS registers, and
implement time delays to control the LED blinking pattern. Additionally, we simulated LED
control circuits using Proteus, enhancing our understanding of microcontroller-based LED
control.
Experiment 05: Reading Switch Status with a PIC Microcontroller

Objective:

• Learn to read the status of a switch or push button with a PIC microcontroller.
• Understand the use of pull-up or pull-down resistors and switch debouncing.
• Learn how to use a push button with a PIC microcontroller.

Instruments Required:

• Computer/PC/Laptop
• MPLABx IDE
• MPLAB XC8 Compiler
• Proteus software

Theory: Switches and push buttons are essential components in electronic projects,
serving as digital inputs. Properly reading a switch is crucial, requiring the use of pull-up or
pull-down resistors to avoid floating states. Pull-up resistors ensure the pin is either in a
high or low state, providing stability and preventing short circuits.

Pull-Up Resistors: Pull-up resistors are used to ensure the pin is pulled to a high state
(VCC) when the switch is open. This prevents ambiguity in pin status. The value of the pull-
up resistor affects the speed of pin response; larger resistances slow down response but
reduce current flow, while smaller resistances allow faster response but increase current.

Switch Debouncing: Mechanical switches experience bouncing due to imperfect contact


surfaces, causing rapid open-close transitions before stabilizing. Debouncing is necessary
to avoid inaccuracies, and this can be achieved through software algorithms or time delays.

MPLAB XC8 Code for Reading Switch State:

#include <xc.h>

void main(void) {

TRISBbits.RB0 = 0; // Set RB0 as output (LED)

TRISCbits.RC0 = 1; // Set RC0 as input (switch)

while (1) {

if (PORTCbits.RC0 == 0) {

__delay_ms(10); // Wait for switch debouncing

if (PORTCbits.RC0 == 0) {

LATBbits.LATB0 = 1; // Turn on LED if the switch is closed

} else {

LATBbits.LATB0 = 0; // Turn off LED if the switch is open

return;

Procedure:

Step 1: Project Setup

• Open MPLABX IDE on your computer.


• Create a new project for the PIC microcontroller you are using (e.g., PIC18F2220).
• Add the necessary header and source files to the project.

Step 2: Configuration 4. Configure the I/O pins of the microcontroller for the switch and
LEDs. Assign the required pins as input or output.

Step 3: Code Implementation 5. Write the code for controlling the switch state and LED
based on the provided template or custom logic.

Step 4: Build the Project 6. Build the project to check for any compilation errors.

Step 5: Proteus Simulation 7. Open Proteus software.

• Design the circuit by using PIC microcontroller (e.g., PIC18F2220), a switch, and
LEDs.
• Load the hex file generated from the MPLABX project into the simulated
microcontroller.

Step 6: Run the Simulation 10. Run the simulation in Proteus to observe the behavior of
the switch and LEDs based on the programmed logic.

Step 7: Capture Simulation Results 11. Capture screenshots or video recordings of the
Proteus simulation showing the switch's effect on the LEDs.

Lab Task:

Task 01:

• Design a circuit for controlling 2 LEDs with a push button and run this simulation.

Task 02:

• Write code for the project described in Task 01.

Review Questions:

Q1. What is a Pull-Up Resistor?

Ans: A pull-up resistor is a resistor connected between a pin and the positive voltage
supply (VCC) to ensure the pin is in a high state when no other active components are
pulling it low.

Q2. What is a Pull-Down Resistor?


Ans: A pull-down resistor is a resistor connected between a pin and ground (GND) to
ensure the pin is in a low state when no other active components are pulling it high.

Q3. Why do mechanical switches debounce?

Ans: Mechanical switches bounce due to the imperfections in their contact surfaces, causing
rapid open-close transitions before stabilizing. This bouncing effect can introduce
inaccuracies in the signal.

Q4. How can you avoid switch debouncing for a microcontroller that can sense
debouncing?

Ans: Switch debouncing can be handled by implementing software algorithms that involve
reading the switch state multiple times with a short delay in between. Alternatively, a
hardware debounce circuit can be used. Proper coding techniques and hardware solutions
ensure accurate sensing of the switch state despite bouncing.

Conclusion: In this experiment, we learned about the importance of pull-up and pull-down
resistors in ensuring stable pin states. We also explored the concept of switch debouncing
to avoid inaccurate readings from mechanical switches. By implementing proper hardware
and software techniques, we can effectively read switch states using a PIC microcontroller.
Experiment 06: Interfacing 7-Segment Display with PIC Microcontroller
in MPLABX

Objective:

• Learn how to interface a 7-Segment Display with a PIC Microcontroller using


MPLABX.
• Display a specific digit on the 7-Segment Display.

Instruments Required:

• Computer/PC/Laptop
• MPLABx IDE
• MPLAB XC8 Compiler
• Proteus software

Theory: The 7-segment display is a commonly used electronic display that consists of seven
LED bars arranged in a pattern that can display numbers from 0 to 9. Each segment is
referred to by a letter from 'a' to 'g'. Additionally, there is a decimal point segment, making
a total of eight segments, although the term "7-segment display" is still used. These displays
are widely used in digital clocks, electronic meters, counters, and various other
applications for displaying numeric data.
Displaying Digits and Letters:
Figures 1 and 2 in the experiment depict how a 7-segment display can represent digits. For
instance, to display the digit "8" (Figure 1), all the segments (LEDs) are switched on,
including the decimal point. In contrast, to display the digit "3" (Figure 2), specific
segments (a, b, c, d, and g) are switched on. The segments can also be combined to display
certain letters, albeit in a limited manner. For example, to display the letter "b," segments c,
d, e, and f are switched on, and for the letter "F," segments a, e, f, and g are activated.

Common Anode vs. Common Cathode:


7-segment displays are available in two configurations: common anode and common
cathode. In the common anode configuration, the anode pins of all segments are connected
together and are usually connected to the power supply. To activate a segment, a
microcontroller grounds the corresponding segment pin (by sending a logic "0"). In the
common cathode configuration, all the cathode pins of the segments are connected and
usually connected to ground. To activate a segment, the microcontroller applies voltage to
the required segment pin (by sending a logic "1").

Current Limiting Resistors:


Just like standard LEDs, current limiting resistors are necessary in each segment of the
display to control the current and prevent damage. Understanding the typical voltage drop
for LEDs is essential when designing the circuit.

Displaying Numbers:
The easiest way to display a number on the 7-segment display is by determining or looking
up the pattern corresponding to the digit to be displayed. This is often done using a lookup
table, which correlates numbers to the segments that should be turned on or off to display
the desired digit. The table can use decimal, hexadecimal, or binary format.

Procedure:

• Create a new project and add necessary files (header and source file) as discussed in
the introductory experiment.
• Configure the I/O bits and generate source code to output, then paste it into the
header file.
• Design the circuit using a PIC microcontroller and a 7-segment display in Proteus.
• Write the provided C code in the .c source file for the project and build it.
• Load the .hex file into the microcontroller following the procedure discussed in the
introductory experiment.
• Run the simulation.
Lab Task: Task 01:

• Design a circuit with a 7-segment display controlled by a PIC Microcontroller to


display a digit specified by the lab instructor when a switch is closed.
• Run the simulation.
• Provide a screenshot of the simulation.

Task 02:

• Write the C code for the above task.

Review Questions: Q1. What is a 7-segment display?

Ans: A 7-segment display is an electronic display that uses seven LEDs arranged in a
specific pattern to display numbers from 0 to 9.

Q2. How can a 7-segment display be controlled by a Microcontroller?

Ans: A 7-segment display can be controlled by a Microcontroller by appropriately turning


on or off the segments to display the desired digit.

Q3. If you want to display the digit 7, which LEDs should be turned on in the 7-Segment
Display?

Ans: The LEDs corresponding to segments a, b, and c should be turned on to display the
digit 7.

Q4. If you want to display only the digit 1, what will be the code?

Ans: The code to display the digit 1 will correspond to turning on the segments b and c in
the 7-segment display.

Conclusion:

In this experiment, we successfully interfaced a 7-segment display with a PIC


Microcontroller using MPLABX. We learned about the fundamentals of 7-segment displays,
their configurations (common anode and common cathode), and how to control them using
a microcontroller. We also understood the importance of current limiting resistors to
protect the display.
By writing the appropriate code and configuring the microcontroller's I/O pins, we were
able to display specific digits on the 7-segment display. The code was written to display a
sequence of digits from 0 to 9 with a 1-second delay when a switch was closed.

This experiment enhanced our understanding of interfacing electronic components with a


microcontroller, which is a fundamental skill in embedded systems design. The knowledge
gained here can be further applied in various projects involving displays, digital counters,
and real-time data representation. Overall, this experiment provided a hands-on learning
experience in microcontroller interfacing and programming.

Experiment 07: Interfacing LCD Display


with PIC Microcontroller in MPLABX

Objective:
• Learn how to use an LCD Display with PIC Microcontroller using MPLABx
• Display a required string on the LCD Display
Tools Required:
• Computer/PC/Laptop
• MPLABx IDE
• MPLAB XC8 Compiler
• Proteus software

Theory:
LCD Overview:
LCDs (Liquid Crystal Displays) are alphanumeric or graphical displays commonly used in
microcontroller-based applications. They come in various shapes, sizes, and capabilities.
LCDs can be broadly categorized into parallel LCDs and serial LCDs based on the interfacing
technique.

Pin Configuration:
A typical 14-pin LCD has specific pins for power, control, and data. These pins include VSS,
VDD, VEE, RS, R/W, E, and D0-D7. Proper connections and configurations are essential for
effective communication with the microcontroller.

LCD Commands and Functions:


LCD controllers have memory blocks such as DDRAM (Display Data RAM) and CGRAM
(Character Generator RAM). Various commands are used to control the LCD, including
functions to clear the screen, set the cursor position, and control display attributes.

LCD Library:
Microchip XC8 provides an LCD library for controlling HD44780 LCD controllers. The
library includes functions to initialize the LCD, display characters, and manipulate the
display.

Procedure:
Project Setup:

• Create a new project and add the necessary files (source file and configuration file).
• Add the configuration .c file to the project.

Circuit Design:
• Design the circuit using PIC18F2620 microcontroller and an LCD display in Proteus.
• Define the physical connections between the LCD and microcontroller I/O ports in
the "xlcd.h" file.

Code Implementation:

• Write the provided C code in the source file for the project.
• Ensure to modify the LCD pin connections and configurations based on the circuit
design.

Build and Load:

• Build the project to generate the .hex file.


• Load the .hex file into the microcontroller using the appropriate procedure.

Simulation:

• Run the simulation in Proteus to validate the interfacing and functionality.


Lab Task
Task 01
Design a circuit with LCD display controlled by a PIC Microcontroller and display your
name and roll number on LCD. Run this simulation. Paste its screen shot.
Task 02
Write the code in C language for above task.

Review Questions:
Q1. What is the pin configuration of an LCD?
Ans: The typical pin configuration of a 14-pin LCD is as follows:

Pin No. Name Logic State Description


1 VSS 0V Ground
2 VDD +5V Power Supply
3 VEE 0V to +5V Contrast Control
4 RS - Register Select: 0 for commands, 1 for data
5 R/W - Read/Write: 0 for write, 1 for read
6 E - Enable (controls read/write operation)
7 D0 0/1 Bit 0 (LSB)
8 D1 0/1 Bit 1
9 D2 0/1 Bit 2
10 D3 0/1 Bit 3
11 D4 0/1 Bit 4
12 D5 0/1 Bit 5
13 D6 0/1 Bit 6
14 D7 0/1 Bit 7 (MSB)

Q2. Explain the functions of the Enable (E) and RS pins of an LCD.

Ans:

• Enable (E) Pin: The Enable pin (E) is used to enable or disable the LCD. When E is
set to 1, the LCD is enabled, allowing data or commands to be written or read. When
E is set to 0, the LCD is disabled, and it doesn't accept any data or commands.
• RS (Register Select) Pin: The RS pin is used to select whether the data on the data
bus is to be treated as a command or character data. When RS is set to 0, the data is
treated as a command (e.g., clear screen, position cursor). When RS is set to 1, the
data is treated as character data to be displayed on the LCD.

Q3. How are delay functions defined in the code for controlling the
LCD?
Ans: The delay functions are defined using NOP (No Operation) statements or provided
delay functions like Delay10TCYx(). These delays are based on the microcontroller's
instruction cycle time, ensuring that the LCD functions receive the required timing for
proper operation.

Q4. How do you display a string on the LCD?


Ans: To display a string on the LCD, you can use functions like putrsXLCD() or LCDPutStr().
These functions take a string as an argument and display it on the LCD at the current cursor
position.

Conclusion:
In this experiment, we learned about interfacing an LCD display with a PIC Microcontroller
using MPLABx. We explored the theory behind LCDs, their pin configurations, commands,
functions, and how to use the provided LCD library. This knowledge is essential for
incorporating LCD displays into microcontroller-based projects effectively.
Experiment 08: Analog to Digital Conversion in PIC
Microcontroller using MPLABX
Objective
• Learn how to use the Analog to Digital pins of the PIC microcontroller.
• Learn how to connect an analog voltage or sensor to a PIC and display analog
voltage on an LCD.

Tools Required:
• Computer/PC/Laptop
• MPLABx IDE
• MPLAB XC8 Compiler
• Proteus software

Theory
Analog and Digital Signals: Analog signals are continuous and represent quantities with a
wide range of possible values. Examples include temperature, sound, and light intensity. On
the other hand, digital signals are discrete and can only have specific values, typically
represented as 0s and 1s (off and on, respectively). Digital signals are used in computers
and digital communication systems.

PIC Microcontrollers and ADC: PIC microcontrollers, widely used in embedded systems,
often include built-in Analog to Digital Converters (ADC). These ADCs transform analog
signals into digital values that can be processed by the microcontroller. The number of ADC
channels depends on the specific PIC microcontroller model.

A/D Conversion Steps:

• Quantization: Breaking down the continuous analog signal into a finite set of
discrete levels. For instance, if we have a 0-5V signal and use a 3-bit ADC, we'll have
8 discrete levels (2^3) representing the analog range.
• Encoding: Assigning a digital value (binary number) to each quantization level. For
example, in a 3-bit ADC, the levels might be represented as 000, 001, 010, 011, 100,
101, 110, and 111 for the corresponding voltage ranges.

ADC Configuration: To configure the ADC, we use functions like OpenADC, specifying
parameters like clock source, result justification, acquisition time, channel selection,
interrupts, and reference voltage configuration. These configurations ensure accurate
analog to digital conversion.

A/D Acquisition Time: The acquisition time is the delay between selecting a specific
analog input and starting the measurement. It ensures the ADC accurately captures the
input voltage. The appropriate acquisition time mainly depends on the source impedance
of the analog input and is specified in terms of TAD (time to complete one bit conversion).

Resolution: Resolution in ADC refers to the number of discrete values it can produce over
the analog range. Higher resolution (more bits) allows for a finer division of the analog
range into digital values, providing more accurate measurements.

Procedure
• Create a new project in MPLABX and add the necessary files (source file and header
file).
• Configure the ADC and generate the source code to output, then paste it in the
header file.
• Design the circuit in Proteus using a PIC18F2580 microcontroller, reference voltage
source, potentiometer, and LCD display.
• Write the given C code for the project and build it in MPLABX.
• Load the .hex file into the microcontroller using the appropriate procedure.
• Run the simulation to display the analog voltage on the LCD.
Lab Task
Task 01
Design a circuit by using PIC18F2620 Microcontroller, a voltage source connected to its
analogue channel AN1 through potentiometer and LCD display in Proteus. LCD should
display discrete voltage upto +5V.
Configure bits and generate source code for require microcontroller and build the project
in MPlabx.
Run this simulation. Paste its screen shot below.
Task 02
Write the C code for above project and paste screen shot below after building the project in
MPLABX

Review Questions
• How many analog channels are in different PIC microcontrollers?

Answer: The number of analog channels varies for different PIC microcontrollers.

• If you want to enable analog channel pin AN3 for analog data, what will be the code?

Answer: OpenADC(ADC_FOSC_2 & ADC_RIGHT_JUST & ADC_2_TAD, ADC_CH3 & ...);

• What is the ADC initialize function?

Answer: init_ADC1 is the ADC initialize function in the provided code.


• What is A/D acquisition time select?

Answer: A/D acquisition time select is the time delay provided between selecting a specific
analog input and the measurement itself, mainly depending on the source impedance.

Conclusion
This experiment introduced the fundamental concepts of analog to digital conversion and
illustrated the steps to set up and use ADC in PIC microcontrollers. Understanding these
concepts is essential for interfacing analog sensors and devices with microcontrollers and
utilizing the acquired data in various applications. The practical implementation in the
provided code demonstrated the integration of ADC readings with an LCD display,
showcasing a real-world application of A/D conversion.
Experiment 09 Interfacing Matrix Keypad with PIC
Microcontroller using MPLABX
Objective:

The objective of this experiment is to learn how to interface a Matrix Keypad with a PIC
Microcontroller using MPLABX IDE and MPLAB XC8 Compiler.

Tools Required:

• Computer/PC/Laptop
• MPLABX IDE
• MPLAB XC8 Compiler
• Proteus software

Theory
Matrix Keypads
Matrix keypads are a type of input device commonly used to enter data or commands into
electronic systems. They are essentially an array of buttons arranged in rows and columns,
where each button represents a specific character, number, or function. The arrangement
allows for a large number of inputs using fewer pins on a microcontroller compared to a
one-to-one button-to-pin connection.

The most common sizes for matrix keypads are 3×3, 4×3, and 4×4, referring to the number
of rows and columns they have. For example, a 3×3 keypad has 3 rows and 3 columns,
totaling 9 buttons.

Key Mapping
The values of each key on the keypad can be mapped according to the specific application's
requirements. Different keypads may have different mappings based on the application,
and it's crucial to understand the mapping to interpret the pressed keys correctly.

For instance, Figure 3 and Figure 4 in the provided material depict typical key mappings for
a 3×4 and 4×4 matrix keypad. Key mappings could include numbers, letters, special
characters, or even functions.
Detecting a Pressed Key
To determine which key is pressed on a matrix keypad, a scanning method is employed.
Here's a general method for a 4-row, 3-column (4×3) matrix keypad:

• A logic 1 is applied to the first row (Row A).


• The column pins are read. If a column pin reads logic 1, it means the corresponding
key in that column for the first row is pressed.
• The process is repeated for the remaining rows, and the pressed key is determined
based on the row and column combination.

This scanning technique is carried out continuously to detect which key is being pressed.

Interfacing with PIC Microcontroller


To interface a matrix keypad with a PIC Microcontroller, the rows and columns of the
keypad are connected to specific pins on the microcontroller. The microcontroller scans the
rows and reads the columns to detect the pressed key.

In the provided code, the PORTB is used for connecting the keypad. The microcontroller
sequentially applies logic 1 to each row and reads the column pins to identify the pressed
key. The kbd_getc function is responsible for this detection and returns the pressed key.

Understanding the mapping and the scanning mechanism is crucial for effectively
interfacing and utilizing matrix keypads in various applications, such as security systems,
calculators, and input interfaces.

Procedure:

• Create a new project in MPLABX and configure the necessary settings, including
enabling internal oscillator and configuring pins.
• Design the circuit using Proteus, incorporating a PIC18F2580 microcontroller, a 7-
segment display, and a matrix keypad.
• Write the provided code in the .c source file, build the project, and generate the .hex
file.
• Load the .hex file into the microcontroller using the appropriate procedure.
• Simulate the project in Proteus.
Lab Task
Task 01
Make a project by using PIC18F2620 Microcontroller, with keypad and 7-segment display
and connect keypad with port C instead of port B.
Run this simulation.
Paste its screen shot.
Write source code for above project and build the project.
Paste its screen shot also.

Review Questions:

Q1. What is the function of a matrix keypad?

Ans: A matrix keypad is an input device used to enter numeric, alphanumeric, or


configuration data into microcontroller systems in a structured matrix layout. It facilitates
user input in various applications.

Q2. How is a keypad interfaced and controlled with a PIC Microcontroller?

Ans: A keypad is interfaced with a PIC Microcontroller by connecting its rows and columns
to specific GPIO pins on the microcontroller. The microcontroller scans the rows and reads
the columns to detect the pressed key and take appropriate actions.

Q3. If the keypad is connected to port C instead of port B, what changes would be made in
the given code?

Ans: The changes would involve modifying the port definitions and configurations related
to the keypad in the code to reflect the connections made to port C instead of port B.

Conclusion:

In this experiment, we successfully interfaced a matrix keypad with a PIC Microcontroller


using MPLABX IDE and MPLAB XC8 Compiler. The code was designed to detect the first
pressed key and display it on a 7-segment display. Understanding and implementing
keypad interfacing is essential for various applications involving user input.
Experiment 10 Interfacing a Relay with PIC Microcontroller
using MPLABX
Objective:

• Learn how to interface an Electromagnetic Relay with PIC Microcontroller in


MPLABX.
• Understand how to control a fan and light bulb with a microcontroller through a
relay.

Tools Required:

• Computer/PC/Laptop
• MPLABX IDE
• MPLAB XC8 Compiler
• Proteus software
Theory:

A relay is an electromagnetic switch used to control high voltage/current using low-power


circuits. Relays isolate low-power circuits from high-power circuits, enhancing safety by
keeping high dangerous voltage/current isolated. The relay's coil, wound on a soft iron
core, becomes a magnet when a low voltage is applied, energizing the soft iron core and
either closing or opening the high voltage/current contacts of the relay. Relays are used to
switch higher power devices such as motors, light bulbs, and solenoids.

1. Relay Basics: A relay is an electrically operated switch that uses an electromagnetic coil
to mechanically control the switch. It enables the control of high-power devices using low-
power electronic circuits. Relays are crucial for isolating low-power circuits from high-
power circuits for safety and efficient operation.

2. Relay Structure: Typically, a relay consists of a coil, an armature, a spring, and one or
more sets of electrical contacts. When a low voltage is applied across the coil, it generates a
magnetic field, attracting the armature and closing or opening the electrical contacts.

3. Relay Working:

• De-energized (Figure 2): When the coil is not energized, the armature connects to
the normally closed (NC) contact, completing a circuit through common (COM). This
configuration keeps the controlled device off.
• Energized (Figure 3): When the coil is energized, the armature moves, disconnecting
NC and connecting to the normally open (NO) contact. This completes the circuit
through COM, turning on the controlled device.

4. Relay Types:

• Single Pole - Double Throw (SPDT) Relay: Has three terminals: COM, NO, and NC.
• Other Relay Types: Include Single Pole - Single Throw (SPST), Double Pole - Double
Throw (DPDT), etc., depending on the application.

5. Relay Specifications:

• Coil Ratings: Voltage and current required to energize the relay coil (e.g., 5V to 12V,
50-100mA).
• Contact Ratings: Maximum voltage and current the relay contacts can handle
continuously without damage.

6. Interfacing Circuit:
• A relay should not be connected directly to a microcontroller pin due to the high
current requirements. A transistor circuit (as shown in Figure 4) is used to control
the relay.
• The freewheeling diode (D1) protects the transistor from the back EMF generated
by the relay coil when it switches off.

7. MPLAB XC8 Code:

• The microcontroller sets the port bit direction using the TRIS register
(TRISBbits.RB0 = 0 for output).
• The microcontroller controls the relay by sending a logic '1' or '0' to the port using
the LAT register (LATBbits.LATB0 = 1 for ON, and LATBbits.LATB0 = 0 for OFF).

By understanding these principles, we can design and implement circuits to control various
devices using relays and microcontrollers effectively.

Procedure:

• Create a new project and add necessary files (Source file and Header file).
• Configure the bits and generate source code to output and paste it in the header file.
• Design the circuit using Proteus, including the microcontroller, relay, transistor,
freewheeling diode, and the device to be controlled (e.g., fan or lamp).
• Write the given code in the .c source file for the project and build it.
• Load the .hex file into the microcontroller.
• Run the simulation.
Lab Task Task 01
Make a project by using PIC18F2620 Microcontroller as shown above in figure 4. Switch on
and off the lamp using relay with some delays (i.e. lamp will on for 5 seconds and off for 2
seconds.) Hint. (Use delay functions __delay_ms(100); for output 1 and 0.)
Run this simulation.
Paste its screen shot.
Task 02
Write source code for above project and build the project.
Paste its screen shot also

Review Questions:

• Function of Relay:

A relay is an electromagnetic switch used to control high voltage/current using low-power


circuits.
• Types of Relays:

Various types of relays are used in different circuits for protection and control, including
electromechanical relays, solid-state relays, thermal relays, and more.

• How to Interface Relay with PIC Microcontroller:

A relay is interfaced with a PIC Microcontroller using a transistor circuit, allowing the
microcontroller to switch the relay on and off.

• Delay Function for a 4-Second Light Bulb ON:

To keep a light bulb ON for 4 seconds, a delay function like __delay_ms(4000) would be
used.

Conclusion:

In this experiment, we successfully learned how to interface an electromagnetic relay with


a PIC Microcontroller using MPLABX. We understood the functioning and specifications of a
relay and created a circuit to control a fan and a light bulb using the microcontroller
through the relay. The use of a transistor circuit and a freewheeling diode for relay control
was also demonstrated.
Experiment 11: Digital Thermometer using PIC
Microcontroller and LM35 Temperature Sensor

Objective
• Learn to design a digital thermometer using a PIC Microcontroller and LM35
Temperature Sensor.
• Understand how to control the temperature sensor with a PIC Microcontroller.

Instruments Required
• Computer/PC/Laptop
• MPLABx IDE
• MPLAB XC8 Compiler
• Proteus software

Theory
LM35 Temperature Sensor
The LM35 is a popular temperature sensor that is widely used in electronic circuits to
measure temperature. It is a precision analog integrated-circuit temperature sensor
manufactured by Texas Instruments. The key features of the LM35 temperature sensor
include:

• Calibrated directly in Celsius (Centigrade).


• Linear output with a scale factor of 10.0 mV/°C.
• High accuracy, typically within 0.5°C at +25°C.
• Suitable for a wide temperature range from -55°C to +150°C.
• Low power consumption, drawing less than 60 μA from the power supply.
• Low self-heating, approximately 0.08°C in still air.

LM35 Output and Voltage-temperature Relationship


The LM35 sensor provides an output voltage that is linearly proportional to the Celsius
temperature. The voltage output changes by 10 mV per degree Celsius change in
temperature. The output voltage at 0°C is 0V, and for every 1°C increase in temperature,
the output voltage increases by 10 mV. Therefore, at the maximum temperature value of
150°C, the maximum output voltage of the sensor would be 1.5V.

Interfacing LM35 with PIC Microcontroller


The LM35 sensor is interfaced with a PIC Microcontroller to measure the temperature
accurately. The output pin of the LM35 is connected to an analog input pin of the PIC
Microcontroller. The VCC pin of the LM35 is connected to a +5V power supply, and the
ground pin is connected to the ground. This setup allows the PIC Microcontroller to read
the analog voltage output of the LM35, which is directly proportional to the temperature.

Analog to Digital Conversion (ADC)


To convert the analog voltage from the LM35 into a digital value that can be processed by
the microcontroller, an Analog to Digital Converter (ADC) is used. The PIC Microcontroller
is configured to use the ADC module to sample and convert the analog voltage. The
resulting digital value is then processed to calculate the temperature based on the linear
relationship between the LM35 output voltage and the temperature in Celsius.

Procedure
• Create a new project and add necessary source and header files.
• Configure the microcontroller settings (e.g., oscillator, pin configurations) and
generate the source code.
• Design the circuit using PIC18F2620 microcontroller, LM35 Temperature Sensor,
and an LCD display in Proteus.
• Write the provided code in the .c source file for the project.
• Build the project to generate the .hex file.
• Load the .hex file into the microcontroller using the appropriate procedure.
• Run the simulation to observe the temperature display on the LCD based on the
sensor readings.
Lab Task
Task 01
Make a project by using PIC18F2220 Microcontroller as shown in above figure. Interface
the temperature sensor with PIC Microcontroller.
Run this simulation.
Paste its screen shot.
Task 02
Write source code for above project and build the project.
Paste its screen shot also.

Review Questions
Q1. What is the function of the LM35 Temperature Sensor?

• The LM35 Temperature Sensor provides an output voltage linearly proportional to


the Celsius temperature.

Q2. What is the relation between the output voltage of the temperature sensor and
temperature in Celsius?

• The output voltage of the LM35 sensor is linearly proportional to the Celsius
temperature, changing by 10 mV per degree Celsius.

Q3. How is the LM35 interfaced with the PIC Microcontroller?

• The output pin of the LM35 is connected to an analog input of the PIC
Microcontroller. The VCC of LM35 is connected to a +5V supply, and the ground is
connected to ground.

Conclusion
In this experiment, we successfully designed a digital thermometer using a PIC
Microcontroller and an LM35 Temperature Sensor. Understanding the principles of the
LM35 sensor, analog to digital conversion, and microcontroller interfacing is crucial for
building temperature monitoring systems.
Experiment 12: Interrupts in PIC Microcontroller
Objective:
• Understand the mechanisms and significance of interrupts in PIC Microcontrollers,
particularly focusing on external interrupts.

Tools Required:
• Computer/PC/Laptop
• MPLABx IDE
• MPLAB XC8 Compiler
• Proteus software

Theory:
Interrupts are fundamental features of microcontrollers that allow them to respond
promptly to external events or stimuli. An interrupt is an event that demands immediate
attention, causing the microcontroller to pause its current task and execute a specific
program, known as the Interrupt Service Routine (ISR), related to the event. After
executing the ISR, the microcontroller resumes its main program. This mechanism is
similar to how a mobile phone interrupts a game to handle an incoming call and then
returns to the game after the call is completed.

Without interrupts, a microcontroller would need to periodically pause its main program to
check for certain conditions, a method known as polling. However, this approach is
inefficient as it consumes processing time and may lead to delays or overlook critical
processes. Interrupts allow the microcontroller to focus on its main program and only
respond to events when they occur, enhancing efficiency and responsiveness.

Advantages of Interrupts:

• Fail-Safe Applications: Interrupts are vital in applications where immediate action


is required in response to faults or emergencies, ensuring the system's safety and
integrity.
• Routine Task Performance: Interrupts enable the microcontroller to perform
routine tasks at precise intervals, such as reading sensors or blinking LEDs at
specific times.
• Task Completion Check: Interrupts can be used to check if certain tasks, like A/D
conversions or data reception, have been completed, eliminating the need for
continuous polling.

Interrupts in PIC18F Series:


The PIC18F series of PIC Microcontrollers offer a variety of interrupts, including external
edge-triggered interrupts, timer overflows, A/D conversion completion interrupts, and
more. Different registers, such as RCON and INTCON, control interrupt operations. These
registers handle enabling or disabling interrupt sources, setting priorities, and managing
interrupt flags.

Interrupt Priority:
Interrupts in the PIC18F family are categorized into two groups: high priority and low
priority. High-priority interrupts can interrupt low-priority interrupts, but low-priority
interrupts cannot interrupt high-priority ones. The application can choose to enable or
disable this priority scheme based on its needs.

Conditions for Interrupts to Work:


For an interrupt to function:

• The interrupt source's enable bit must be enabled.


• The interrupt flag for the source must be cleared.
• If the source is a peripheral, the peripheral interrupt enable/disable bit must be set.
• The global interrupt enable/disable bit must be set.

Register Details:
• RCON Register: Contains the IPEN bit, which enables interrupt priority levels when
set to 1.
• INTCON Registers: Contain various enable, priority, and flag bits related to
interrupts.

Handling External INT0 Interrupt on PORTB.0 Pin:


To handle an external interrupt on the RB0 pin (INT0), specific steps are followed:

• Set RB0 as an input pin.


• Enable the interrupt bit for RB0.
• Define the triggering edge for the interrupt (falling edge, for instance).
• Clear the interrupt flag for RB0.
• Enable the master switch for interrupts.

When an interrupt occurs, a corresponding interrupt subroutine is executed, performing


the required actions based on the interrupt's context.

Procedure:

• Set RB0 as an input pin (TRISBbits.RB0 = 1).


• Enable the interrupt bit for RB0 (INTCONbits.INT0E = 1).
• Set the interrupt to trigger on a falling edge (INTCON2bits.INTEDG0 = 0).
• Clear the interrupt flag for RB0 (INTCONbits.INT0F = 0).
• Enable the master switch for interrupts (ei()).
• Implement the interrupt subroutine to handle the interrupt and flash the LED
accordingly.
• Implement a flashing routine to be called when an interrupt occurs.
• Run the simulation in Proteus to observe the interrupt handling and LED flashing.
Lab Task
Task 01
Make a project by using PIC18F2220 Microcontroller (an interrupt handling by push
button and blink the LED 2 for 10 seconds) in Proteus.
Build the project code in MPLABX Load the .Hex file to the microcontroller
Run this simulation.
Paste its screen shot.
Task 02
Write the code for above task.
Also paste screen shot of code successful building the project.

Review Questions:

Q1. Define external interrupts and their significance in PIC Microcontrollers.

Ans: External interrupts are events that halt normal program execution, allowing the
microcontroller to respond to specific stimuli. They are crucial for immediate and precise
responses in various applications.

Q2. Explain the function of the RCON and INTCON registers in handling interrupts.

Ans: The RCON register manages interrupt priority enabling, while the INTCON register
contains various enable, priority, and flag bits for controlling interrupts.

Q3. Describe the steps to handle an external interrupt on a specific pin in PIC
Microcontrollers.

Ans: The steps involve configuring the pin as an input, enabling the interrupt, setting the
triggering edge, clearing the interrupt flag, and enabling the master switch for interrupts.
Additionally, an interrupt subroutine is implemented to handle the interrupt and perform
the required actions.

Conclusion:
This experiment provided a comprehensive understanding of interrupts in PIC
Microcontrollers, emphasizing external interrupts. Interrupts are crucial for responsive
and efficient applications, allowing microcontrollers to handle events promptly and
efficiently, thus enhancing the overall performance and reliability of the system.

You might also like