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

Microcontroller Lab Manual

Uploaded by

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

Microcontroller Lab Manual

Uploaded by

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

DEPARTMENT OF ELECTRONICS & TELECOMMUNICATION

ENGINEERING

Academic Year 2023-24

MICROCONTROLLER
LABORATORY MANUAL

TE 1st Semester

People’s Empowerment Group


ISB&M COLLEGE OF ENGINEERING
S. No. 44/1, 44/1/2, Nande Village Tal: Mulshi, Pune – 412 115
People’s Empowerment Group

ISB&M COLLEGE OF ENGINEERING


S. No. 44/1, 44/1/2, Nande Village Tal: Mulshi, Pune – 412 115

DEPARTMENT OF ELECTRONICS & TELECOMMUNICATION


ENGINEERING

MICROCONTROLLER
LABORATORY MANUAL

Student Name:……………………………………………………

Roll No:………………………………………………………………

Branch:……………………………..Section ……………………

Year …………………………Semester………………………..

FACULTY INCHARGE
INSTRUCTIONS TO STUDENTS

• Before entering the lab the student should carry the following things.
o Identity card issued by the college.
o Class notes
o Lab observation book
o Lab Manual
o Lab Record
• Student must sign in and sign out in the register provided when attending the lab session without
fail.
• Come to the laboratory in time. Students, who are late more than 15 min., will not be allowed to
attend the lab.
• Students need to maintain 100% attendance in lab if not a strict action will be taken.
• All students must follow a Dress Code while in the laboratory
• Foods, drinks are NOT allowed.
• All bags must be left at the indicated place.
• The objective of the laboratory is learning. The experiments are designed to illustrate phenomena
in different areas of Physics and to expose you to measuring instruments, conduct the experiments
with interest and an attitude of learning
• You need to come well prepared for the experiment.
• Work quietly and carefully
• Be honest in recording and representing your data.
• If a particular reading appears wrong repeat the measurement carefully, to get a better fit for a
graph
• All presentations of data, tables and graphs calculations should be neatly and carefully done
• Graphs should be neatly drawn with pencil. Always label graphs and the axes and display units.
• If you finish early, spend the remaining time to complete the calculations and drawing graphs.
Come equipped with calculator, scales, pencils etc.
• Do not fiddle with apparatus. Handle instruments with care. Report any breakage to the Instructor.
Return all the equipment you have signed out for the purpose of your experiment.
SPECIFIC SAFETY RULES FOR BEE LABORATORY

• You must not damage or tamper with the equipment or leads.

• You should inspect laboratory equipment for visible damage before using it. If there is a
problem with a piece of equipment, report it to the technician or lecturer. DONOT return
equipment to a storage area
• You should not work on circuits where the supply voltage exceeds 40 volts without very
specific approval from your lab supervisor. If you need to work on such circuits, you should
contact your supervisor for approval and instruction on how to do this safely before
commencing the work.
• Always use an appropriate stand for holding your soldering iron.
• Turn off your soldering iron if it is unlikely to be used for more than 10 minutes.
• Never leave a hot soldering iron unattended.
• Never touch a soldering iron element or bit unless the iron has been disconnected
from themains and has had adequate time to cool down.
• Never strip insulation from a wire with your teeth or a knife, always use an appropriate
wirestripping tool.
• Shield wire with your hands when cutting it with a pliers to prevent bits of wire flying
about the bench.
CONTENTS

Page
S.No Name of the experiment
Number
Simple program on memory Transfer
1 1-3
Parallel Port interfacing of LEDS
2 4-7
Interfacing of Multiplexed 7-segment display
3 8-10
Interfacing Push buttons, LEDs, Relay & Buzzer to PIC Microcontroller
4 11-19
Interfacing LCD to Display Message
5 20-25
6 Interfacing of Stepper motor to 8051- software delay using 26-29
Timer

On-chip ADC Programming


7 30-43
Generation of PWM Signal
8 44-58
ISB&M COE

Experiment No: 01

TITLE: Simple program on memory Transfer

S/W PACKAGES AND H/W USED: keil uvision 5, , 8051 Development Board

THEORY:
The microcontroller like 8051 was designed in the year 1981 by Intel. The microcontroller is one
kind of integrated circuit that includes 40-pins with dual inline package or DIP, RAM-128 bytes,
ROM-4kb & 16-bit timers–2. Based on the requirement, it includes addressable & programmable
4 – parallel 8-bit ports. In the 8051 microcontroller architecture, the system bus plays a key role to
connect all the devices to the central processing unit. This bus includes a data bus- an 8-bit, an
address bus-16-bit & bus control signals. Other devices can also be interfaced throughout the
system bus like ports, memory, interrupt control, serial interface, the CPU, timers.

There are two buses in 8051 Microcontroller one for the program and another for data. As a result,
it has two storage rooms for both programs and data of 64K by 8 sizes. The microcontroller
comprises of 8-bit accumulator & an 8-bit processing unit. It also consists of 8 bit B register as
majorly functioning blocks and 8051 microcontroller programming is done with embedded C
language using Keil software. It also has several other 8 bit and 16-bit registers.
For internal functioning & processing Microcontroller, 8051 comes with integrated built-in RAM.
This is prime memory and is employed for storing temporary data. It is an unpredictable memory
i.e. its data can get be lost when the power supply to the Microcontroller switched OFF. This
microcontroller is very simple to use, affordable less computing power, simple architecture &
instruction set.
The micro-controller needs a program that is a set of commands. This program enlightens the
Microcontroller to perform precise tasks. These programs need a storage space on which they can
be accumulated and interpret by the Microcontroller to act upon any specific process. The memory
which is brought into play to accumulate the program of the Microcontroller is recognized as
Program memory or code memory. In common language, it’s also known as Read-Only Memory
or ROM.

The microcontroller also needs memory to amass data or operands for the short term. The storage
space which is employed to momentarily data storage for functioning is acknowledged as Data
Memory and we employ Random Access Memory or RAM for this principle reason.
Microcontroller 8051 contains code memory or program memory 4K so which has 4KB Rom and
it also comprises data memory (RAM) of 128 bytes.
The main features of the 8051 microcontroller architecture include the following.
• 8-bit CPU through two Registers A & B.
• 8K Bytes – Internal ROM and it is a flash memory that supports while programming the system.
• 256 Bytes – Internal RAM where the first RAM with 128 Bytes from 00H to 7FH is once more
separated into four banks through 8 registers in every bank, addressable registers -16 bit &
general-purpose registers – 80.
• The remaining 128 bytes of the RAM from 80H to FFH include Special Function Registers

Electronics & Telecommunication Engineering


Page 1
ISB&M COE

(SFRs). These registers control various peripherals such as Serial Port, Timers, all I/O Ports, etc.
• Interrupts like External-2 & Internal-3
• Oscillator & CLK Circuit.
• Control Registers like PCON, SCON, TMOD, TCON, IE, and IP.
• 16-bit Timers or Counters -2 like T0 & T1.
• Program Counter – 16 bit & DPRT (Data Pointer).
• I/O Pins – 32 which are arranged like four ports such as P0, P1, P2 & P3.
• Stack Pointer (SP) – 8bit & PSW (Processor Status Word).
• Serial Data Tx & Rx for Full-Duplex Operation

SOURCE CODE:

#include<reg51.h>
int main()
{
unsigned char xdata *p;
p = ( unsigned char *) 0x8000;
*p=0x10;
&p++;
*p=0x20;
&p++;
B=*p;
return 0;
}

OUTPUT:

Electronics & Telecommunication Engineering


Page 2
ISB&M COE

RESULT:

Electronics & Telecommunication Engineering


Page 3
ISB&M COE

EXPERIMENT NO: 02
TITLE: Parallel Port interfacing of LEDS

PROBLEM STATEMENT:
Parallel port interacting of LEDS-
1. Flashing of Leds connected to Port 2
2. Switch off all the Leds connected to Port2 and blink only one led connected to P2.1
3. Program to show L-R & R-L Shifting

S/W PACKAGES AND H/W USED: keil u vision 5, , 8051 Development Board

THEORY:
The microcontroller like 8051 was designed in the year 1981 by Intel. The microcontroller is one kind of
integrated circuit that includes 40-pins with dual inline package or DIP, RAM-128 bytes, ROM-4kb &
16-bit timers–2. Based on the requirement, it includes addressable & programmable 4 – parallel 8-bit
ports. In the 8051 microcontroller architecture, the system bus plays a key role to connect all the devices
to the central processing unit. This bus includes a data bus- an 8-bit, an address bus-16-bit & bus control
signals. Other devices can also be interfaced throughout the system bus like ports, memory, interrupt
control, serial interface, the CPU, timers.
LED (Light Emitting Diode)

LED is a semiconductor device used in many electronic devices, mostly used for signal transmission
/power indication purposes. It is very cheaply and easily available in a variety of shape, color, and size.
The LEDs are also used for design message display boards and traffic control signal lights etc.
It has two terminals positive and negative as shown in the figure.

The only way to know polarity is either to test it with a multimeter or by carefully observing inside the
LED. The larger end inside the led is -ve (cathode) and the shorter one is +ve (anode), that is how we
Electronics & Telecommunication Engineering
Page 4
ISB&M COE

find out the polarity of the LED. Another way to recognize the polarity is, connecting leads, POSITIVE
terminal has more length than NEGATIVE terminal.

LED Interfacing to 8051

There are two ways which we can interface LED to the Microcontroller 8051. But the connections and
programming techniques will be different. This article provides the information on LED interfacing with
8051 and LED blinking code for AT89C52/ AT89C51 Microcontroller.

Interfacing LED to 8051 Methods

Observe carefully the interface LED 2 is in forward biased because the input voltage of 5v connected to
the positive terminal of the LED, So here the Microcontroller pin should be at LOW level. And vice
versa with the interface 1 connections.

The resistor is important in LED interfacing to limit the flowing current and avoid damaging the LED
and/or MCU.
• Interface 1 will glow LED, only if the PIN value of the MC is HIGH as current flows towards the
ground.
• Interface 2 will glow LED, only if the PIN value of the MC is LOW as current flows towards PIN
due to its lower potential.
SOURCE CODE:

1. Flashing of Leds connected to Port 2

#include<reg51.h> //header file//


void delay(unsigned int count) //the program execution stat point//
{

Electronics & Telecommunication Engineering


Page 5
ISB&M COE

unsigned int i; //data type//


while(count) //for continuous loop//
{
i=115;
while(i>0)
i--;
count--;
}
}
void main() //the program execution stat point//
{
while(1)
{
P2=0x00; //send the hexa value to the port2//
Delay(1000);
P2=0xFF; //send the hexa value to the port2//
Delay(1000);
}
}
2. Switch off all the Leds connected to Port2 and blink only one led connected to P2.1
#include<reg51.h> //header file//
void delay(unsigned int count) //the program execution stat point//
{
unsigned int i; //data type//
while(count) //for continuous loop//
{
i=115;
while(i>0)
i--;
Count--;
}
}
sbit led1=P2^1;
void main() //the program execution stat point//
{
P2=0x00; //send the hexa value to the port2//
while(1)
{
led1=0;
Delay(1000);
led1=1;
Delay(1000);
}
}

Electronics & Telecommunication Engineering


Page 6
ISB&M COE

3. Program to show L-R & R-L Shifting:


Program Description In this program we try to glow all seven LED‟s in different formats (from L → R ,
R → L , even , odd). Initialize with LED address.For LED‟s to glow from Right to Left (R → L) one
after the the other set the counter c=0 and increment the counter by one till the value reaches c=7and in
between call set and clear LED function. LED‟s glow from Left to Right (L → R) one after the the
other). Initialize with LED address. For LED‟s to glow from Right to Left (R → L) one after the the
other set the counter c=7 and decrement the counter by one till the value reaches c=0and in between call
set and clear LED function.
#include<REGX51.H>
#define LED P2
void delay(unsigned int d);
int main(void)
{
unsigned int i;
while(1)
{
LED=0X01;
for(i=0;i<7;i++)
{
delay(1000);
LED=LED<<=0X01;
}
LED=0X80;
for(i=0;i<=7;i++)
{
delay(1000);
LED=LED>>=0X01;
}}}
void delay(unsigned int d)
{
unsigned i,j;
for(i=0;i<d;i++)
for(j=0;j<101;j++);
}

OUTPUT:

Electronics & Telecommunication Engineering


Page 7
ISB&M COE

EXPERIMENT NO: 03
TITLE: Interfacing of Multiplexed 7-segment display

PROBLEM STATEMENT:
Write an Embedded C program to display number 0-9 on SSD with 8051

S/W PACKAGES AND H/W USED:


keil uvision 5, , 8051 Development Board

THEORY:
The 7-segment display, also written as “seven segment display”, consists of seven LEDs (hence
its name) arranged in a rectangular fashion as shown. Each of the seven LEDs is called a segment
because when illuminated the segment forms part of a numerical digit (both Decimal and Hex) to be
displayed. An additional 8th LED is sometimes used within the same package thus allowing the
indication of a decimal point, (DP) when two or more 7-segment displays are connected together to
display numbers greater than ten. Each one of the seven LEDs in the display is given a positional
segment with one of its connection pins being brought straight out of the rectangular plastic package.
These individually LED pins are labelled from a through to g representing each individual LED. The
other LED pins are connected together and wired to form a common pin.So by forward biasing the
appropriate pins of the LED segments in a particular order, some segments will be light and others will
be dark allowing the desired character pattern of the number to be generated on the display. This then
allows us to display each of the ten decimal digits 0 through to 9 on the same 7-segment display. The
displays common pin is generally used to identify which type of 7-segment display it is. As each LED
has two connecting pins, one called the “Anode” and the other called the “Cathode”, there are therefore
two types of LED 7-segment display called: Common Cathode (CC) and Common Anode (CA). The
difference between the two displays, as their name suggests, is that the common cathode has all the
cathodes of the 7-segments connected directly together and the common anode has all the anodes of the
7-segments connected together and is illuminated as follows.The Common Cathode (CC) – In the
common cathode display, all the cathode connections of the LED segments are joined together to logic
“0” or ground. The individual segments are illuminated by application of a “HIGH”, or logic “1” signal
via a current limiting resistor to forward bias the individual Anode terminals (a-g).

Common Anode

Electronics & Telecommunication Engineering


Page 8
ISB&M COE

Common Cathode

Electronics & Telecommunication Engineering


Page 9
ISB&M COE

SOURCE CODE:
#include <reg51.h>
unsigned char array[]={0x40,0x79,0x24,0x30,0x19,0x12,0x02,0x02,0x78,0x00,0x18}; //common
anode values
void main()
{
unsigned char i;
for(i=0;i<11;i++)
{
P0=array[i];
}
}

OUTPUT:

Electronics & Telecommunication Engineering


Page 10
ISB&M COE

EXPERIMENT NO: 04
TITLE: Interfacing Push buttons, LEDs, Relay & Buzzer to PIC Microcontroller

PROBLEM STATEMENT:
Interface Push buttons, LEDs, Relay and Buzzer to PIC Microcontroller. Write a program in
Embedded C to interact with peripherals as follows.
a. LED’s start chasing from left to right and turn ON Relay, buzzer whenever pushbutton 1 is
pressed.
b. LED’s start chasing from right to left and turn OFF Relay, buzzer whenever pushbutton 2 is
pressed.

OBJECTIVE:
a. To understand the PORT Structure of PIC Microcontroller.
b. To study the SFRs to control the PORT Pins.
c. To interface common peripherals like pushbuttons, LEDs, relay.
d. To understand the use of MPLAB IDE and C18 Compiler.
e. To write a simple program in Embedded C.

S/W PACKAGES AND H/W USED:MPLAB IDE, C18 Compiler, Explore PIC Development Board

THEORY
Depending on the device selected, there are up to five general purpose I/O ports available on PIC18F
Microcontroller devices. Some pins of the I/O ports are multiplexed with an alternate function from the
peripheral features on the device. In general, when a peripheral is enabled, that pin may not be used as a
general purpose I/O pin.

1. Some common Features of the I/O Ports


• Up to 70 bi-directional I/O pins
o Some multiplexed with peripheral functions
• High drive capability
o 25mA source/sink capability
• Direct, single cycle bit manipulation
• 4kV ESD protection diodes
o Based on human body model
• After reset:
o Digital I/O default to Input (Hi-Z)
o Analog capable pins default to analog

Electronics & Telecommunication Engineering


Page 11
ISB&M COE

2. SFR Associated with I/O Port


Each port has three registers for its operation and figure 1.1 and figure 1.2 showsthe functioning of each
registers:
TRIS register (Data Direction register): To select PORT pin as input or output. All port pins are input by
default. Whenever a bit in the TRISx register is a 0, the corresponding bit in PORTx is an output. If the
bit in TRISx is a 1, the corresponding bit in PORTx is an input.
PORT register (reads the levels on the pins of the device)

LAT register (output latch): The data latch (LAT register) is useful for read-modify-write operations
on the value that the I/O pins are driving.
I/OPin Direction Control

TRISB 1 101 10 0 0

PORTB In InOutIn InOut OutOut

Figure 1.1 :TRISx Register

Electronics & Telecommunication Engineering


Page 12
ISB&M COE

2.1 Register Map:

SFR Description Access Reset Value Address

PORTA : RA6 – RA0

TRISA PORTA Direction Register Read/Write 0x7F 0xF92

PORTA PORTA Read/Write Register Read/Write unknown 0xF80

LATA PORTA Output Latch Register Read/Write unknown 0xF89

PORTB: RB7 - RB0

TRISB PORTB Direction Register Read/Write 0xFF 0xF93

PORTB PORTB Read/Write Register Read/Write unknown 0xF81

LATB PORTB Output Latch Register Read/Write unknown 0xF8A

PORTC: RC7 - RC0

TRISC PORTC Direction Register Read/Write 0xFF 0xF94

PORTC PORTC Read/Write Register Read/Write unknown 0xF82

LATC PORTC Output Latch Register Read/Write unknown 0Xf8B

PORTD: RD7 - RD0

TRISD PORTD Direction Register Read/Write 0xFF 0xF95

PORTD PORTD Read/Write Register Read/Write unknown 0xF83

LATD PORTD Output Latch Register Read/Write unknown 0xF8C

PORTD: RE2 – RE1

TRISE PORTE Direction Register Read/Write 0x07 0xF96

PORTE PORTE Read/Write Register Read/Write unknown 0xF84

LATE PORTE Output Latch Register Read/Write unknown 0xF8D

Electronics & Telecommunication Engineering


Page 13
ISB&M COE

2.2 Port Pin Diagram

Fig. 1.3(PIC18F4520 Pins Fig. 1.3(a) – PIC18F4550 Pin

3. Generic I/O Port structure:


All the ports of PIC18 are bidirectional and identical. They all have the following four
components in their structure as shown in figure 1.3.
1. DATA LATCH
2. OUTPUT DRIVER
3. INPUT BUFFER
4. TRIS LATCH
The PIC18 Ports have both the latch and buffer. Therefore, when reading the ports there are two
possibilities
1. Reading the input pin
2. Reading the latch

Electronics & Telecommunication Engineering


Page 14
ISB&M COE

Figure 1.4: Generic I/O Port Operation

3.1 PORTA, TRISA and LATA Registers


• PORTA is an 8-bit wide, bidirectional port.
• The RA4 pin is multiplexed with the Timer0 module clock input to become the RA4/T0CKI pin.
• The RA6 pin is multiplexed with the main oscillator pin; it is enabled as an oscillator or I/O pin
by the selection of the main oscillator in Configuration Register.

• Several PORTA pins are multiplexed with analog inputs, the analog VREF+ and VREF- inputs
and the comparator voltage reference output.
• The operation of pins RA5 and RA3:RA0 as A/D converter inputs is selected by clearing/setting
the control bits in the ADCON1 register.
• On a Power-on Reset, RA5 and RA3:RA0 are configured as analog inputs and read as ‘0’. RA4
is configured as a digital input.

3.2 PORTB, TRISB and LATB Registers


• PORTB is an 8-bit wide, bidirectional port.
• Each of the PORTB pins has a weak internal pull-up. A single control bit can turn on all the pull-
ups. This is performed by clearing bit RBPU (INTCON2 register). The weak pull-up is
automatically turned off when the port pin is configured as an output. The pull-ups are disabled
on a Power-on Reset.
• Four of the PORTB pins (RB7:RB4) have an interrupt on change feature. Only pins configured
as inputs can cause this interrupt to occur (i.e., any RB7:RB4 pin configured as an output is

Electronics & Telecommunication Engineering


Page 15
ISB&M COE

excluded from the interrupt on change comparison). The input pins (of RB7:RB4) are compared
with the old value latched on the last read of PORTB. The “mismatch” outputs of RB7:RB4 are
ORed together to generate the RB Port Change Interrupt with Flag bit RBIF (INTCON register).
• On a Power-on Reset, RB4:RB0 are configured as analog inputs by default and read as ‘0’;
RB7:RB5 are configured as digital inputs. By programming the configuration bit, PBADEN,
RB4:RB0 will alternatively be configured as digital inputs on POR.

3.3 PORTC, TRISC and LATC Registers


• PORTC is an 8-bit wide, bidirectional port.
• PORTC is multiplexed with several peripheral functions. PORTC is primarily multiplexed with
serial communication modules, including the EUSART, MSSP module and the USB module.
• PORTC pins have Schmitt Trigger input buffers.
• When enabling peripheral functions, care should be taken in defining TRIS bits for each PORTC
pin.
• Some peripherals override the TRIS bit to make a pin an output, while other peripherals override
the TRIS bit to make a pin an input.
• The user should refer to the corresponding peripheral section for the correct TRIS bit settings.
The pin override value is not loaded into the TRIS register.
• This allows read-modify-write of the TRIS register, without concern due to peripheral overrides.
• In PIC18F2455/2550/4455/4550 devices, the RC3 pin is not implemented.
• On a Power-on Reset, these pins are configured as digital inputs.

3.4 PORTD, TRISD and LATD Registers


• PORTD is an 8-bit wide, bidirectional port.
• All pins on PORTD are implemented with Schmitt Trigger input buffers.
• Three of the PORTD pins are multiplexed with outputs P1B, P1 and P1D of the enhanced
CCP module.
• PORTD can also be configured as an 8-bit wide microprocessor port (Parallel Slave Port (PSP)
or Streaming Parallel Port (SPP)). In this mode , the input buffers are TTL.
• On a Power-on Reset, these pins are configured as digital inputs.

3.5 PORTE, TRISE and LATE Registers


• For 40/44-pin devices, PORTE is a 4-bit wide port.
• Three pins (RE0/RD/AN5, RE1/WR/AN6 and RE2/CS/AN7) are individually configurable as
inputs or outputs.
• These pins have Schmitt Trigger input buffers. When selected as an analog input, these pins will
read as ‘0’s.
• The fourth pin of PORTE (MCLR/VPP/RE3) is an input only pin. Its operation is controlled by
the M CLRE configuration bit. When selected as a port pin
(MCLRE = 0), it functions as a digital input only pin; as such, it does not have TRIS or LAT bits
associated with its operation. Otherwise, it functions as the device’s Master Clear input. In either
configuration, RE3 also functions as the programming voltage input during programming.

Electronics & Telecommunication Engineering


Page 16
ISB&M COE

• For 28-pin devices, P ORTE is only available when Master Clear functionality is disabled
(MCLRE = 0 ). In these cases, PORTE is a single bit, input only port comprised of RE3 only .
• On a Power-on Reset, RE2:RE0 are configured as analog inputs. On a Power-on Reset, RE3 is
enabled as a digital input only if Master Clear functionality is disabled.

5. Algorithm
1. As LED connected to PORTD configure these pins as output by writing 0x00 to the appropriated
TRES register.
2. As buttons are connected to RB.4 and RB.5 so configure these pins as input by writing 1 to the
appropriated bits of TRES register.
3. Check the status of RB.4, if it is zero then move 1 bit of PORTB from right to left.
4. Else check the status of RB.5, if it is zero then move 1 bit of PORTB from left to right.
5. Repeat step 3 to 4

6. Source Code

//Expt.1: Interfacing LEDs, Switches, Buzzer and Relay


//Includes
#include <p18f4550.h> //Include Controller specific .h
#include "vector_relocate.h" //Vector Remapping for USB HID Bootloader

//Declarations
#define lrbit PORTBbits.RB4 //SW1 interfaced to RB4
#define rlbit PORTBbits.RB5 //SW2 interfaced to RB5
#define buzzer PORTCbits.RC2 //Buzzer interfaced to RC2
#define relay PORTCbits.RC1 //Relay interfaced to RC1

Electronics & Telecommunication Engineering


Page 17
ISB&M COE

//Function Prototypes
void msdelay (unsigned int time);//Function for delay

//Start of Program Code


void main() //Main Program
{
unsigned char val=0; //Variable to latch the switch condition
INTCON2bits.RBPU=0; //To Activate the internal pull on PORTB
ADCON1 = 0x0F; //To disable the all analog inputs

TRISBbits.TRISB4=1; //To configure RB4 as input for sensing SW0


TRISBbits.TRISB5=1; //To configure RB5 as input for sensing SW1

TRISCbits.TRISC1=0; //To configure RC1 (relay) as output


TRISCbits.TRISC2=0; //To configure RC2 (buzzer) as output
TRISD = 0x00; //To configure PORTD (LED) as output

PORTD = 0x00; //Initial Value for LED


buzzer = 0; //Initial Value for Buzzer
relay = 0; //Initial Value for Relay

while (1) //While loop for repeated operation


{
if (!(lrbit)) //To check whether SW0 is pressed
val = 1; // Latch the status of switch SW0
if (!(rlbit)) //To check whether SW1 is pressed
val = 2; // Latch the status of switch SW1

if (val == 1)
{
buzzer = 1;
relay = 1;
PORTD = PORTD >>1; //Shift left by 1 bit
if (PORTD == 0x00)
PORTD = 0x80; // Make the MSB bit equal to 1
msdelay(250);
}
if (val == 2)
{
buzzer = 0;
relay = 0;
PORTD = PORTD<<1; //Shift right by 1 bit
if (PORTD == 0x00)
PORTD = 0x01; // Make the LSB bit eqaul to 1
msdelay(250);
}
}
} //End of the Program

//Function Definitions
Electronics & Telecommunication Engineering
Page 18
ISB&M COE

void msdelay (unsigned int time)//Function for delay


{
unsigned int i, j;
for (i = 0; i < time; i++)
for (j = 0; j < 710; j++); //Calibrated for a 1 ms delay in MPLAB
}
Conclusion

Electronics & Telecommunication Engineering


Page 19
ISB&M COE

EXPERIMENT NO: 05
TITLE: Interfacing LCD to Display Message

PROBLEM STATEMENT: Interface 16x2 LCD to PIC Microcontroller in 8-bit Mode. Write a
program in Embedded C to display user defined messages on LCD without using standard library
functions.
OBJECTIVE:
c. To understand the working of Liquid Crystal Display (LCD).
d. To study the LCD interfacing modes and Timing diagram.
e. To study and use of the LCD commands to drive LCD.
f. To interface LCD in 8-bit mode to PIC Microcontroller
S/W PACKAGES AND H/W USED:
MPLAB IDE, C18 Compiler, Explore PIC Development Board
THEORY
1. LCD Interfacing
In recent years the LCD is finding widespread use replacing LED’s. This is due to the following
reason:
f. The declining prices of LCD.
g. The ability to display numbers, characters, and graphics. This is in contrast to LEDs, which are
limited to numbers and few characters.
h. In corporation of a refreshing controller into the LCD, thereby reliving the CPU of the task of
refreshing the LCD. In contrast, the LED must be refreshed by the CPU to keep displaying the
data.
i. Ease of programming for characters and graphics.
Most of LCD’s available in the market are based on controller HD44780. The LCD display can
be interfaced either in 4-bit interface or 8-bit interface mode.

1.1 LCD pin descriptions:


1.1.1 Vcc, Vss and Vee:
While Vcc and Vss provide +5V and ground, repectively, Vee is used for controlling LCD
contrast.
2. Register Select (RS): There are two very important registers inside the LCD. The RS pin is used for
their selection as follows.
a. RS = 0: the instruction command code register is selected, allowing the user to send a command
such as clear display, cursor at home.
b. RS = 1: the data register is selected, allowing the user to send the data to be displayed on the
LCD.
1.1.3 Read/write (R/W): R/W input allows the user to write information to the LCD or read
Electronics & Telecommunication Engineering
Page 20
ISB&M COE

information from it. R/W = 1 when reading, R/W = 0 when writing.

1.1.4 Enable (EN): The enable pin is used by the LCD to latch information presented to its data pins.
When data is supplied to data pins, a high to low pulse must be applied to the pin in order for the
LCD to latch in the data present at the data pins. This pulse must be a minimum of 450ns wide.

1.1.5 Data bus (D0 – D7): The 8-bit data pins, D0-D7 are used to send the information to the LCD or
read the contents of the LCD’s internal registers. To display the numbers and letters, we send ASCII
codes to these pins while making RS=1.
There are also instruction command codes that can be sent to the LCD to clear the display or blink the
cursor.
We also use RS = 0 to check the busy flag bit to see if the LCD is ready to receive information. The
busy flag is D& and can be read when R/W = 1 and RS=0. When D7 =1, the LCD is busy taking care of
internal operations and will not accept any new information. When D7 = 0, the LCD is ready to receive
new information.
1.2 Pin Assignment of 16x2 LCD

Pin number Symbol Level I/O Function

1 Vss - - Power supply (GND)

2 Vcc - - Power supply (+5V)

3 Vee - - Contrast adjust

4 RS 0/1 I 0 = Instruction input


1 = Data input

5 R/W 0/1 I 0 = Write to LCD module


1 = Read from LCD module

6 E 1, 1->0 I Enable signal

7 DB0 0/1 I/O Data bus line 0 (LSB)

Electronics & Telecommunication Engineering


Page 21
ISB&M COE

8 DB1 0/1 I/O Data bus line 1

9 DB2 0/1 I/O Data bus line 2

10 DB3 0/1 I/O Data bus line 3

11 DB4 0/1 I/O Data bus line 4

12 DB5 0/1 I/O Data bus line 5

Pin number Symbol Level I/O Function

13 DB6 0/1 I/O Data bus line 6

14 DB7 0/1 I/O Data bus line 7 (MSB)

15 VB+ 1 -

Backlight Supply
16 VB- 0 -

Electronics & Telecommunication Engineering


Page 22
ISB&M COE

1.3 Timing Diagram for 16x2 LCD

1.4 LCD command codes

Sr. No. Command to LCD instruction Code (Hex)

01 Clear display screen 01

02 Return home 02

03 Decrement cursor (shift cursor to left) 04

04 Increment cursor (shift cursor to right) 06

05 Shift display right 05

06 Shift display left 07

07 Display off, cursor off 08

08 Display off, cursor on 0A

09 Display on, cursor off 0C

10 Display on cursor blinking 0E

11 Shift cursor position to left 10

12 Shift cursor position to right 14

Electronics & Telecommunication Engineering


Page 23
ISB&M COE

13 Shift the entire display to left 18

14 Shift the entire display to right 1C

15 Force cursor to beginning of 1st line. 80


16 Force cursor to beginning of 2nd line. C0
17 2 lines and 5x7 matrixes. 38

5. Algorithm
As LCD data bus is connected to PORTD and handshaking signal EN-RE0, RS-RE1, E-RE2,
configure these pins output writing 0x00 to the appropriated TRES register.
The RE0, RE1, RE2 this pins have dual function (analog/digital), by default on every reset it
work as analog input. So make this pin as digital by using ADCON1 register.

Initialize LCD.
a. Write a commands {2 line and 5X7 matrix (0x38), Display ON cursor OFF (0x0C),
Increment & shift cursor right (0x06), Clear display screen (0x01) to LCD}.

Electronics & Telecommunication Engineering


Page 24
ISB&M COE

4. Display message on first line.


a. Write a command 0x80 to LCD.
b. Load ASCII character from the given string.
c. Write data to L CD
d. Repeat 2 and 3 sixteen times.
5. Display message on Second line.
a. Write a command 0xC0 to LCD.
b. Load ASCII character from the given string.
c. Write data to L CD
d. Repeat 2 and 3 sixteen times.
6. Endless Loop

Electronics & Telecommunication Engineering


Page 25
ISB&M COE

EXPERIMENT NO: 06

TITLE: Interfacing of Stepper motor to 8051- software delay using Timer

S/W PACKAGES AND H/W USED: keil uvision 5, , 8051 Development Board

THEORY:
A Stepper Motor or a step motor is a brushless, synchronous motor which divides a full
rotation into a number of steps. Unlike a brushless DC motor which rotates continuously
when a fixed DC voltage is applied to it, a step motor rotates in discrete step angles. The
Stepper Motors therefore are manufactured with steps per revolution of 12, 24, 72, 144,
180, and 200, resulting in stepping angles of 30, 15, 5, 2.5, 2, and 1.8 degrees per step.
The stepper motor can be controlled with or without feedback. Stepper motors work on
the principle of electromagnetism. There is a soft iron or magnetic rotor shaft surrounded
by the electromagnetic stators. The rotor and stator have poles which may be teethed or
not depending upon the type of stepper. When the stators are energized the rotor moves to
align itself along with the stator (in case of a permanent magnet type stepper) or moves to
have a minimum gap with the stator (in case of a variable reluctance stepper). This way
the stators are energized in a sequence to rotate the stepper motor.

INTERFACING DIAGRAM:

Electronics & Telecommunication Engineering


Page 26
ISB&M COE

SOURCE CODE :

#include<reg52.h>
#include<stdio.h>

void delay(int);

void main()
{
do
{
P2=0x01; //0001
delay(1000);
P2=0x02; //0010
delay(1000);
P2=0x04; //0100
delay(1000);
P2=0x08; //1000
delay(1000);
}
while(1);
}

Electronics & Telecommunication Engineering


Page 27
ISB&M COE

void delay(int k)
{
int i,j;
for(i=0;i<k;i++)
{
for(j=0;j<100;j++)
{}
}
}

Code for Full Drive

#include<reg52.h>
#include<stdio.h>

void delay(int);

void main()
{
do
{
P2 = 0x03; //0011
delay(1000);
P2 = 0x06; //0110
delay(1000);
P2 = 0x0C; //1100
delay(1000);
P2 = 0x09; //1001
delay(1000);
}
while(1);
}

void delay(int k)
{
int i,j;
for(i=0;i<k;i++)
{
for(j=0;j<100;j++)
{}
}
}

Electronics & Telecommunication Engineering


Page 28
ISB&M COE

Code for Half Drive

#include<reg52.h>
#include<stdio.h>

void delay(int);

void main()
{
do
{
P2=0x01; //0001
delay(1000);
P2=0x03; //0011
delay(1000);
P2=0x02; //0010
delay(1000);
P2=0x06; //0110
delay(1000);
P2=0x04; //0100
delay(1000);
P2=0x0C; //1100
delay(1000);
P2=0x08; //1000
delay(1000);
P2=0x09; //1001
delay(1000);
} while(1);
}

void delay(int k)
{
int i,j;
for(i=0;i<k;i++)
{
for(j=0;j<100;j++)
{}
}
}

OUTPUT:

Electronics & Telecommunication Engineering


Page 29
ISB&M COE

EXPERIMENT NO: 07

TITLE: On-chip ADC Programming

PROBLEM STATEMENT: Interface analog voltage 0 – 5v to PIC microcontroller and Write a


program in Embedded C to convert analog voltage into digital using on-chip ADC Module. Display the
Digital result in BCD / Voltage form on 16x2 LCD display.

OBJECTIVE :

g. To understand the working of A/D converter.


h. To study the on-chip ADC section of PIC Microcontroller.
i. To interface analog input to PIC Microcontroller

S/W PACKAGES AND H/W USED: MPLAB IDE, C18 Compiler, Explore PIC Development Board

THEORY:
1. ADC Devices:
Analog to digital converters are among the most widely used devices for data
acquisitions. Digital computers use binary (discrete) value but in physical world everything is analog
(continuous). A physical quantity is converted to electrical signals using device called transducer or also
called as sensors. Sensors and many other natural quantities produce an output that is voltage (or
current). Therefore we need an analog - to - digital converter to translate the analog signal to digital
numbers so that the microcontroller can read and process them.
The ADC chips are either parallel or serial. In parallel ADC, we have 8 or more pins dedicated to bring
out the binary data, but in serial ADC we have only one pin for data out.
Some of the major characteristics of ADC are a) resolution b) conversion time c) reference voltage
(Vref).

1.1 Resolution
An ADC has an n bit resolution where n can be 8, 10, 16, 0r even 24 bits. The higher resolution
ADC provides a smaller step size, where step size is smallest change that can be discerned by an ADC.
This is shown in Table 8.1. Although the resolution for ADC chip is designed at the time of its design
and cannot be changed, we can control the step size with the help of reference voltage (Vref).

Electronics & Telecommunication Engineering


Page 30
ISB&M COE

n - bit Number of steps Step Size (mV)

8 256 5/256 = 19.53

10 1024 5/1024 = 4.88

12 4096 5/4096 = 1.2

16 65536 5/65536 = 0.076

Table 8.1: Resolution verses step size for ADC.


1.2 Conversion time
Conversion time is defined as the time it takes the ADC to convert the analog input to digital
(binary) number. The conversion time is dictated by the clock source connected to the ADC in addition
to the method used for data conversion and technology used in the fabrication of the ADC chip.
In addition to conversion time, acquisition time is another major factor in judging an ADC. Acquisition
time is defined as the time it takes to sample the analog voltage using sample and hold circuit. Sampled
analog input is applied to actual conversion unit of ADC.
In some of the ADCs, conversion time doesn’t contain the acquisition time but specified separately.
Therefore effective conversion time is addition of specified conversion time and specified acquisition
time.

1.3 Reference Voltage (Vref)


Vref is an input voltae used for the reference voltage. The voltage connected to this pin, along
with resolution of the ADC chip, gives us the step size.
step size = Vref / 2n where n= no. of bits
For example if the analog input range needs to be 0 to 3 Volts, Vref is connected to 3 Volts. That
gives 3V/1024 = 2.92 mV step size for 10-bit ADC.
Vref (V) Vin (V) Step Size (mV)
5.00 0 to 5 5/1024 = 4.88
2.56 0 to 2.56 2.56/1024 = 2.5
1.024 0 to 1.024 1.024/1024 = 1
Table 8.1: Relation between Vref, Vin and step size

2. 10-Bit Analog-To-Digital Converter (A/D) Module of PIC uC


The Analog-to-Digital (A/D) converter module has 10 inputs for the 28-pin devices and 13 for the
40/44-pin devices. This module allows conversion of an analog input signal to a corresponding 10-bit
digital number.

Electronics & Telecommunication Engineering


Page 31
ISB&M COE

2.2 Pin Description

Signal Pin No. Symbol

Channel 0 (AN0) 2 RA0/AN0

Channel 1 (AN1) 3 RA1/AN1

Channel 2 (AN2) 4 RA2/AN2/Vref-/CVref

Channel 3 (AN3) 5 RA3/AN3/Vref+

Channel 4 (AN4) 7 RA5/AN4/SS/HLVDIN/C2OUT

Channel 5 (AN5) 8 RE0/AN5/CK1SPP

Channel 6 (AN6) 9 RE1/AN6/CK2SPP

Channel 7 (AN7) 10 RE2/AN7/OESPP

Channel 8 (AN8) 35 RB2/AN8/INT2/VMO

Channel 9 (AN9) 36 RB3/AN9/VPO

Channel 10 (AN10) 34 RB1/AN10/INT1/SCK/SCL

Channel 11 (AN11) 37 RB4/AN11/KBIO/CSSPP

Channel 12 (AN12) 33 RB0/AN12/INT0/FLT0/SDI/SDA

2.3 ADC Register Map:


SFR Description Access Reset Value Address

ADCON0 A/D Control Register 0 Read/Write 0x00 0xFC2

ADCON1 A/D Control Register 1 Read/Write 0x00 0xFC1

ADCON2 A/D Control Register 2 Read/Write 0x00 0xFC0

ADRESH A/D Result High Register Read unknown 0xFC4

Electronics & Telecommunication Engineering


Page 32
ISB&M COE

ADRESL A/D Result Low Register Read unknown 0xFC3

2.4 ADC Register Description

Bit No. Control Bit Description


Bit 7 - 6 Unimplemented Read as ‘0’
Bit 5 - 2 CHS3:CHS0 Analog Channel Select bits
0000 = Channel 0 (AN0) 0001 = Channel 1 (AN1)
0010 = Channel 2 (AN2) 0011 = Channel 3 (AN3)
0100 = Channel 4 (AN4) 0101 = Channel 5 (AN5)
0110 = Channel 6 (AN6) 0111 = Channel 7 (AN7)
1000 = Channel 8 (AN8) 1001 = Channel 9 (AN9)
1010 = Channel 10 (AN10) 1011 = Channel 11 (AN11)
1100 = Channel 12 (AN12) 1101 = Unimplemented
1110 = Unimplemented 1111 = Unimplemented
Bit 1 GO/DONE A/D Conversion Status bit
1 = A/D conversion in progress; 0 = A/D Idle

Bit 0 ADON A/D On bit


1 = A/D converter module is enabled
0 = A/D converter module is disabled

NOTE: Only highlighted bits are applicable to this exercise.

ADCON0 Register in our Program


bit7-6 This two bits are Unimplemented so we write this bit as 00
bit5-2 Analog input is connected to Channel 1 (AN1). so we have to write

3. A/D Control Register 1 (ADCON1)

Bit No. Control Bit Description


Bit 7 - 6 Unimplemented Read as ‘0’
Bit 5 VCFG0 Voltage Reference Configuration bit (VREF- source)
1 = VREF- (AN2); 0 = VSS
Bit 4 VCFG0 Voltage Reference Configuration bit (VREF+ source)
Electronics & Telecommunication Engineering
Page 33
ISB&M COE

1 = VREF+ (AN3); 0 = VDD


bit 3-0 PCFG3:PCFG0 A/D Port Configuration Control bits shown in table 8.3
1101 : Analog channel AN1
NOTE: Only highlighted bits are applicable to this exercise.

Table 8.3: PCFG3:PCFG0: A/D Port Configuration Control bits:

ADCON1 Register in our Program


Bit7-6 This two bits are Unimplemented so we write this bit as 00
Bit 5 In our application (VREF-) supply as 0 volt so we write this bit as 0.
Bit 4 In our application (VREF+) supply as 5 volt so we write this bit as 0.
Bit3-0 Here we are using only one analog channel AN1. Therefor we write this bit as PCFG3:PCFG0
- 1101.

Electronics & Telecommunication Engineering


Page 34
ISB&M COE

3. A/D Control Register 2 (ADCON2)

Bit No. Control Bit Description


Bit 7 ADFM A/D Result Format Select bit
1 = Right justified; 0 = Left justified

Bit 6 Un Unimplemented Read as ‘0’


Bit 5–3 ACQT2:ACQT0 A/D Acquisition Time Select bits
000=0 TAD 001=2 TAD 010=4 TAD 011 =6 TAD
100=8 TAD 101=12 TAD 110=16 TAD 111 =20 TAD
bit 2–0 ADCS2:ADCS0 A/D Conversion Clock Select bits
000=FOSC/2 001=FOSC/8 010=FOSC/32 011=FRC*
100=FOSC/4 101=FOSC/16 110=FOSC/64 111=FRC*
FRC* - clock derived from A/D RC oscillator

NOTE: Only highlighted bits are applicable to this exercise.

2.4.3.1 A/D Result Format Select bit (ADFM):


We need right justified data. Therefore ADFM = ‘1’. If you write
1 then result is right justified as shown below;

If you write 0 then result is left justified as shown below;

2.4.3.2 A/D Conversion Clock Select bits (ADCS2:ADCS0)

The A/D conversion time per bit is defined as TAD. The A/D conversion requires 11 TAD per 10-bit
conversion. The source of the A/D conversion clock is software selectable. There are seven possible
options for TAD as shown in table 8.4
For correct A/D conversions, the A/D conversion clock (TAD) must be as short as possible
but greater than the minimum TAD. Table 8.4 shows the resultant TAD times derived from the
Electronics & Telecommunication Engineering
Page 35
ISB&M COE

device operating frequencies and the A/D clock source selected.

TAD = 4 * Tosc where Tosc = 1/Fosc Minimum TAD = 0.7 us (to be


maintained as per datasheet)

Therefore for 10bit ADC


Typical conversion tim e = 11 TAD = 11 * 0.7 us = 7.7 us

AD Clock Sour ce (TAD) Maximum Device Frequency


Operation ADCS2:ADCS0 PIC18FXXXX
2 TOSC 000 2.86 MHz
4 TOSC 100 5.71 MHz
8 TOSC 001 11.43 MHz
16 TOSC 101 22.86 MHz
32 TOSC 010 45.71 MHz
64 TOSC 110 48.0 MHz
RC(3) x11 1.00 MHz
Table 8.4 TAD vs. DEVICE OPERATING FREQUENCIES

2.4.3.3 A/D Acquisition Time Select bits (ACQT2:ACQT0)


Figure 8.1 shows the acquisition time (TACQ) is depends on am plifier settling time, capacitor
charging time and temperature coefficient.
TACQ = TAMP + TC + TCOFF
Where
TAMP : Amplifier Settling Ti me = 0.2 us (Typical value) TC :
Holding Capacitor C harging Time
= -(CHOLD)(RIC + RSS + RS) ln(1/2048) µs
= -(25 pF) (1 kL + 2 kL + 2.5 kL) ln(0.0004883) µs (Typical value)
= 1.05 µs
TCOFF : Temperature Coefficient = (Temp – 25°C)(0.02 µs/°C)
= (85°C – 25°C)(0.02 µs/°C) (Typical temp)
= 1.2 µs

Electronics & Telecommunication Engineering


Page 36
ISB&M COE

Therefore minimum calculated acquisition time is


TACQ = 0.2 µs + 1.05 µs + 1.2 µs = 2.45 µs

Derived A/D acquisition time ≥ Calculated acquisition time TACQ


Derived A/D acquisition time = n * TAD
where n is depends on A/D Acquisition Time Select bits (ACQT2:ACQT0). So select A/D Acquisition
Time Select bits (ACQT2:ACQT0) such that the we meet above timings.

2.5 Calculations
a. For Fosc = 20MHz
Tosc = 1/20MHz = 50 ns
Selected ADC clock source ADCS2:ADCS0 = 110 ie Fosc/64

TAD = 64Tosc = 64 * 50 ns
TAD = 3.2 us which is much greater than minimum TAD = 0.7 us

Conversion Time = 11TAD = 11 * 3.2 us = 35.2 us

Electronics & Telecommunication Engineering


Page 37
ISB&M COE

Selected A/D Acquisition Time Select bits ACQT2:ACQT0 = 001 i.e n= 2 Derived A/D
acquisition time = n * TAD = 2 * TAD
= 2 * 3.2 us
= 6.4 us
Which is much greater than calculated acquisition time = 2.4 us

Effective conversion time = acquisition time + conversion time


= 35.2 us + 6.4 us
= 41.6 us
b. For Fosc = 48MHz
Tosc = 1/48MHz = 20.83 ns
Selected ADC clock source ADCS2:ADCS0 = 110 i.eFosc/64

TAD = 64Tosc = 64 * 20.83 ns


TAD = 1.33 us which is greater than minimum TAD = 0.7 us

Conversion Time = 11TAD = 11 * 1.3 us = 14.66 us

Selected A/D Acquisition Time Select bits ACQT2:ACQT0 = 001 i.e n= 2 Derived A/D
acquisition time = n * TAD = 2 * TAD
= 2 * 1.33 us
= 2.67 us
Which is greater than calculated acquisition time = 2.4 us

Effective conversion time = acquisition time + conversion time


= 14.66 us + 2.67 us
= 17.33us

Electronics & Telecommunication Engineering


Page 38
ISB&M COE

The following steps should be followed to perform an A/D conversion:


1. Configure the A/D module :
• Configure analog pins, voltage reference and digital I/O (ADCON1)
• Select A/D input channel (ADCON0)
• Select A/D acquisition time (ADCON2)
• Select A/D conversion clock (ADCON2)
• Turn on A/D module (ADCON0)
2. Configure A/D interrupt (if desired):
• Clear ADIF bit
• Set ADIE bit
• Set GIE bit
3. Wait the required acquisition time (if required).
4. Start conversion:
• Set GO/DONE bit (ADCON0 register)
5. Wait for A/D conversion to complete, by either:
• Polling for the GO/DONE bit to be cleared OR

• Waiting for the A/D interrupt


6. Read A/D Result registers (ADRESH: ADRESL); clear bit ADIF, if required.
7. For next conversion, go t o step 1 or step 2, as required. The A/D conversion time per bit is
defined as TAD. A minimum wait of 3 TAD is required before the next acquisition starts.

Electronics & Telecommunication Engineering


Page 39
ISB&M COE

5. Source Code

Description: This program will convert 8 channels using the MAX7651


and send the results to Serial Port 0

#include <reg51.h> //include MAX7651 register definitions


#include <stdio.h> //Standard I/O, Print() function.

#define NUMBER_OF_CHANNELS 8 //Convert 8 channels

void convert_all_channels(int* buffer); //Function declaration


int convert_channel(int adc_ch); //Function declaration

void main(void) //Begin Main()


{
int Adc_Results[NUMBER_OF_CHANNELS]; //Array to store conversion result
int i; //for loop counter

convert_all_channels(Adc_Results); //Convert all channels, Store results in


Adc_Results
Electronics & Telecommunication Engineering
Page 40
ISB&M COE

#ifndef MONITOR51 //Setup Serial Port


SCON = 0x50; //9600 Baud, 8N1, Xon, Xoff
TMOD |= 0x20;
TH1 = 0xFA;
TR1 = 1;
TI = 1;
PCON |= 0x80;
#endif

for (i=0; i < NUMBER_OF_CHANNELS; i++) //Display contents to Adc_Results


{
printf ("CH %d:%x ",i,Adc_Results[i]); //print the hex
}

printf("
channel 0 %x", convert_channel(0)); //Convert a single channel and display
printf("
channel 1 %x", convert_channel(1));
printf("
channel 2 %x", convert_channel(2));
printf("
channel 3 %x", convert_channel(3));
printf("
channel 4 %x", convert_channel(4));
printf("
channel 5 %x", convert_channel(5));
printf("
channel 6 %x", convert_channel(6));
printf("
channel 7 %x", convert_channel(7));

while(1); //End Program, Start infinite loop since there


is no OS
}
/*-------------------------------------------------------------------------
Function: convert_all_channels

Usage: The function will return 8 conversion results to an array.

Parameters: p_buffer, pointer to an 8 location array stores the conversion results

Return: Values are returned to the calling function using the function parameters

Electronics & Telecommunication Engineering


Page 41
ISB&M COE

/*-------------------------------------------------------------------------
Setup ADC in the MAX7651
--------------------------------------------------------------------------*/

sfr ADCON = 0xC5; //Define address of MAX7651 ADCON


sfr ADDAT1 = 0xC3; //Define address of MAX7651 ADDAT1
(8MSBs)
sfr ADDAT0 = 0xC2; //Define address of MAX7651 ADDAT0 (4LSBs)

void convert_all_channels(int* buffer);


--------------------------------------------------------------------------*/

#define NUMBER_OF_CHANNELS 8

void convert_all_channels(int* p_buffer) //pointer Buffer to return


{
int adc_ch;
int conv_val;

/*-----------------------------------------------
Convert all ADC channels
-----------------------------------------------*/

for (adc_ch = 0; adc_ch < NUMBER_OF_CHANNELS; adc_ch++) //for ADC


channels 1 to 7
{

/*-----------------------------------------------
Start a conversion and wait for it to complete.
-----------------------------------------------*/

ADCON = adc_ch; //Start conversion and select channel


while ((ADCON & 0x80) == 0); //wait for conversion to complete
conv_val = (ADDAT0 >> 4) | (ADDAT1 << 4); //Format the data in 12 bit format

*(p_buffer+adc_ch) = conv_val; //Write result back to calling function


} //End For
} //End function convert_all_channels()

/*-------------------------------------------------------------------------
Function: convert_channel
Copyright: Maxim Integrated
Target: MAX7651
Date: Feb 26, 2004
Electronics & Telecommunication Engineering
Page 42
ISB&M COE

Author: Maxim Integrated

Usage: The function will convert and return the result of a Channel.
Parameters: adc_ch, Select ADC channel to be converted.

Channels 0-7 = single ended channel 0-7.


Channels 8-11 = differential channel pairs {CH0,1}, {CH2,3}, {CH4,5}, {CH6,7}
Channel 12 = differential reference measurement {REF+,REF-}

Return: Function returns Integer with the conversion result

Function Declaration: int convert_channel(int adc_ch);


--------------------------------------------------------------------------*/

/*-------------------------------------------------------------------------
Setup ADC in the MAX7651
--------------------------------------------------------------------------*/

sfr ADCON = 0xC5; //Define address of MAX7651 ADCON


sfr ADDAT1 = 0xC3; //Define address of MAX7651 ADDAT1
(8MSBs)
sfr ADDAT0 = 0xC2; //Define address of MAX7651 ADDAT0 (4LSBs)

int convert_channel(int adc_ch)


{
int conv_val;

if (ADCON <0 || ADCON >12){ //Check for valid channel


return (-2048); //Using -FS for the error code
}

ADCON = adc_ch; //Select channel and Start conversion


while ((ADCON & 0x80) == 0); //Wait for the conversion to complete

conv_val = (ADDAT0 >> 4) | (ADDAT1 << 4); //Format the data in 12 bit
format

return (conv_val); //Return result back to calling


function
} //End function convert_chan

OUTPUT

Electronics & Telecommunication Engineering


Page 43
ISB&M COE

EXPERIMENT NO: 08
TITLE: Generation of PWM Signal

PROBLEM STATEMENT:
Interface DC Motor (9V – 12V ; 200 – 300 rpm) to PIC microcontroller. Write a program
in Embedded C to control the speed of DC motor using on-chip PWM Module of PIC
Microcontroller.

OBJECTIVE:

i. To understand the working of PWM.


ii. To study the on-chip CCP Module (PWM section) of PIC Microcontroller.

iii. To interface DC motor, via Driver IC L293D, to PIC Microcontroller


iv. Apply the PWM signal to control the speed of DC Motor

S/W PACKAGES AND H/W USED:

MPLAB IDE, C18 Compiler, ExplorePIC Development Board, DC Motor, CRO

THEORY:
j. PWM Technique:

k. CCP Module of PIC uC


Depending upon the device selected there are 1 – 4 CCP (Capture/Compare/PWM)
modules in PIC microcontroller. Each module contains a 16-bit register, which can operate as a
16-bit Capture register, a 16-bit Compare register or a PWM Master/Slave Duty Cycle register.

Each Capture/Compare/PWM module is associated with a control register (generically,


CCPxCON) and a data register (CCPRx). The data register, in turn, is comprised of two 8-bit
registers: CCPRxL (low byte) and CCPRxH (high byte). All registers are both readable and
writable.
The CCP modules utilize Timers 1, 2 or 3, depending on the mode selected. Timer1 and
Timer3 are available to modules in Capture or Compare modes, while Timer2 is available for
modules in PWM mode.
The pin assignment for CCP2 (Capture input, Compare and PWM output) can change,
based on device configuration. The CCP2MX Configuration bit determines which pin CCP2 is
multiplexed to. By default, it is assigned to RC1 (CCP2MX = 1). If the Configuration bit is
cleared, CCP2 is multiplexed with RB3. Changing the pin assignment of CCP2 does not
Electronics & Telecommunication Engineering
Page 44
ISB&M COE

automatically change any requirements for configuring the port pin. Users must always verify
that the appropriate TRIS register is configured correctly for CCP2 operation, regardless of
where it is located.
4. Capture Mode Applications
Event arrival time recording
Period measurement
Pulse-width measurement
Interrupt generation
Event counting
Time reference
Duty cycle measurement

5. Compare Mode Applications


Generate …
o Single pulse o
Train of pulses
o Periodic waveform
Start ADC conversion
Time reference

3. PWM Mode of CCP Module


In Pulse-Width Modulation (PWM) mode, the CCPx pin produces up to a 10-bit
resolution PWM output. Since the CCP2 pin is multiplexed with a PORTB or PORTC data latch,
the appropriate TRIS bit must be cleared to make the CCP2 pin an output. A PWM output has a
time base (period) and a time that the output stays high (duty cycle). The frequency of the PWM
is the inverse of the period (1/period).
The simplified block diagram of the CCP1 configured to generate PWM is shown in
Figure 9.1, with example waveforms in Figure 9. 2. The block diagram for CCP2 is similar to
CCP1. It can be seen that Figure 9.1 contains CCPR1L, Timer 2, comparator and the PR2
register working together. Although not shown, Timer 2 is still driven from the on-chip
oscillator, through its own prescaler. The comparator output drives an R–S flip-flop. When the
value in PR2 equals Timer 2, then the comparator clears the timer and sets the flip-flop, whose
output goes high. This is seen in Figure 9.2. This action sets the PWM period.

Having established the PWM period, let us consider how the pulse width is determined.
A second Compare register arrangement is introduced to do this. This is made up of the

Electronics & Telecommunication Engineering


Page 45
ISB&M COE

CCPR1H register, plus a second comparator. As the logic of the diagram shows, every time this
comparator finds equal input values, it resets the output flip-flop, clearing the output to zero. It is
this comparator that determines the pulse width. Again, this is shown in Figure 9.2. To change
the pulse width, the programmer writes to the CCPR1L register, which acts as a buffer. Its value
is transferred to CCPR1H only when a PWM cycle is complete, to avoid output errors in the
process. The block diagram is made more complex because three of the registers are ‘stretched’,
to make them potentially 10-bit instead of 8-bit. This increases the resolution. CCPR1L uses two
bits of the CCP1CON register. CCPR1H isextended with an internal 2-bit latch, while the
extension to Timer 2 is as described in Note 1 of Figure 9.1
Because of these two extra bits, in its 10-bit version it is effectively clocked direct from the
internal oscillator signal, undivided. If the prescaler is used, then it acts on this frequency, not the
usual Fosc/4. Notice, however, that the PR2 register remains at eight bits. This means that the
PWM period has only an 8-bit equivalent resolution.

Figure 9.1 : PWM Block Diagram

Electronics & Telecommunication Engineering


Page 46
ISB&M COE

Figure 9.2: PWM output waveform

PWM Period and Duty Cycle

The PWM period T is determined by the interaction of the PR2 register and the eight bits of
Timer 2. It may be calculated as follows:
PWM Period = Tpwm = (PR2 + 1) x (Timer 2 input Clock)
PWM Period = Tpwm = (PR2 + 1) x (4 * Tosc * TMR2 Prescaler value) Therefore
to find the PR2 for desired PWM Period

Above equation can be represented in terms of frequency as below.

Where,
Timer 2 input Clock = 4 * Tosc * TMR2 Prescaler value
Fosc = Input Crystal Oscillator Frequency
Tosc = input clock period = 1/Fosc
Fpwm = PWM frequency
Tpwm = PWM Period = 1/Fpwm

The PWM pulse width Ton is determined by the interaction of the extended CCPR1H register
Electronics & Telecommunication Engineering
Page 47
ISB&M COE

(all 10 bits of it) and the extended (10-bit) Timer 2. It may be calculated as follows:

Ton = (Pulse width register) x (PWM Timer input clock period)


Where, ‘PWM timer input clock period’ is the period of the clock input to the extended Timer 2
and ‘pulse width register’ is the value in the extended CCPR1L register.

Hence,
Ton = (CCPR1L: CCP1CON<5:4>) x (Tosc * TMR2 Prescaler value)
Note that there is not here a factor of four with the Tosc term, as we are using 10-bits of Timer 2.
Rearranging the above equation, to find value of pulse width
register

Above equation can be represented in terms of frequency and percentage Duty cycle
(%DCpwm) as below.

Note: Choose TMR2PREto ensure that PR2 is in the range of 0 to 255 for the desiredPWM
frequency and CCPR1L:CCP1CON<5:4> is in the range of 0 to 1023 for the desired PWM duty
cycle.

Electronics & Telecommunication Engineering


Page 48
ISB&M COE

1.1.5 Pin Description


Signal Pin No. Symbol

CCP2(1) 16 RC1/T1OSI/CCP2(1)/UOE
CCP1 17 RC2/CCP1/P1A

CCP2(1) 36 RB3/AN9/CCP2(1)/VPO
Note 1: RB3 is the alternate pin for CCP2 multiplexing.

3.3 PWM Register Map:

SFR Description Access Reset Value Address

CCP1CON Standard CCP1 Control Reg. Read/Write 0x00 0xFBD

CCPR1L CCP1 Register low byte Read/Write unknown 0xFBE

CCPR1H CCP1 Register high byte No access unknown 0xFBF

CCP2CON Standard CCP2 Control Reg. Read/Write 0x00 0xFBA

CCPR2L CCP2 Register high byte Read/Write unknown 0xFBB

CCPR2H CCP2 Register high byte No access unknown 0XFBC

T2CON Timer 2 Control Register Read/Write 0x00 0xFCA

TMR2 Timer 2 Register Read/Write 0x00 0xFCC

PR2 Timer 2 Period register Read/Write 0xFF 0xFCB

3.4 PWM Mode Register Description

3.4.1 Standard CPPx Control Register (CCPxCON – CCP1CON/CCP2CON)

Bit No. Control Bit Description


Bit 7 - 6 Unimplemented Read as ‘0’
Electronics & Telecommunication Engineering
Page 49
ISB&M COE

Bit 5 - 4 DCxB1:DCxB0 PWM Duty Cycle Bit 1 and Bit 0 for CCPx Module
Unused in Capture mode & Compare mode:
PWM mode: These bits are the two LSbs (bit 1 and bit
0) of the 10-bit PWM duty cycle. The eight MSbs of the
duty cycle are found in CCPR1L.
Bit 3 - 0 CCPxM3:CCPxM0 CCPx Module Mode Select bits
0000 = CCP disabled (resets CCPx module)
0001 = Reserved
0010 = Compare mode: toggle output on match (CCPxIF
bit is set)
0011 = Reserved
0100 = Capture mode: every falling edge
0101 = Capture mode: every rising edge
0110 = Capture mode: every 4th rising edge
0111 = Capture mode: every 16th rising edge
1000 = Compare mode: initialize CCPx pin low; on

3.4.2 Timer 2 Control Register

Bit No. Control Bit Description


Bit 7 Unimplemented Read as ‘0’

Bit 6 - 3 T2OUTPS3:T2OUTPS0: Timer2 Output Postscaler Select bits (1:1 to 1:16)


0000 = 1:1 Postscaler
0001 = 1:2 Postscaler

Electronics & Telecommunication Engineering


Page 50
ISB&M COE


1111 = 1:16 Postscaler

Bit 2 TMR2ON: Timer2 On bit


1 = Timer2 is on, 0 = Timer2 is off

Bit 1 - 0 T2CKPS1:T2CKPS0 Timer2 Clock Prescaler Select bits


00 = Prescaler is 1:1
01 = Prescaler is 1:4
1x = Prescaler is 1:16

4. Timer 2 Module
The Timer2 module timer incorporates the following features:
• 8-bit timer and period registers (TMR2 and PR2, respectively)
• Readable and writable (both registers)
• Software programmable prescaler (1:1, 1:4 and 1:16)
• Software programmable Postscaler (1:1 through 1:16)
• Interrupt on TMR2 to PR2 match
• Optional use as the shift clock for the MSSP module
The module is controlled through the T2CON register which enables or disables the timer and
configures the prescaler and Postscaler. Timer2 can be shut off by clearing control bit, TMR2ON
(T2CON<2>), to minimize power consumption. A simplified block diagram of the module is
shown in Figure9.3.

4.1 Timer2 Operation


Electronics & Telecommunication Engineering
Page 51
ISB&M COE

In normal operation, TMR2 is incremented from 00h on each clock (FOSC/4). A 2-bit
counter/prescaler on the clock input gives direct input, divide-by-4 and divides-by- 16 prescale
options. These are selected by the prescaler control bits, T2CKPS1:T2CKPS0 (T2CON<1:0>).
The value of TMR2 is compared to that of the period register, PR2, on each clock cycle. When
the two values match, the comparator generates a match signal as the timer output. This signal
also resets the value of TMR2 to 00h on the next cycle and drives the output counter/ Postscaler.

The TMR2 and PR2 registers are both directly readable and writable. The TMR2 register
is cleared on any device Reset, while the PR2 register initializes at FFh. TMR2 is not cleared
when T2CON is written. Both the prescaler and postscaler counters are cleared on the following
events:
a write to the TMR2 register
a write to the T2CON register
any device Reset (Power-on Reset, MCLR Reset, WDT Reset or Brown-out)

3. Timer2 Interrupt
Timer2 also can generate an optional device interrupt. The Timer2 output signal (TMR2
to PR2 match) provides the input for the 4-bit output counter/postscaler. This counter generates
the TMR2 match interrupt flag which is latched in TMR2IF (PIR1<1>). The interrupt is enabled
by setting the TMR2 Match Interrupt Enable bit, TMR2IE (PIE1<1>). A range of 16 postscale
options (from 1:1 through 1:16 inclusive) can be selected with the postscaler control bits,
T2OUTPS3:T2OUTPS0 (T2CON<6:3>).

4.3 TMR2 Output


The unscaled output of TMR2 is available primarily to the CCP modules, where it is used
as a time base for operations in PWM mode. Timer2 can be optionally used as the shift clock
source for the MSSP module operating in SPI mode.

Electronics & Telecommunication Engineering


Page 52
ISB&M COE

Electronics & Telecommunication Engineering


Page 53
ISB&M COE

Electronics & Telecommunication Engineering


Page 54
ISB&M COE

Electronics & Telecommunication Engineering


Page 55
ISB&M COE

Electronics & Telecommunication Engineering


Page 56
6. Quadruple half H Drivers (L293D)
The L293D is quadruple high-current half-H drivers. The L293D is designed to provide
bidirectional drive currents of up to 600-mA at voltages from 4.5 V to 36 V. The device is designed
to drive inductive loads such as relays, solenoids, dc and bipolar stepping motors, as well as other
high-current/high-voltage loads in positive-supply applications. All inputs are TTL compatible. Each
output is a complete totem-pole drive circuit, with a Darlington transistor sink and a pseudo-
Darlington source.

Drivers are enabled in pairs, with drivers 1 and 2 enabled by 1,2EN and drivers 3 and 4
enabled by 3,4EN as shown in pin diagram and function table. When an enable input is high, the
associated drivers are enabled, and their outputs are active and in phase with their inputs. When the
enable input is low, those drivers are disabled, and their outputs are off and in the high-impedance
state. With the proper data inputs, each pair of drivers forms a full-H (or bridge) reversible drive
suitable for solenoid or motor applications.

Electronics & Telecommunication Engineering


Page 57
8. Algorithm
The following steps should be taken when configuring the CCP module for PWM operation:
1. Set the PWM period by writing to the PR2register.
2. Set the PWM duty cycle by writing to the CCPR1L register and
CCP1CON<5:4> bits.
3. Make the CCP1 pin an output by clearing the appropriate TRIS bit.
4. Make the RC6 and RC7 as output to TURN ON the Motor.
5. Set the TMR2 prescale value, and then enable Timer2 by writing to T2CON.
6. Configure the CCP1 module for PWM operation.

Electronics & Telecommunication Engineering


Page 58

You might also like