0% found this document useful (0 votes)
77 views97 pages

MPLAB Data Visualization Techniques

This document outlines an introductory lab experiment on embedded system design. The lab covers using MPLAB and Proteus software to write, compile, load and simulate code for a PIC microcontroller. Students are tasked with making projects in both MPLAB and Proteus to practice these skills.

Uploaded by

apna attock
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
77 views97 pages

MPLAB Data Visualization Techniques

This document outlines an introductory lab experiment on embedded system design. The lab covers using MPLAB and Proteus software to write, compile, load and simulate code for a PIC microcontroller. Students are tasked with making projects in both MPLAB and Proteus to practice these skills.

Uploaded by

apna attock
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 97

Embedded System Design

CEL-440
LAB JOURNAL

Name: __________________________________________

Enrollment No: __________________________________

Section: _________________________________________

Department of Electrical Engineering

Bahria School of Engineering and Applied Sciences

H-11 Campus, Islamabad


List of Experiments

Exp. Obtained
Experiment Name Date Sign
No Marks

1. Introduction to PIC 18 Microcontroller, MPLAB and proteus


software.
2. Debugging the code in MPLAB

3. Introduction to Assembly Language and I/O Port Programming


for PIC 18 Microcontroller

4. Seven segment display with PIC 18 Microcontroller.

5. Generation of time delay using branch instructions and loops

6. Implementation of arithmetic instructions using Assembly.

7. Implementation of logical instructions using Assembly.

8. Interfacing LCD with PIC 18 Microcontroller.

9. Interfacing Stepper Motor with Microcontroller.

10. Introduction and Demonstration of Arduino.

11. Generation of Square Waves with different Frequencies using


Timers in PIC 18 Microcontroller

12. Serial Communication using PIC 18 Microcontroller

13. Using interrupts created by timers and to observe the flow of


program when interrupt is invoked

14. Open Ended Lab.

2
Experiment 01
Introduction PIC Architecture, MPLAB and proteus software
Objectives:
This lab helps students understand the basis of PIC microcontroller. In this lab students will be able to learn the
MPLAB and proteus software for the real-world simulation of different microcontrollers.

Equipment/Tools:
• Proteus software
• MPLAB software

Background:
PIC stands for Peripheral Interface Controller. PIC microcontroller was developed by microchip technology in 1993.
PIC microcontrollers are of low cost, very fast and easy for the programming and execution of programs. Their
interfacing with other peripherals is also very easy.

PIC Microcontroller architecture is based on Harvard architecture and supports RISC architecture (Reduced Instruction
Set Computer). PIC microcontroller architecture consists of memory organization (ram, rom, stack), CPU, timers,
counter, ADC, DAC, serial communication, CCP module and I/O ports. PIC microcontroller also supports protocols like
CAN, SPI, UART for interfacing with other peripherals. Some PIC Microcontroller families are 10xxx, 12xxx, 14xxx,
16xxx, 17xxx and 18xxx. They are all 8-bit processors, which means CPU can work on only 8-bit data at a time and
data larger than 8-bit are broken into 8-bit pieces to be processed by the CPU.

Features of PIC 18 family

• It has RISC (reduced instruction set computer) architecture.


• It contains ROM (read only memory) of size 2M (megabytes).
• It has on-chip program (code) ROM (read only memory) in the form of flash memory.
• It contains RAM (random access memory) between 256 bytes to 4096 bytes.
• It has Data EEPROM (Electrical Erasable Programmable Read Only Memory).
• It includes Timers.
• It has ADC (analog to digital converter).
• All I/O port registers are bit accessible and port accessible both.

Pin Diagram of PIC18F452

3
Getting started with MPLAB
MPLAB is an integrated development environment (IDE) created by Microchip Technology for programming their
microcontrollers and digital signal controllers (DSCs). It stands for Microchip PIC (Peripheral Interface Controller)
LABoratory, as it was originally designed for PIC microcontrollers, but it has expanded to support a wide range of
Microchip devices.

Following are steps to write program in MPLAB

1. Open MPLab IDE

2. From the 'Projects' tab, select the first option 'Project Wizard

4
3. Click on Next in the welcome window that appears

4. Select the desired PIC which you need to program or build your project on and click on 'Next'

5
5. Check if the Tool Suite contents listed contains a compiler suiting your programming needs ("ASMC
assembler) and click 'Next'

6. Create a new project file at your desired location in the desired name.

6
7. Take care that the project file is saved in the '*.mcp' format and click 'Next’

8. In the next window, add any files you desire to add to your new project, if required. else just skip
this step by clicking 'Next'

7
9. Now select the 'New' option from the 'File' tab.

10. Select 'Save as' option from the 'File' tab and save the new file in the same folder in which you have
created the project by selecting a suitable option from 'save as type'(depending on which type of
program you're doing)
Example: For assembly language code extension will be .asm (Task1.asm)
For C Source Files extension should be (task1.c)

8
11. Go to the 'Project' tab and select the option 'Add Files to The Project' and add the file saved in the previous
step

12. Begin programming in the file

9
A simple program of led blinking is set as example to understand the basic debugging of a program
in MPLAB

Write first line

#include <P18F452.INC>
After that write following code

13. When you are ready to compile and link your project, use the Build Target command from the
Project menu. MPLAB begins to translate and link the source files and creates an absolute object

10
module that you can load into the MPLAB debugger for testing. The status of the build process is
listed in the Build page of the Output Window.

14. File with .HEX extension will be generated in the project folder.

Introduction to PROTEUS:

For simulating microcontroller circuit, we must have a software which should be capable of microcontroller simulation.
Proteus is a professional software which provides you with the option to load the program (HEX) file on microcontroller
and analyze the real time simulation of your code.

11
• Familiarization with proteus software

• Simulation of microcontroller circuits using proteus

Procedure:

1. In start menu open the software ISIS from proteus professional


2. Open the option “pick device” as shown in figure.

3. Now select microcontrollers ICs from left window and select PIC18f452

4. Now place this IC on circuit

12
5. Now to load program file right click on IC, it will turn into red, now if you again right click, this will
delete that component and if you left click it will show you component properties; so double right
click is used to delete and single right click followed by single left click opens the properties of that
component.

6. Now in program file option browse for desired hex file and load it on the controller.

7. For output visualization you have an option “Visual Instruments” in left window, you can choose
oscilloscope from there.

8. For voltage sources you can select any generator from the left toolbar option “GENERATORS”

13
9. For connecting different components use left click at the pin of one component it will start making a
wire, hold left click till you connect it to the other terminal of connection.

10. A wrong connection can be deleted by double right click on that wire.

11. To visualize the output, click on the play option on the bottom toolbar.

12. To stop the simulation, you are provided with stop option on the same toolbar.

13. You cannot edit a circuit while simulation is on.

Lab task
Task 1:

• Make a new project in MPLAB


• Write the code given above. Build a file.

Task 2:

• Make new project in proteus


• Place microcontroller
• Burn the hex file
• Run the simulation

14
15
16
Conclusion:

……………………………………………………………………………………………………………………………………………………………

……………………………………………………………………………………………………………………………………………………………

……………………………………………………………………………………………………………………………………………………………

……………………………………………………………………………………………………………………………………………………………

……………………………………………………………………………………………………………………………………………………………

……………………………………………………………………………………………………………………………………………………………

……………………………………………………………………

17
Experiment 02
Debugging the code in MPLAB
Objectives:
This lab helps students to debug code in MPLAB and analyze values of SFRs and registers of PIC

Equipment/Tools:
• MPLAB software

Background:
Debugging code in MPLAB involves using the integrated debugger tools provided by MPLAB X IDE to step through
your code, set breakpoints, inspect variables, and analyze the program's behavior.

Basic Debugging Actions

1. Set Breakpoints: Click in the left margin of the editor to set breakpoints in your code. These are points
where your program will pause during debugging.

2. Start Debugging Session: Click on the "Debug" icon (usually a bug-shaped icon) or go to "Run" > "Debug" to
start the debugging session.

3. Debug Controls: Use the debug control buttons (e.g., Run, Pause, Step Over, Step Into, Step Out) to control
the execution of your code. These buttons are often located in the toolbar.

4. Inspect Variables: Use the "Variables" or "Watch" window to monitor the values of variables during
runtime. You can add variables to watch by right-clicking and selecting "Add Watch."

5. Call Stack and Registers: Check the "Call Stack" window to see the history of function calls and the
"Registers" window to monitor the CPU registers.

Procedure

1. Open MPLab IDE

18
2. From the 'Projects' tab, select the first option 'Project Wizard

3. Click on Next in the welcome window that appears

4. Select the desired PIC which you need to program or build your project on and click on 'Next'

19
5. Check if the Tool Suite contents listed contains a compiler suiting your programming needs ("ASMC
assembler) and click 'Next'

6. Create a new project file at your desired location in the desired name.

20
7. Take care that the project file is saved in the '*.mcp' format and click 'Next’

8. In the next window, add any files you desire to add to your new project, if required. else just skip
this step by clicking 'Next'

21
9. Now select the 'New' option from the 'File' tab.

10. Select 'Save as' option from the 'File' tab and save the new file in the same folder in which you have created
the project by selecting a suitable option from 'save as type'(depending on which type of program you're
doing)
Example: For assembly language code extension will be .asm (Task1.asm)
For C Source Files extension should be (task1.c)

22
11. Go to the 'Project' tab and select the option 'Add Files to The Project' and add the file saved in the previous
step.

12. Begin programming in the file.

23
A simple program of led blinking is set as example to understand the basic debugging of a program
in MPLAB

Write first line “#include <P18F452.INC>”

After that write following code

13. When you are ready to compile and link your project, use the Build Target command from the
Project menu. MPLAB begins to translate and link the source files and creates an absolute object
module that you can load into the MPLAB debugger for testing. The status of the build process is
listed in the Build page of the Output Window.

24
14. File with .HEX extension will be generated in the project folder.

Debugging

Once the program is assembled and linked, you can test it with the MPLAB SIM debugger. In MPLAB, use the Run
command from the Debug menu or toolbar. MPLAB initializes the debugger and starts program execution of the
main program.

You will see this Debugging tool

We can select SFRs and other register/memory to see value by running program step by step. We can add watch to
add SFRs of your interest only

25
The PORTB registers enabling HIGH in a certain period,

26
The PORTB registers enabling LOW in a certain period,

LAB TAKS

Task 1: Write a program given in above example and observe value of PROTB

Task 2: Write a program that will toggle value of PROTC pin 3 and PORTD pin 4 with some delay and observe value
using watch

27
28
Conclusion:

……………………………………………………………………………………………………………………………………………………………

……………………………………………………………………………………………………………………………………………………………

……………………………………………………………………………………………………………………………………………………………

……………………………………………………………………………………………………………………………………………………………

……………………………………………………………………………………………………………………………………………………………

……………………………………………………………………………………………………………………………………………………………

……………………………………………………………………

29
Experiment 03
Introduction to Assembly Language and I/O Port Programming for PIC 18 Microcontroller
Objectives:

• Gain familiarity with assembly language.

• Learn essential assembly language commands.

• Understand the syntax of assembly language programming.

• Learn to use the I/O ports of the PIC 18 Microcontroller.

Equipment/Tools:

• Proteus

• MPLAB

Introduction: Before diving into assembly language programming, it's essential to grasp fundamental coding
concepts, assembly language syntax, and basic microcontroller knowledge. This introduction will also cover the I/O
ports of the PIC18F452 microcontroller.

I/O Ports of PIC18F452 Microcontroller: The PIC18F452 microcontroller features 40 pins, with 34 of them serving
as input/output pins organized into five groups, denoted as PORTS A, B, C, D, and E. This section provides an
overview of these ports:

• Port A: Consists of seven pins named RA0-RA6.

• Port B: Comprises eight pins named RB0-RA7.

• Port C: Contains eight pins named RC0-RC7.

• Port D: Comprises eight pins named RD0-RD7.

• Port E: Consists of three pins named RE0-RE2.

Please note that some pins of the I/O ports may serve alternate functions from peripheral features. When used for
another function, they may not be available as general-purpose I/O pins. This discussion focuses on the input-output
features of ports.

Registers: Each port is associated with three registers for its operation:

1. TRIS Register (Data Direction Register):

• TRIS is a data direction register that defines whether the microcontroller should read from or write
to the corresponding port.

• Example for PORT A:

• TRISA=0 (making port an output port)

• TRISA=1 (making port an input port)

2. PORT Register:

• The PORT register reads the levels on the pins of the device, assigning logic values (0/1) to the ports.

• Example:

• For input mode of PORT A:

• Set the direction of data by TRIS register: TRISA=1

30
• Read the status of the pins: PORTA=0x** (Assigning low logic to the pins)

• For output mode of PORT A:

• Set the direction of data by TRIS register: TRISA=0 (making port an output port)

• Assign a value for output: PORTA=0x03 (Assigning high logic to RA0 and RA2)

Additional Notes on PORT B:

• PORTB is an 8-bit wide, bi-directional port.

• All PORTB pins have a weak internal pull-up, which can be controlled using the RBPU bit.

• Four PORTB pins (RB7:RB4) support an interrupt on-change feature.

• RB0, RB1, and RB2 can be used as external interrupt inputs.

Additional Notes on PORT C:

• PORTC is an 8-bit wide, bi-directional port and is multiplexed with several peripheral functions.

• All PORTC pins have Schmitt Trigger input buffers.

• RC1 and RC2 are configured as default peripheral pins for CCP2 and CCP1 modules, respectively.

• RC4 can be used as SPI Data In (SPI mode) or Data I/O (I2C mode).

• RC5 is used for Synchronous Serial Port data output SDO.

• RC6 is used as Addressable USART Asynchronous Transmit or Addressable USART Synchronous


Clock.

• RC7 is used as Addressable USART Asynchronous Receive or Addressable USART Synchronous


Data.

Additional Notes on PORT D and PORT E:

• PORTD is an 8-bit wide, bidirectional port with Schmitt Trigger buffers in I/O mode.

• PORTD can be configured as a parallel slave port using control bit PSPMODE (TRISE<4>).

• PORTE is a 3-bit wide, bi-directional port with Schmitt Trigger input buffers.

• PORTE pins can be multiplexed with analog inputs when used as analog inputs.

Introduction to Assembly Language: Assembly language instructions consist of four fields:

[Label:] mnemonic [operands] [;comment]

1. [Label:] - Used for branching or jumping to specific code locations.

2. Mnemonic - Represents the opcode (e.g., add, mov).

3. Operands - Mention registers or constants used by the command.

4. ; Comment - Used to make the code more readable and user-friendly.

Square brackets indicate optional fields.

31
Assembly language command example:
again MOVLW 40H ; move literal 40H to WREG

GOTO again

MOV Instruction:

The MOVLW and MOVWF instruction copies data from one location to another with the format:

MOVLW K

MOVWF Filereg ; Filereg -> Data memory location or SFR

For example:

MOVLW 55H

MOVWF 10H

After these instructions, WREG = FILEREG (0x10) = 55h.

Example Code: 0101_0101

CLRF TRISB ; set TRIS register as output

Loop MOVLW 55H ; Load 55H into WREG

MOVWF PORTB ; Send 55H to PORT B

CALL DELAY

GOTO loop

DELAY MOVLW 0x0FF

MOVWF 0x10

Back DECFSZ 0x10

GOTO Back

RETURN

32
Lab Tasks:

Task 1: Introduction to Assembly Language Programming

1. Write a Basic Assembly Program to Set Port B as Output:

• Create a simple assembly program using MPLAB to configure Port B as an output.

2. Generate Assembly Code to Blink all LEDs connected to the Port B:

• Develop assembly code to create a basic LED blinking pattern on the LED bar graph in which all LED
of Port B turn on for some delay and turn off for same delay. [use delay of lab1 and use loop to
repeat that code]

3. Generate Assembly Code to Blink Even LEDs connected to Port B:

• Create assembly code that specifically blinks the even-numbered LEDs [use delay and loop in lab1].

• B0,B2,B4,B6

4. Generate Assembly Code to Blink Odd LEDs connected to Port B:

• Develop assembly code that specifically blinks the odd-numbered LEDs.

• B1,B3,B5,B7

5. Generate the Sequence: 10000001, 01000010, 00100100, 00011000 on LED connected to Port B:

• Write assembly code to generate the specified LED sequence on port B.

Task 2: Hex File Burning and Simulation in Proteus

1. Burn the Hex File into the PIC18F452 Microcontroller:

• Transfer the compiled hex file generated from MPLAB into the PIC18F452 microcontroller.

2. Run the Simulation and Display the Results:

• Utilize Proteus for simulation purposes.

• Observe and demonstrate the outcomes of the assembly code execution on the LED bar graph
during the simulation.

33
34
35
Conclusion:

……………………………………………………………………………………………………………………………………………………………

……………………………………………………………………………………………………………………………………………………………

……………………………………………………………………………………………………………………………………………………………

……………………………………………………………………………………………………………………………………………………………

……………………………………………………………………………………………………………………………………………………………

……………………………………………………………………………………………………………………………………………………………

……………………………………………………………………

36
Experiment 04
Interfacing Common Anode/Cathode Seven Segment Display with PIC18F452
Objective:

Demonstrate the interfacing of a common cathode seven-segment display with the PIC18F452 microcontroller by
implementing up/down counters for both single and double-digit numbers.

Equipment/Tools:

• PIC18F452 microcontroller

• Common Cathode Seven Segment Displays (SSDs)

• MPLAB

• Power supply

• Proteus simulation software

Background:

A seven-segment display consists of seven segments labeled a, b, c, d, e, f, g, and a decimal point (dp). These
segments are arranged to display numerical digits (0-9) and some letters (A-F). Common cathode displays have the
common cathode pin connected to the ground (0V), and segments are activated by applying a logic 1 (5V) to the
corresponding pins. It's important to use resistors in series with each segment to limit the current. PIC18F452 can
effectively sink current, making common cathode displays suitable for interfacing.

Figure 3.1 Common Cathode and common Anode seven segment displays

Procedure:

1. Connect the common cathode pins of the seven-segment display to ground (0V) or connect common anode
pin to the 5v through resister of 100 or 220 ohms.

2. Connect each segment (a, b, c, d, e, f, g, dp) to individual pins on the PIC18F452 microcontroller.

3. Write code to control the display segments for counting from 0 to 9 and from 9 to 0.

37
4. Simulate the circuit in Proteus and verify the functionality.

5. Implement the circuit on hardware, ensuring proper connections.

Figure 4.2 7-segment display truth table for common anode and common cathode

Figure 4.3 7-segment display interfacing with PIC18f452

38
Lab Tasks:

Task 1: Counter from 0 to 9 (Common Cathode SSD)

Write code to create a counter that counts from 0 to 9 and displays the numbers on the common cathode seven-
segment display. Verify the output in Proteus and on hardware.

Task 2: Counter from 9 to 0 (Common Cathode SSD)

Write code to create a counter that counts from 9 to 0 and displays the numbers on the common cathode
seven-segment display. Verify the output in Proteus and on hardware.

Task 3: Counter Even number from 0 to 9

Write code to create a counter that counts from 0 to 9 (but only even numbers) and displays the numbers
on the common cathode seven-segment display. Verify the output in Proteus and on hardware.

39
40
Conclusion:

……………………………………………………………………………………………………………………………………………………………

……………………………………………………………………………………………………………………………………………………………

……………………………………………………………………………………………………………………………………………………………

……………………………………………………………………………………………………………………………………………………………

……………………………………………………………………………………………………………………………………………………………

……………………………………………………………………………………………………………………………………………………………

……………………………………………………………………

41
Experiment 05
Implementing Time Delays with Branch Instructions and Loops
Objective:

This lab aims to provide students with a comprehensive understanding of branch instructions and loops in
microcontroller programming.

Equipment/Tools:

• PIC18F452 Microcontroller

• MPLab Integrated Development Environment (IDE)

Background:

A loop refers to the repetition of a sequence of operations or instructions for a specified number of times. In PIC
microcontrollers, there are various methods to execute repetitive tasks. Branch instructions are used to control the
flow of execution in the microcontroller, allowing for repeated tasks based on conditions or without any condition
testing.

In this lab, we will explore key branch instructions used for looping:

1. DECFSZ The "DECFSZ" instruction is employed for creating loops. This instruction is used in combination with
GOTO label instruction.

• Syntax: DECFSZ fileReg, d;

• Description: Decrement the fileReg and skip the next instruction if it becomes 0.

Example:

AGAIN ADDLW 3 ;

DECFSZ COUNT

GOTO AGAIN

42
This above example will repeatedly add 3 to WREG and decrement the value of COUNT. How many times the
code will repeat is dependent on the value of COUNT.

2. BNZ The "BNZ" (Branch if Not Zero) instruction is used for looping, relying on the zero flag in the status
register. This instruction is mostly used in combination with DECF filereg.

• Syntax: BNZ BACK

• Description: Branch to the label "BACK" if the zero flag (Z) is set to 0.

AGAIN ADDLW 3;

DECFCOUNT

BNZ AGAIN

3. BZ The "BZ" instruction is used for checking the Z flag, and it jumps to the target address if the Z flag is set
(Z=1). It is useful for performing subtraction operations.

4. BNC "BNC" stands for "Branch if No Carry." The carry flag is used to make a decision regarding whether to
jump or not. If the carry flag (C) is zero, it branches (jumps) to a label; otherwise, it continues executing the
next instruction.

Unconditional branch instructions:

5. GOTO: It is a long unconditional jump instruction that can transfer control to any memory location within
the address space. GOTO uses a 4-byte instruction with 12 bits for the OPCODE and 20 bits for the target
address location. To enable jumps within 1M of memory location, the lowest bit of the program counter is
set to A0=0.

LAB TASKS:

Task 1: Write a program that (a) clears WREG, (b) adds 5 to WREG ten times, and (c) places the result in the Special
Function Register (SFR) of PORTB, which should be connected to LEDs. Utilize the DECFSZ instructions for looping.

Task 2: Perform task 1 using BNZ command.

Task 3: Perform task 1 using BNC and INCF command.

Task 4: Write a program to (a) load the PORTB SFR register with the value 55H and (b) complement Port B 1000
times. (hint: This required nested loop)

43
44
45
Conclusion:

……………………………………………………………………………………………………………………………………………………………

……………………………………………………………………………………………………………………………………………………………

……………………………………………………………………………………………………………………………………………………………

……………………………………………………………………………………………………………………………………………………………

……………………………………………………………………………………………………………………………………………………………

……………………………………………………………………………………………………………………………………………………………

……………………………………………………………………

46
Experiment 06
Introduction to Arithmetic Instructions for PIC Microcontrollers
Objective:

This lab is designed to provide students with a fundamental understanding of arithmetic instructions used in PIC
microcontroller programming.

Equipment/Tools:

• PIC18F452 Microcontroller

• MPLab Integrated Development Environment (IDE)

Background:

Arithmetic operation instructions are essential for executing mathematical operations in PIC microcontrollers,
enabling them to perform various arithmetic tasks. These operations include addition (ADD), subtraction (SUB),
multiplication (MUL), and division (DIV). The following basic arithmetic instructions are commonly used in PIC
microcontroller programming:

1. ADDLW : The "ADDLW" instruction is employed to perform addition by adding a constant to the W register.
This instruction allows for straightforward addition of two values, with the result stored in another register
or memory location.

• Syntax: Label ADDLW k

• Description: Add the given constant (k) to the W register.

2. ADDWF : "ADDWF" is another instruction for performing addition by adding a constant to the W register.

• Syntax: Label ADDWF f, d

• Description: Add the contents of the W register to the f register.

3. SUBLW : The "SUBLW" instruction is used for subtraction, allowing the subtraction of a constant from the W
register. The result can be stored in another memory location.

• Syntax: Label SUBLW k

• Description: Subtract the W register's contents from the given constant (k).

4. SUBWF: "SUBWF" is employed for subtraction operations. It subtracts the contents of the W register from
the f register.

• Syntax: Label SUBWF f

• Description: Subtract the contents of the W register from the f register.

5. MULLW : The "MULLW" instruction is used for multiplication. PIC supports byte-by-byte multiplication only.
In this instruction, one operand should be in the WREG, and the other should be a literal value. The result is
stored in special function registers PRODH and PRODL.

• Syntax: MULLW K

• Description: Multiply the contents of the W register by a literal value (K).

47
Division: There is no specific instruction for division in PIC microcontrollers. Division can be implemented
using multiple subtraction operations.

LAB TASKS:

Task 1: Write a program to add two 16-bit numbers: 3CE7H and 3B8DH. Do calculations manually and
compare your result.

Task 2: Write a program to subtract two 16-bit numbers: 2762H and 1296H. Assume file register location 6
contains 62H, and location 7 contains 27H. Place the difference in file register locations 6 and 7.

Task 3: Multiply the numbers 25H and 65H. Send high byte to PORTB and low byte to PORTC

Task 4: Write a program to subtract 4C from 6E.

48
49
Conclusion:

……………………………………………………………………………………………………………………………………………………………

……………………………………………………………………………………………………………………………………………………………

……………………………………………………………………………………………………………………………………………………………

……………………………………………………………………………………………………………………………………………………………

……………………………………………………………………………………………………………………………………………………………

……………………………………………………………………………………………………………………………………………………………

……………………………………………………………………

50
Experiment 07
Introduction to Logical Instructions for PIC Microcontrollers
Objectives: This lab is designed to familiarize students with fundamental logical instructions used in PIC
microcontroller programming.

Equipment/Tools:

• PIC18F452 Microcontroller

• MPLab Integrated Development Environment (IDE)

Background: Logical operation instructions are crucial for performing various logical operations in PIC
microcontrollers, including AND, OR, NOT, and XOR. These instructions enable the microcontroller to process and
manipulate binary data effectively. Key logical instructions for PIC microcontrollers include:

1. ANDLW

• Syntax: Label ANDLW k

• Description: Perform a logical AND operation between the given constant (k) and the W register.

2. IORLW

• Syntax: Label IORLW k

• Description: Perform a logical OR operation between the given constant (k) and the W register.

3. IORWF

• Syntax: Label IORWF f, d

• Description: Perform a logical OR operation between the W register and the f register.

4. XORLW

• Syntax: Label XORLW k

• Description: Perform a logical XOR operation between the given constant (k) and the W register.

5. XORWF

• Syntax: Label XORWF f, d

• Description: Perform a logical XOR operation between the W register and the f register.

6. INCF

• Syntax: Label INCF f, d

• Description: Increment the content of the f register.

7. DECF

• Syntax: Label DECF f, d

• Description: Decrement the content of the f register.

8. RLNCF

51
• Syntax: Label RLNCF f, d

• Description: Rotate the content of the f register to the left through the Carry bit.

9. RRNCF

• Syntax: Label RRNCF f, d

• Description: Rotate the content of the f register to the right through the Carry bit.

10. COMF

• Syntax: Label COMF f, d

• Description: Complement the content of the f register.

LAB TASKS:

Task 1: Perform a logical AND operation between two literal values and display the results:

• 35H

• 0FH

Task 2: Display the results of performing a logical OR operation between the following values:

• 04H

• 30H

Task 3: Display the results of the following operations:

• MOVLW 0x54

• XORLW 0x78

Task 4: Write a program to test PORTB and check whether it contains the value 45H. If it does, send 99H to PORTC.

Task 5: Find the two's complement of the value 85H.

52
53
54
Conclusion:

……………………………………………………………………………………………………………………………………………………………

……………………………………………………………………………………………………………………………………………………………

……………………………………………………………………………………………………………………………………………………………

……………………………………………………………………………………………………………………………………………………………

……………………………………………………………………………………………………………………………………………………………

……………………………………………………………………………………………………………………………………………………………

……………………………………………………………………

55
Experiment 08
Interfacing an LCD with PIC18F452
Objectives:

• To interface an LCD with the PIC18F452 microcontroller.

Equipment/Tools:

• 16x2 LCD Display

• PIC18F452 Microcontroller

Background:

In many PIC18F452-based projects, a means of displaying information is essential. One of the most common
methods for achieving this is by using an LCD (Liquid Crystal Display). LCDs provide an affordable and user-friendly
way to display text in embedded systems. Typically, these displays are configured with 16 to 20 characters across 1
to 4 lines.

Understanding LCD:

Figure 1Pin diagram of 16x2 LCD


Pinout:

• 8 Data Pins D7:D0


• These are bi-directional data/command pins. Alphanumeric characters are sent in ASCII format.
• RS: Register Select
• RS = 0 -> Command Register is selected
• RS = 1 -> Data Register is selected
• R/W: Read or Write
• 0 for Write.
• 1 for Read.
• E: Enable (Latch Data)
• Used to latch the data present on the data pins. A high-to-low edge is needed to latch the data.
Before using the LCD library, define these global variables:
• LCD_D7: Data bit 7
• LCD_D6: Data bit 6
• LCD_D5: Data bit 5
• LCD_D4: Data bit 4
• LCD_RS: Register Select (data/instruction) signal pin
• LCD_EN: Enable signal pin
• LCD_D7_Direction: Direction of Data Bit 7
• LCD_D6_Direction: Direction of Data Bit 6
• LCD_D5_Direction: Direction of Data Bit 5
• LCD_D4_Direction: Direction of Data Bit 4
• LCD_RS_Direction: Direction of Register Select pin

56
• LCD_EN_Direction: Direction of the Enable signal pin
Procedure

1: Gather Components
Ensure that you have all the necessary components, including the PIC18F452 microcontroller, 16x2 LCD display,
jumper wires, and a potentiometer for contrast control.

2: LCD Pinout
Understand the pinout of your 16x2 LCD. Typically, it has 16 pins arranged as 2 rows of 8 pins each. The pins are
labeled as follows:

• VSS (Ground)

• VDD (Power)

• V0 (Contrast Control)

• RS (Register Select)

• RW (Read/Write)

• E (Enable)

• D0-D7 (Data Pins)

• A (Anode/Backlight Power)

• K (Cathode/Backlight Ground)

Step 3: PIC18F452 Pinout


Identify the pins on your PIC18F452 microcontroller that will be used for connecting to the LCD. You'll need:

• PORTB or PORTD (or any other suitable port) for connecting the data lines (D0-D7).

• Two GPIO pins for RS and E.

• Ground (GND) and Power (VCC) connections for the LCD.

Step 4: Connect Data Lines


Connect the data lines (D0-D7) from the LCD to the PIC18F452's PORTB or PORTD. Typically, you'll use the first four
data lines (D4-D7) in 4-bit mode. Connect the wires like this:

• LCD D4 to PIC RD0

• LCD D5 to PIC RD1

• LCD D6 to PIC RD2

• LCD D7 to PIC RD3

Step 5: Connect Control Pins


Connect the control pins RS, RW, and E to your PIC18F452. You can use any available GPIO pins. Typical connections
are:

• LCD RS to PIC GPIO (e.g., RB0)

• LCD RW to Ground (set to write mode)

• LCD E to PIC GPIO (e.g., RB1)

Step 6: Connect Power and Ground


• Connect LCD VSS (Ground) to the PIC's ground (GND).

• Connect LCD VDD (Power) to a suitable voltage source (5V or 3.3V, depending on your setup).

57
• Use a 10kΩ potentiometer to adjust the LCD contrast. Connect one end of the potentiometer to V0 on the
LCD and the other end to Ground. The wiper connects to a suitable voltage source (e.g., VCC).

Step 9: Code Configuration


Write your PIC18F452 code to control the LCD. You'll need to configure the data direction, initialize the LCD, and
send commands/data for display.

Several LCD commands are available. The following table shows some important commands.

Generally, the sequence of command used is

i) 38h: select 16x2 LCD,8 bit mode, 5x7 matrix display


ii) 01h: clear display
iii) 0Eh: display on, the cursor blinking
iv) 80h,81h……… : address of character position on the first row
v) 0C0h,0C1h……: address of character position on the second row

Note that the cursor position automatically increments after writing data in the data register.

Addresses of character position:

Step 10: Test Upload


your code to the PIC18F452 and power on the circuit. You should see the desired text or characters displayed on the
LCD.

Lab Task:

Task 1: Write a code to display "Hello World" on the LCD and display the output in Proteus (simulation) and
hardware.

Task 2: Write your name on the LCD and display it in Proteus (simulation) and hardware.

58
Sample code: COMNWRT ; function to send command to LCD
#INCLUDE p18f452.INC; MOVWF LCD_DATA
CONFIG WDT=OFF; disabling the watchdog BCF LCD_CTRL,RS
timer BCF LCD_CTRL,RW
ORG 0; BSF LCD_CTRL,EN
CALL DELAY
MYREG EQU 0X80 BCF LCD_CTRL,EN
RETURN
LCD_DATA EQU PORTD ; Data at PORTD
LCD_CTRL EQU PORTB ; Control from DATAWRT ; function to send data to LCD
PORTB MOVWF LCD_DATA
BSF LCD_CTRL,RS
RS EQU RB0 ;PORTB 0 for RS BCF LCD_CTRL,RW
RW EQU RB1 ;PORTB 1 for RW BSF LCD_CTRL ,EN
EN EQU RB2 ;PORTB 2 for EN CALL DELAY
BCF LCD_CTRL,EN
CLRF TRISD RETURN
CLRF TRISB
BCF LCD_CTRL,EN ;Enable with pin RB2
DELAY ; function for delay
CALL DELAY MOVLW D'200'
MOVLW 0X38 ; 2 lines and 5x7 matrix MOVWF MYREG
CALL COMNWRT AGAIN2 NOP
NOP
CALL DELAY NOP
MOVLW 0X0E ; Display on, cursor blink NOP
CALL COMNWRT NOP
DECF MYREG,F
CALL DELAY BNZ AGAIN2
MOVLW 0X01 ;clear display screen RETURN
CALL COMNWRT

CALL DELAY END


MOVLW 0X06 ;shift cursor to right
CALL COMNWRT

CALL DELAY
MOVLW 0X84;force cursor to begin at
0x84
CALL COMNWRT

CALL DELAY
MOVLW A'N' ;send ASCII of N
CALL DATAWRT

CALL DELAY
MOVLW A'O' ;send ASCII of O
CALL DATAWRT

AGAIN BTG LCD_CTRL,0


BRA AGAIN

59
60
61
Conclusion:

……………………………………………………………………………………………………………………………………………………………

……………………………………………………………………………………………………………………………………………………………

……………………………………………………………………………………………………………………………………………………………

……………………………………………………………………………………………………………………………………………………………

……………………………………………………………………………………………………………………………………………………………

……………………………………………………………………………………………………………………………………………………………

……………………………………………………………………

62
Experiment 09
Stepper Motor Interfacing with PIC18F452
Objectives:

1. Interface a PIC18F452 microcontroller with a stepper motor.


2. Create a schematic in Proteus to simulate the circuit.
3. Execute the code to rotate the stepper motor and observe the results.
Equipment/Tools:

1. PIC18F452 microcontroller
2. Stepper Motor
3. ULN2803/ULN2003 (Stepper Motor Driver)
4. Digital Multimeter (DMM)
5. MPLAB (Integrated Development Environment)
6. Proteus (Simulation Software)
Background:
A stepper motor is a widely used device that trans- lates electrical pulses into mechanical movement. In applications
such as disk drives, dot matrix printers, and robotics, the stepper motor is used for position control. The most common
stepper motors have four stator windings that are paired with a center-tapped common as shown below.

This type of stepper motor is commonly referred to as a four- phase or unipolar stepper motor. The center tap allows
a change of current direction in each of two coils when a winding is grounded, thereby resulting in a polarity change
of the stator. Notice that while a conventional motor shaft runs freely, 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 Figure 17-8. Stator Winding 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.

Working
The stepper motor discussed here has a total of six leads: four leads representing the four stator windings (A,B,C and
D) and two commons for the center-tapped leads. As the sequence of power is applied to each stator winding, the
rotor will rotate. There are several widely used sequences, each of which has a different degree of precision. The
table shows a two-phase, four-step stepping sequence.

Normal Four-step Sequence


Clockwise Step Winding-A Winding-B Winding-C Winding-D Counter Clockwise

1 1 0 0 1
2 1 1 0 0
3 0 1 1 0
4 0 0 1 1

63
Note that although we can start with any of the sequences in Table 17-3, once we start, we must continue in the
proper order. For example, if we start with step 3 (0110), we must continue in the sequence of steps 4, 1, 2, etc.

Step Angle of stepper motor

Because of their discrete step operation, stepper motors can easily be rotated a finite fraction of a rotation at a time,
such as 1.8, 3.6, 7.5 degrees etc. So, for example, let’s assume that a stepper motor completes one full revolution (360
in exactly 200 steps) then the step angle for the motor is given as 360 degrees/200 steps = 1.8 degrees per step. This
value is commonly known as the stepper motors Step Angle. The most used stepper motor being the 200 step per
revolution stepper motor. It has a 50 teeth rotor, 4-phase stator and a step angle of 1.8 degrees (360 degs/(50×4)).

Procedure

1. Use an ohmmeter to measure the resistance of the leads. This should identify which COM leads are connected to
which winding leads.

2. The common wire(s) are connected to the positive side of the motor's power supply. In many motors, +5 V is
sufficient.

3. The four leads of the stator winding are controlled by four bits of the PIC18 port (RBO RB3). Because the PIC18
lacks sufficient current to drive the stepper motor windings, we must use a driver such as the ULN2003 to energize
the stator. Instead of the ULN2003, we could have used transistors as drivers. However, notice that if transistors are
used as drivers, we must also use diodes to take care of inductive current generated when the coil is turned off. One
reason that using the ULN2003 is preferable to the use of transistors as drivers is that the ULN2003 has an internal
diode to take care of back EMF.

Drive Methods:
There are four different drive methods for stepper motor:

i. Wave Drive (Full Step)


ii. 2 Phases On (Full Step)
iii. 1-2 Phases On (Half Step)
iv. Micro step
i. Wave Drive (Full Step):
In the diagram to the right, the wave drive method has been simplified to better illustrate the theory. In the
illustration each 90° turn is representing 1.8° of rotor rotation in an actual motor. In the wave drive
method (also called the 1-phase ON method) only one phase is turned on at a time. When we
energize the “A” phase as a south pole, it attracts the north pole of the rotor. We turn off A and
turn on B; the rotor rotates 90° (1.8°) and so on. Each time only one phase is energized. The
wave drive has a four-step electrical sequence to rotate the motor.

64
Wave Drive method
Clockwise Step Winding-A Winding-B Winding-C Winding-D Counter Clockwise
1 1 0 0 0
2 0 1 0 0
3 0 0 1 0
4 0 0 0 1

Figure 2 Full Wave drive

ii. Phases on (Half Step):


Half Step means that the stepping motor is rotating at 400 steps per revolution (0.9-degree steps x 400 =
360 degrees). First one winding is energized and then two windings are alternately energized. This will
cause the rotor of the stepping motor to move at half the distance (0.9 degrees). In half-step mode, a
typical stepper motor provides about 30% less torque, but it provides a smoother motion than it would
in full-step mode.

1-2 Phases On method


Clockwise Step Winding-A Winding-B Winding-C Winding-D Counter
1 1 0 0 0 Clockwise
2 1 1 0 0
3 0 1 0 0
4 0 1 1 0
5 0 0 1 0
6 0 0 1 1
7 0 0 0 1
8 1 0 0 1

How to Deal with an unknown stepper motor:


You have a stepper motor which has 6 Terminals (A1, A2, A3, B1, B2, and B3). You want to find out the common
Terminals or center taped terminals and the phase sequence.
First, identify two coils as A1, A2, and A3 has no connection with B1, B2 and B3 so resistance will be infinite. So, by
measuring resistances or doing beep test with DMM you can easily identify two coils.

Now you have two coils separately in coil1 there are three terminals (A1, A2 and A3) and in coil2 we have (B1, B2
and B3)
For Finding Common Terminal: Find out the resistance between each terminal of the same coil. If,

65
A1-A2 = R B1-B2 = R
A2-A3 = R B2-B3 = R
A1-A3 = 2R B1-B3 = 2R
Now you can easily say that common Terminals are A2 and B2.

Just short them

For Finding Phase Sequence:

Now you have 5 Terminals A1, A3, B1, B3 and A2 B2.

Apply +5V at A2B2 now you have 4 remaining terminals A1, A3, B1 and B3.

Step1: Connect any 1 Terminal with ground and label it as ‘A’. Now we have 3 remaining terminals (assuming I have
grounded A1 terminal here).

Connect Ground with A3 terminal.

Disconnect A3 terminal and Ground B1 terminal. Disconnect B1 terminal and Ground B3 terminal. Disconnect ground
from B3 terminal.

By grounding any of the wire from A3, B1 or B3 there will be three possibilities. Either motor takes 1 step clockwise,
1 step anti-clockwise or no step.

If motor takes 1 step Anti-clockwise label this wire as ‘D’. If motor takes no step label this terminal as ‘C’.

If motor takes 1 step Clockwise label this terminal as ‘B’. Now ABCD is your phase sequence.

Lab Tasks:

Task 1: Circuit Setup and Hardware Implementation

1. Identify the common wires and A1, A3, B1, B3 and A2,B2 (Common) of stepper motor.

2. Connect the stepper motor to the ULN2803/ULN2003 driver.

3. Connect the driver to the PIC18F452 microcontroller according to your schematic.

66
4. Write code to control the stepper motor in MPLAB. Ensure that you configure the appropriate I/O pins to
interface with the ULN2003 driver.

5. Compile the code to generate a hex file.

6. Implement circuit on Proteus by Adding the PIC18F452 microcontroller, ULN2003 driver, and stepper motor
components to the schematic.

7. Connect the components based on your hardware setup.

8. Import the hex file generated and load it onto the PIC18F452 microcontroller in the Proteus simulation.

9. Implement the above on hardware.

67
68
69
Conclusion:

……………………………………………………………………………………………………………………………………………………………

……………………………………………………………………………………………………………………………………………………………

……………………………………………………………………………………………………………………………………………………………

……………………………………………………………………………………………………………………………………………………………

……………………………………………………………………………………………………………………………………………………………

……………………………………………………………………………………………………………………………………………………………

……………………………………………………………………

70
Experiment 10
Introduction and Demonstration of Arduino
Objectives:

1. Introduce Arduino platform to the students.


2. Demonstrate basic interfacing concepts with Arduino.
3. Develop coding skills for Arduino projects.
Equipment/Tools:

1. Arduino Board (UNO or similar)


2. Liquid Crystal Display (LCD)
3. Light Emitting Diode (LED)
4. Sensor (Temperature or Light)
5. Computer with Arduino IDE installed.
6. Appropriate cables and power supply for Arduino
Background: Arduino is an open-source platform for building digital devices and interactive objects. It consists of a
microcontroller board and an integrated development environment (IDE) for programming. Arduino allows users to
create projects that sense and control the physical world.

Arduino Uno - R3:

• ATmega328 microcontroller
• Input voltage: 7-12V
• 14 Digital I/O Pins (6 PWM outputs)
• 6 Analog Inputs
• 32k Flash Memory
• 16MHz Clock Speed

Procedure:

Step 1: Set Up Your Hardware

1. Connect your Arduino board (e.g., Arduino UNO) to your computer using a USB cable.

2. Make sure you have installed the Arduino IDE (Integrated Development Environment) on your computer. If
not, you can download it from the Arduino website (https://www.arduino.cc/en/Main/Software).

Step 2: Launch Arduino IDE

71
1. Open the Arduino IDE that you have installed.

Step 3: Select Your Arduino Board

1. Go to the "Tools" menu and select "Board." Choose the specific Arduino board you are using (e.g., Arduino
UNO).

Step 4: Choose the Port

1. In the "Tools" menu, select "Port" and choose the port where your Arduino board is connected. The port
might appear as "COMX" (X being a number) on Windows

Step 5: Write Your Code

1. In the Arduino IDE, you'll see a text editor where you can write your code. By default, it will contain a basic
template with setup() and loop() functions.

2. Write your code in the setup() and loop() functions. The setup() function runs once when the board starts,
and the loop() function runs continuously.

Here's a simple example of code to blink an LED:

void setup() {

pinMode(13, OUTPUT); // Set digital pin 13 as an output

void loop() {

digitalWrite(13, HIGH); // Turn on the LED

delay(1000); // Wait for 1 second

digitalWrite(13, LOW); // Turn off the LED

delay(1000); // Wait for 1 second

Step 6: Verify and Compile Your Code

1. Click the checkmark icon (Verify) in the top left corner of the Arduino IDE. This will compile your code and
check for any errors. If there are errors, they will be displayed in the message area at the bottom of the IDE.
Make sure your code compiles without errors before proceeding.

Step 7: Upload Your Code

1. Once your code compiles successfully, click the right-arrow icon (Upload) next to the Verify button. This will
upload your code to the Arduino board.

2. You'll see the status of the upload process in the lower part of the IDE.

Step 8: Observe Your Arduino

1. After uploading, your Arduino board should start executing the code. In the example above, it will blink the
built-in LED on pin 13.

72
Lab Tasks:

Task 1: Blink LED using Arduino

1. Open the Arduino IDE.

2. Create a new project.

3. Write and upload a simple Arduino code to blink an LED connected to one of the digital pins.

4. Explain the code logic and how it controls the LED.

5. Observe the LED blinking.

Task 2: Run Stepper Motor using Arduino

73
74
75
Conclusion:

……………………………………………………………………………………………………………………………………………………………

……………………………………………………………………………………………………………………………………………………………

……………………………………………………………………………………………………………………………………………………………

……………………………………………………………………………………………………………………………………………………………

……………………………………………………………………………………………………………………………………………………………

……………………………………………………………………………………………………………………………………………………………

……………………………………………………………………

76
Experiment 11
Generation of Square Waves with different Frequencies using Timers in PIC 18
Microcontroller
Objective:

• To understand and implement a time delay using Timer1 in a PIC18F452 microcontroller.

Equipment /Tools:

• Oscilloscope
• PIC18F452 microcontroller

Background:

The PIC18 timer is divided into 4 types.


• Timer 0
• Timer 1
• Timer 2
• Timer 3
PIC18 timers can be used to generate a time delay or as a counter to count external events happening outside the
microcontroller.
Timer0 Register:
i. TMR0L and TMR0H:
Timer 0 can be used as 8-bit or a 16-bit timer. The 16-bit register of Timer0 is accessed as TMR0L (low
byte) and TMR0H (high byte).

ii. T0CON:
Each timer has a control register, called TCON, to set various timer operation modes. It is 8-bit register
used for control of Timer0.

iii. TMR0IF flag bit

77
TMR0IF but (Timer0 interrupt flag) is part of the INTCON (interrupt control) register. When the timer
reaches its maximum value of FFFFFH, it rolls over to 0000, and TMR0IF is set to 1

Figure 3 INTCON (interrupt Control Register) has the TMR0IF flag.

Procedure:

1. Load the value into the T0CON register indicating which mode (8-bit or 16-bit) is to be used and the selected
prescaler option. ( T0CON=0x08 for 16-bit no prescale )
2. Load register TMR0H followed by register TMR0L with initial count values.
3. Start the timer with loading 1 value in T0CONbits.TMR0ON ( T0CONbits.TMR0ON=1 )
4. Keep monitoring the timer flag (TMR0IF) to see if it is raised. Get out of the loop when TMR0IF becomes
high. ( while(INTCONbits.TMR0IF==0) )
5. Stop the timer by making T0CONbits.TMR0ON equal to zero. ( T0CONbits.TMR0ON=0 )
6. Clear the TMR0IF flag for the next round.( INTCONbits.TMR0IF==0)
7. Go back to Step 2 to load TMR0H and TMR0L again.

Lab Task

Task 1:

Write a Code to generate a square wave of 100Hz using Timer0. Show your result in Proteus and on Hardware.
Before going to code we must make some calculations to get counts. Timer0 is being used here to generate 100Hz
frequency with 50% duty cycle using XTAL Oscillator of 10 MHz 10 MHz/4 = 2.5 MHz
Period of 1 instruction cycle =1/2.5mhz=0.4us
Code:

Generating the frequency of 100Hz:

1/100Hz=0.01s

0.01*0.5=0.005s //0.5 due to 50% duty cycle

Total time delay(s) =Counts*Period of 1 instruction cycle (s)

Total time delay(s) =Counts*0.4us=0.005s/0.4us=Counts

Counts=12500

65536-12500=53036 Just convert this to hexadecimal you can use MikroC for conversion

=CF2Ch

tmr0h=0xCF

tmr0l=0x2C

Task 2:
Generate a square wave of Frequency 1 KHz with the duty cycle of 65% using Timer0.

78
79
80
Conclusion:

……………………………………………………………………………………………………………………………………………………………

……………………………………………………………………………………………………………………………………………………………

……………………………………………………………………………………………………………………………………………………………

……………………………………………………………………………………………………………………………………………………………

……………………………………………………………………………………………………………………………………………………………

……………………………………………………………………………………………………………………………………………………………

……………………………………………………………………

81
Experiment 12
Serial Communication
Objective:

To establish serial communication between a PIC18F452 microcontroller and a computer using the UART module.

Equipment/Tools:

• PIC18F452 microcontroller
• Breadboard and jumper wires
• Computer with a terminal program (e.g., PuTTY)
• Oscilloscope
• Max-232
• Resistors and Capacitors
Background

Serial Data
Serial data communication uses two methods.
• Synchronous method transfers a block of data at a time.
• Asynchronous method transfers a single byte at a time.
It is possible to write software to use either of these methods, but the programs can be tedious and long. There
are special IC chips made by many manufacturers for serial communications.
• UART (universal asynchronous Receiver-transmitter)
• USART (universal synchronous-asynchronous Receiver-transmitter)
Baud rate:
The rate of data transfer in serial data communication is stated in bps (bits per second). Another widely used
terminology for bps is baud rate.

RS-232 standard:
An interfacing standard RS232 was set by the Electronics Industries Association (EIA) in 1960
The standard was set long before the advent of the TTL logic family, its input and output voltage levels are
not TTL compatible.
• In RS232, a 1 is represented by -3 ~ -25 V, while a 0 bit is +3 ~ +25 V, making -3 to +3 undefined.
MAX232 chip:
PIC18 operates on TTL logic. A line driver such as the MAX232 chip is required to convert RS232 voltage
levels to TTL levels, and vice versa.
Two pins of PIC18 are used specifically for transferring and receiving data serially. These are TX and RX and
are part of PORTC (RC6 and RC7)
• Pin 25 (RC7) is assigned to TX.
• Pin 26 (RC6) is assigned to RX.

82
Procedure:
Programming the PIC18 to transfer data serially
In programming the PIC18 to transfer character bytes serially, the following steps must be taken:
1. The TXSTA register is loaded with the value 20H, indicating asynchronous mode with 8-bit data frame, low
baud rate, and transmit enabled.
2. Make TX pin of PORTC (RC6) an output for data to come out of the PIC.
3. The SPBRG is loaded with one of the values (0FH for 9600, 20H for 4800 if Fosc 10MHz) to set the baud rate
for serial data transfer.
4. SPEN bit in the RCSTA register is set HIGH to enable the serial port of the PIC18.
5. The character byte to be transmitted serially is written into the TXREG register.
6. Monitor the TXIF bit of the PIR1 register to make sure UART is ready for the next byte.
7. To transfer the next character, go to Step 5.
Programming the PIC18 to receive data serially
In programming the PIC18 to receive character bytes serially, the following steps must be taken:
1. The RCSTA register is loaded with the value 90H, to enable the continuous receive in addition to the 8-bit
data size option.
2. The TXSTA register is loaded with the value 00H to choose the low baud rate option.
3. SPBRG is loaded with one of the values (0FH for 9600, 20H for 4800 if Fosc 10 MHz) to set the baud rate.
4. Make the RX pin of PORTC (RC7) an input for data to come into the PIC18.
5. The RCIF flag bit of the PIR1 register is monitored for a HIGH to see if an entire character has been received
yet.
6. When RCIF is raised, the RCREG register has the byte. Its contents are moved into a safe place.
7. To receive the next character, go to Step 5.

Lab Task

Task 1: Write a code to transmit a string “Serial Communication” serially. Perform it in Proteus using virtual Terminal
and on Hardware via RS232 and Max232 using HyperTerminal.

Task 2: Write a code to Receive a data (byte) serially and then transmit back to display it on Hyper Terminal screen.
Perform it in Proteus using virtual Terminal and on Hardware via RS-232 and Max-232 using HyperTerminal.

83
84
Conclusion:

……………………………………………………………………………………………………………………………………………………………

……………………………………………………………………………………………………………………………………………………………

……………………………………………………………………………………………………………………………………………………………

……………………………………………………………………………………………………………………………………………………………

……………………………………………………………………………………………………………………………………………………………

……………………………………………………………………………………………………………………………………………………………

……………………………………………………………………

85
Experiment 13
Using interrupts created by timers and to observe the flow of program when interrupt is
invoked.
Objectives:

• Introduction to Interrupts
• Familiarization with Hardware Interrupts
• Familiarization with Timer Interrupts
Equipment’s /Tools:
• PIC18F452 microcontroller
• LED’s
Background:
A single microcontroller can serve several devices. There are two methods by which devices receive service from
microcontroller.
• Polling
• Interrupts
In Polling microcontroller continuously monitors the state of a given device, when the status conditions are met it
performs the service. The main Drawback of Polling is microcontroller must wait until the time information arrived
or conditions are met So, Due to wasting of time it is an insufficient use of microcontroller.
Interrupt is the signal sent to microcontroller to mark the event that requires immediate attention. In interrupts
once you must enable the corresponding interrupt then you can perform any task and you don’t have to wait. When
conditions are met, the corresponding flag will be raised then your microcontroller leaves all the work and runs the
Interrupt Service routine. For Every Interrupt there must be an interrupt Service routine.
Execution of an Interrupt:
Upon activation of an interrupt microcontroller goes through the following steps.
1. Finishes the instruction being executed and saves the address of the next instruction on the stack.
2. Jumps to a fixed location in memory called the interrupt vector table. The interrupt vector table directs the
microcontroller to the address of Interrupt Service routine.
3. Start to execute the interrupt service routine.
4. Upon executing the last instruction RETFIE the microcontroller returns to the place where it was interrupted,
and this is done by popping.

Sources of interrupts in the PIC18


There are many sources of interrupts in the PIC18, depending on which peripheral is incorporated into the chip. The
following are some of the most widely used sources of interrupts in the PIC18:

1. There is an interrupt set aside for each of the timers, Timers 0, 1, 2, and so on.
2. Three interrupts are set aside for external hardware interrupts. Pins RB0 (PORTB.0), RB1 (PORTB.1), and RB2
(PORTB.2) are for the external hardware interrupts INT0, INT1, and INT2, respectively.
3. Serial communication's USART has two interrupts, one for receive and another for transmit.
4. The PORTB-Change interrupt.
5. The ADC (analog-to-digital converter).
6. The CCP (compare capture pulse-width-modulation).

Enabling and disabling an interrupt

Upon reset, all interrupts are disabled (masked), meaning that none will be responded to by the microcontroller if
they are activated. The interrupts must be enabled (unmasked) by software in order for the microcontroller to
respond to them. The D7 bit of the INTCON (Interrupt Control) register is responsible for enabling and disabling the
interrupts globally. Figure shows the INTCON register. The GIE bit makes the job of disabling all the interrupts easy.

86
Steps in enabling an interrupt

To enable any one of the interrupts, we take the following steps:

1. Bit D7 (GIE) of the INTCON register must be set to HIGH to allow the inter- rupts to happen. This is done with
the "BSF INTCON, GIE" instruction.
2. If GIE 1, each interrupt is enabled by setting to HIGH the interrupt enable (IE) flag bit for that interrupt.
Because there are a large number of interrupts in the PIC18, we have many registers holding the interrupt
enable bit. Figure 11-2 shows that the INTCON has interrupt enable bits for Timer0 (TMROIE) and external
interrupt 0 (INT0IE).
3. As shown in Figures 11-2 and 11-3, for some of the peripheral interrupts such as TMR1IF, TMR2IF, and TXIF,
we have to enable the PEIE flag in addition to the GIE bit.

The PIC18FXX2 devices have multiple interrupt sources and an interrupt priority feature that allows each interrupt
source to be assigned a high priority level or a low priority level. The high priority interrupt vector is at 000008h and
the low priority interrupt vector is at 000018h. High priority interrupt events will override any low priority interrupts
that may be in progress.

There are ten registers which are used to control interrupt operation. These registers are:

• INTCON
• INTCON2
• INTCON3
• RCON
• PIR1, PIR2
• PIE1, PIE2
• IPR1, IPR2

87
INTCON
GIE/GIEH PEIE/GIEL TMR0IE INT0IE RBIE TMR0IF INT0IF RBIF
Bit-7 Bit-6 Bit-5 Bit-4 Bit-3 Bit-2 Bit-1 Bit-0

Bit 7 GIE/GIEH: Global Interrupt Enable bit

When IPEN = 0:
1 = Enables all unmasked interrupts
0 = Disables all interrupts
When IPEN = 1:
1= Enables all high priority interrupts
0 = Disables all interrupts

Bit 6 PEIE/GIEL: Peripheral Interrupt Enable bit

When IPEN = 0:
1 = Enables all unmasked peripheral interrupts
0 = Disables all peripheral interrupts
When IPEN = 1:
1 = Enables all low priority peripheral interrupts
0 = Disables all low priority peripheral interrupts

Bit 5 TMR0IE: TMR0 Overflow Interrupt Enable bit


1 = Enables the TMR0 overflow interrupt
0 = Disables the TMR0 overflow interrupt

Bit 4 INT0IE: INT0 External Interrupt Enable bit


1 = Enables the INT0 external interrupt
0 = Disables the INT0 external interrupt

Bit 3 RBIE: RB Port Change Interrupt Enable bit


1 = Enables the RB port change interrupt
0 = Disables the RB port change interrupt

Bit 2 TMR0IF: TMR0 Overflow Interrupt Flag bit


1 = TMR0 register has overflowed (must be cleared in
software)
0 = TMR0 register did not overflow

Bit-1 INT0IF: INT0 External Interrupt Flag bit


1= The INT0 external interrupt occurred (must be
cleared in software)
0 = The INT0 external interrupt did not occur

Bit-0 RBIF: RB Port Change Interrupt Flag bit


1 = RB7:RB4 pins changed state (must be cleared in
software)
0 = None of the RB7:RB4 pins have changed state

88
INTCON2
RBPU INTEDG0 INTEDG1 INTEDG2 — TMR0IP — RBIP

Bit 7 RBPU: PORTB Pull-up Enable bit


1 = All PORTB pull-ups are disabled
0 = PORTB pull-ups are enabled by individual port latch values

Bit 6 INTEDG0: External Interrupt0 Edge Select bit


1 = Interrupt on rising edge
0 = Interrupt on falling edge

Bit 5 INTEDG1: External Interrupt1 Edge Select bit


1 = Interrupt on rising edge
0 = Interrupt on falling edge

Bit 4 INTEDG2: External Interrupt2 Edge Select bit


1 = Interrupt on rising edge
0 = Interrupt on falling edge

Bit 3 Unimplemented

Bit 2 TMR0IP:TMR0 Overflow Interrupt Priority bit


1 = High priority
0 = Low priority

Bit-1 Unimplemented

Bit-0 RBIP: RB Port Change Interrupt Priority bit


1 = High priority
0 = Low priority

89
INTCON3:
INT2IP INT1IP — INT2IE INT1IE — INT2IF INT1IF

Bit 7 INT2IP: INT2 External Interrupt Priority bit


▪ 1 = High priority
▪ 0 = Low priority

Bit 6 INT1IP: INT1 External Interrupt Priority bit


▪ 1 = High priority
▪ 0 = Low priority

Bit 5 Unimplemented

Bit 4 INT2IE: INT2 External Interrupt Enable bit


▪ 1 = Enables the INT2 external interrupt
▪ 0 = Disables the INT2 external interrupt

Bit 3 INT1IE: INT1 External Interrupt Enable bit


▪ 1 = Enables the INT1 external interrupt
▪ 0 = Disables the INT1 external interrupt

Bit 2 Unimplemented

Bit-1 INT2IF: INT2 External Interrupt Flag bit


▪ 1 = The INT2 external interrupt occurred (must be
cleared in software)
▪ 0 = The INT2 external interrupt did not occur

Bit-0 INT1IF: INT1 External Interrupt Flag bit


▪ 1 = The INT1 external interrupt occurred (must be
cleared in software)
▪ 0 = The INT1 external interrupt did not occur

90
PIR:
PSPIF ADIF RCIF TXIF SSPIF CCP1IF TMR2IF TMR1IF

Bit 7 PSPIF: Parallel Slave Port Read/Write Interrupt Flag bit


▪ 1=A read or write operation has taken place (must be
cleared in software)
▪ 0 = No read or write has occurred

Bit 6 ADIF: A/D Converter Interrupt Flag bit


▪ 1 = An A/D conversion completed (must be cleared in
software)
▪ 0 = The A/D conversion is not complete

Bit 5 RCIF: USART Receive Interrupt Flag bit


▪ 1 = The USART receive buffer, RCREG, is full (cleared when
RCREG is read)
▪ 0 = The USART receive buffer is empty

Bit 4 TXIF: USART Transmit Interrupt Flag bit


▪ 1 = The USART transmit buffer, TXREG, is empty
(cleared when TXREG is written)
▪ 0 = The USART transmit buffer is full

Bit 3 SSPIF: Master Synchronous Serial Port Interrupt Flag bit


▪ 1= The transmission/reception is complete (must be
cleared in software)
▪ 0 = Waiting to transmit/receive

Bit 2 CCP1IF: CCP1 Interrupt Flag bit


Capture mode:
▪ 1 = A TMR1 register capture occurred (must be cleared in
software)
▪ 0 = No TMR1 register capture occurred
Compare mode:
▪ 1 = A TMR1 register compare match occurred (must be
cleared in software)
▪ 0 = No TMR1 register compare match occurred
PWM mode:
Unused in this mode

Bit-1 TMR2IF: TMR2 to PR2 Match Interrupt Flag bit


▪ 1 = TMR2 to PR2 match occurred (must be cleared in
software)
▪ 0 = No TMR2 to PR2 match occurred

Bit-0 TMR1IF: TMR1 Overflow Interrupt Flag bit


▪ 1 = TMR1 register overflowed (must be cleared in
software)
▪ 0 = MR1 register did not overflow

91
LAB TASK
Task 1:

Generate a frequency of 100 Hz by using Timer0 Interrupt.

Task 2:

Detect the falling edge using External Interrupt0 and Show the detection of falling edge by toggling
the led.

92
93
Conclusion:

……………………………………………………………………………………………………………………………………………………………

……………………………………………………………………………………………………………………………………………………………

……………………………………………………………………………………………………………………………………………………………

……………………………………………………………………………………………………………………………………………………………

……………………………………………………………………………………………………………………………………………………………

……………………………………………………………………………………………………………………………………………………………

……………………………………………………………………

94
Experiment 14
Open Ended Lab

95
96
Conclusion:

……………………………………………………………………………………………………………………………………………………………

……………………………………………………………………………………………………………………………………………………………

……………………………………………………………………………………………………………………………………………………………

……………………………………………………………………………………………………………………………………………………………

……………………………………………………………………………………………………………………………………………………………

……………………………………………………………………………………………………………………………………………………………

……………………………………………………………………

97

You might also like